text
stringlengths
54
60.6k
<commit_before>/** * Copyright (C) 2015 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <gtest/gtest.h> #include <repo/repo_controller.h> #include <repo/error_codes.h> #include "../repo_test_database_info.h" #include "../repo_test_fileservice_info.h" #include "../repo_test_utils.h" using namespace repo; static std::shared_ptr<RepoController> getController() { static std::shared_ptr<RepoController> controller = std::make_shared<RepoController>(); return controller; } TEST(RepoControllerTest, CommitScene){ auto controller = getController(); auto token = initController(controller.get()); //Try to commit a scene without setting db/project name uint8_t errCode; auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode); EXPECT_EQ(0, errCode); EXPECT_FALSE(controller->commitScene(token, scene)); EXPECT_FALSE(scene->isRevisioned()); //Trying to commit a scene with empty db and project name should also fail scene->setDatabaseAndProjectName("", ""); EXPECT_FALSE(controller->commitScene(token, scene)); EXPECT_FALSE(scene->isRevisioned()); scene->setDatabaseAndProjectName("balh", ""); EXPECT_FALSE(controller->commitScene(token, scene)); EXPECT_FALSE(scene->isRevisioned()); scene->setDatabaseAndProjectName("", "blah"); EXPECT_FALSE(controller->commitScene(token, scene)); EXPECT_FALSE(scene->isRevisioned()); //Setting the db name and project name should allow commit successfully scene->setDatabaseAndProjectName("commitSceneTest", "commitCube"); EXPECT_TRUE(controller->commitScene(token, scene)); EXPECT_TRUE(scene->isRevisioned()); EXPECT_TRUE(projectExists("commitSceneTest", "commitCube")); EXPECT_EQ(scene->getOwner(), REPO_GTEST_DBUSER); auto scene2 = controller->loadSceneFromFile(getDataPath(simpleModel), errCode); std::string owner = "dog"; EXPECT_EQ(errCode, 0); scene2->setDatabaseAndProjectName("commitSceneTest", "commitCube2"); EXPECT_TRUE(controller->commitScene(token, scene2, owner)); EXPECT_TRUE(scene2->isRevisioned()); EXPECT_TRUE(projectExists("commitSceneTest", "commitCube2")); EXPECT_EQ(scene2->getOwner(), owner); //null pointer checks EXPECT_FALSE(controller->commitScene(token, nullptr)); EXPECT_FALSE(controller->commitScene(nullptr, scene)); } TEST(RepoControllerTest, LoadSceneFromFile){ auto controller = getController(); auto defaultG = core::model::RepoScene::GraphType::DEFAULT; auto optG = core::model::RepoScene::GraphType::OPTIMIZED; //standard import uint8_t errCode; auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode); ASSERT_TRUE(scene); EXPECT_EQ(errCode, 0); ASSERT_TRUE(scene->getRoot(defaultG)); ASSERT_TRUE(scene->getRoot(optG)); EXPECT_FALSE(scene->isMissingTexture()); EXPECT_FALSE(scene->isRevisioned()); EXPECT_TRUE(dynamic_cast<core::model::TransformationNode*>(scene->getRoot(defaultG))->isIdentity()); //Import the scene with no transformation reduction auto sceneNoReduction = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, false); EXPECT_EQ(errCode, 0); EXPECT_TRUE(sceneNoReduction); EXPECT_TRUE(sceneNoReduction->getRoot(defaultG)); EXPECT_TRUE(sceneNoReduction->getRoot(optG)); EXPECT_FALSE(sceneNoReduction->isMissingTexture()); //There should be more transformations in the non-reduced scene than the standard scene EXPECT_TRUE(sceneNoReduction->getAllTransformations(defaultG).size() > scene->getAllTransformations(defaultG).size()); //Import the scene with root trans rotated auto sceneRotated = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, true, true); EXPECT_EQ(errCode, 0); EXPECT_TRUE(sceneRotated); ASSERT_TRUE(sceneRotated->getRoot(defaultG)); EXPECT_TRUE(sceneRotated->getRoot(optG)); EXPECT_FALSE(sceneRotated->isMissingTexture()); //The root transformation should not be an identity core::model::TransformationNode *rootTrans = dynamic_cast<core::model::TransformationNode*>(sceneRotated->getRoot(defaultG)); EXPECT_FALSE(rootTrans->isIdentity()); //Import the scene with non existant file auto sceneNoFile = controller->loadSceneFromFile("thisFileDoesntExist.obj", errCode); EXPECT_EQ(errCode, REPOERR_MODEL_FILE_READ); EXPECT_FALSE(sceneNoFile); //Import the scene with bad Extension auto sceneBadExt = controller->loadSceneFromFile(getDataPath(badExtensionFile), errCode); EXPECT_EQ(errCode, REPOERR_FILE_TYPE_NOT_SUPPORTED); EXPECT_FALSE(sceneBadExt); //Import the scene with texture but not found auto sceneNoTex = controller->loadSceneFromFile(getDataPath(texturedModel), errCode); EXPECT_EQ(errCode, 0); EXPECT_TRUE(sceneNoTex); EXPECT_TRUE(sceneNoTex->getRoot(defaultG)); EXPECT_TRUE(sceneNoTex->getRoot(optG)); EXPECT_TRUE(sceneNoTex->isMissingTexture()); //Import the scene with texture but not found auto sceneTex = controller->loadSceneFromFile(getDataPath(texturedModel2), errCode); EXPECT_EQ(errCode, 0); EXPECT_TRUE(sceneTex); EXPECT_TRUE(sceneTex->getRoot(defaultG)); EXPECT_TRUE(sceneTex->getRoot(optG)); EXPECT_FALSE(sceneTex->isMissingTexture()); //FIXME: need to test with change of config, but this is probably not trival. } <commit_msg>revert back to calling the method again.<commit_after>/** * Copyright (C) 2015 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <gtest/gtest.h> #include <repo/repo_controller.h> #include <repo/error_codes.h> #include "../repo_test_database_info.h" #include "../repo_test_fileservice_info.h" #include "../repo_test_utils.h" using namespace repo; static std::shared_ptr<RepoController> getController() { static std::shared_ptr<RepoController> controller = std::make_shared<RepoController>(); return controller; } TEST(RepoControllerTest, CommitScene){ auto controller = getController(); auto token = initController(controller.get()); //Try to commit a scene without setting db/project name uint8_t errCode; auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode); EXPECT_EQ(0, errCode); EXPECT_FALSE(controller->commitScene(token, scene)); EXPECT_FALSE(scene->isRevisioned()); //Trying to commit a scene with empty db and project name should also fail scene->setDatabaseAndProjectName("", ""); EXPECT_FALSE(controller->commitScene(token, scene)); EXPECT_FALSE(scene->isRevisioned()); scene->setDatabaseAndProjectName("balh", ""); EXPECT_FALSE(controller->commitScene(token, scene)); EXPECT_FALSE(scene->isRevisioned()); scene->setDatabaseAndProjectName("", "blah"); EXPECT_FALSE(controller->commitScene(token, scene)); EXPECT_FALSE(scene->isRevisioned()); //Setting the db name and project name should allow commit successfully scene->setDatabaseAndProjectName("commitSceneTest", "commitCube"); EXPECT_TRUE(controller->commitScene(initController(controller.get()), scene)); EXPECT_TRUE(scene->isRevisioned()); EXPECT_TRUE(projectExists("commitSceneTest", "commitCube")); EXPECT_EQ(scene->getOwner(), REPO_GTEST_DBUSER); auto scene2 = controller->loadSceneFromFile(getDataPath(simpleModel), errCode); std::string owner = "dog"; EXPECT_EQ(errCode, 0); scene2->setDatabaseAndProjectName("commitSceneTest", "commitCube2"); EXPECT_TRUE(controller->commitScene(initController(controller.get()), scene2, owner)); EXPECT_TRUE(scene2->isRevisioned()); EXPECT_TRUE(projectExists("commitSceneTest", "commitCube2")); EXPECT_EQ(scene2->getOwner(), owner); //null pointer checks EXPECT_FALSE(controller->commitScene(token, nullptr)); EXPECT_FALSE(controller->commitScene(nullptr, scene)); } TEST(RepoControllerTest, LoadSceneFromFile){ auto controller = getController(); auto defaultG = core::model::RepoScene::GraphType::DEFAULT; auto optG = core::model::RepoScene::GraphType::OPTIMIZED; //standard import uint8_t errCode; auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode); ASSERT_TRUE(scene); EXPECT_EQ(errCode, 0); ASSERT_TRUE(scene->getRoot(defaultG)); ASSERT_TRUE(scene->getRoot(optG)); EXPECT_FALSE(scene->isMissingTexture()); EXPECT_FALSE(scene->isRevisioned()); EXPECT_TRUE(dynamic_cast<core::model::TransformationNode*>(scene->getRoot(defaultG))->isIdentity()); //Import the scene with no transformation reduction auto sceneNoReduction = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, false); EXPECT_EQ(errCode, 0); EXPECT_TRUE(sceneNoReduction); EXPECT_TRUE(sceneNoReduction->getRoot(defaultG)); EXPECT_TRUE(sceneNoReduction->getRoot(optG)); EXPECT_FALSE(sceneNoReduction->isMissingTexture()); //There should be more transformations in the non-reduced scene than the standard scene EXPECT_TRUE(sceneNoReduction->getAllTransformations(defaultG).size() > scene->getAllTransformations(defaultG).size()); //Import the scene with root trans rotated auto sceneRotated = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, true, true); EXPECT_EQ(errCode, 0); EXPECT_TRUE(sceneRotated); ASSERT_TRUE(sceneRotated->getRoot(defaultG)); EXPECT_TRUE(sceneRotated->getRoot(optG)); EXPECT_FALSE(sceneRotated->isMissingTexture()); //The root transformation should not be an identity core::model::TransformationNode *rootTrans = dynamic_cast<core::model::TransformationNode*>(sceneRotated->getRoot(defaultG)); EXPECT_FALSE(rootTrans->isIdentity()); //Import the scene with non existant file auto sceneNoFile = controller->loadSceneFromFile("thisFileDoesntExist.obj", errCode); EXPECT_EQ(errCode, REPOERR_MODEL_FILE_READ); EXPECT_FALSE(sceneNoFile); //Import the scene with bad Extension auto sceneBadExt = controller->loadSceneFromFile(getDataPath(badExtensionFile), errCode); EXPECT_EQ(errCode, REPOERR_FILE_TYPE_NOT_SUPPORTED); EXPECT_FALSE(sceneBadExt); //Import the scene with texture but not found auto sceneNoTex = controller->loadSceneFromFile(getDataPath(texturedModel), errCode); EXPECT_EQ(errCode, 0); EXPECT_TRUE(sceneNoTex); EXPECT_TRUE(sceneNoTex->getRoot(defaultG)); EXPECT_TRUE(sceneNoTex->getRoot(optG)); EXPECT_TRUE(sceneNoTex->isMissingTexture()); //Import the scene with texture but not found auto sceneTex = controller->loadSceneFromFile(getDataPath(texturedModel2), errCode); EXPECT_EQ(errCode, 0); EXPECT_TRUE(sceneTex); EXPECT_TRUE(sceneTex->getRoot(defaultG)); EXPECT_TRUE(sceneTex->getRoot(optG)); EXPECT_FALSE(sceneTex->isMissingTexture()); //FIXME: need to test with change of config, but this is probably not trival. } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved */ #ifndef _Stroika_Foundation_Characters_String_inl_ #define _Stroika_Foundation_Characters_String_inl_ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" namespace Stroika { namespace Foundation { namespace Characters { template <> inline size_t C_String::Length (const char* p) { RequireNotNull (p); return ::strlen (p); } template <> inline size_t C_String::Length (const wchar_t* p) { RequireNotNull (p); return ::wcslen (p); } // class String::_Rep inline String::_Rep::_Rep () { } inline String::_Rep::~_Rep () { } inline void String::_Rep::CopyTo (Character* bufFrom, Character* bufTo) const { RequireNotNull (bufFrom); Require (bufFrom + GetLength () >= bufTo); size_t nChars = GetLength (); (void)::memcpy (bufFrom, Peek (), nChars * sizeof (Character)); } inline void String::_Rep::CopyTo (wchar_t* bufFrom, wchar_t* bufTo) const { RequireNotNull (bufFrom); Require (bufFrom + GetLength () >= bufTo); size_t nChars = GetLength (); (void)::memcpy (bufFrom, Peek (), nChars * sizeof (Character)); } // class String inline String::String (const String& from) : _fRep (from._fRep) { } inline String& String::operator= (const String& newString) { _fRep = newString._fRep; return (*this); } inline String::~String () { } inline String::_Rep* String::Clone_ (const _Rep& rep) { return (rep.Clone ()); } inline void String::CopyTo (Character* bufFrom, Character* bufTo) const { RequireNotNull (bufFrom); Require (bufFrom + GetLength () >= bufTo); _fRep->CopyTo (bufFrom, bufTo); } inline void String::CopyTo (wchar_t* bufFrom, wchar_t* bufTo) const { RequireNotNull (bufFrom); Require (bufFrom + GetLength () >= bufTo); _fRep->CopyTo (bufFrom, bufTo); } inline size_t String::GetLength () const { return (_fRep->GetLength ()); } inline bool String::empty () const { return _fRep->GetLength () == 0; } inline void String::clear () { *this = String (); } inline void String::InsertAt (Character c, size_t at) { InsertAt (&c, &c + 1, at); } inline void String::InsertAt (const String& s, size_t at) { // NB: I don't THINK we need be careful if s.fRep == this->fRep because when we first derefence this->fRep it will force a CLONE, so OUR fRep will be unique // And no need to worry about lifetime of 'p' because we don't allow changes to 's' from two different threads at a time, and the rep would rep if accessed from // another thread could only change that other envelopes copy pair<const Character*, const Character*> d = s._fRep->GetData (); InsertAt (d.first, d.second, at); } inline void String::InsertAt (const wchar_t* from, const wchar_t* to, size_t at) { InsertAt (reinterpret_cast<const Character*> (from), reinterpret_cast<const Character*> (to), at); } inline String& String::operator+= (Character appendage) { InsertAt (appendage, GetLength ()); return (*this); } inline String& String::operator+= (const String& appendage) { InsertAt (appendage, GetLength ()); return (*this); } inline Character String::operator[] (size_t i) const { Require (i >= 0); Require (i < GetLength ()); return (_fRep->GetAt (i)); } template <> inline void String::As (wstring* into) const { RequireNotNull (into); size_t n = GetLength (); const Character* cp = _fRep->Peek (); Assert (sizeof (Character) == sizeof (wchar_t)); // going to want to clean this up!!! --LGP 2011-09-01 const wchar_t* wcp = (const wchar_t*)cp; into->assign (wcp, wcp + n); } template <> inline wstring String::As () const { wstring r; As (&r); return r; } template <> inline const wchar_t* String::As () const { // I'm not sure of the Peek() semantics, so I'm not sure this is right, but document Peek() better so this is safe!!! -- LGP 2011-09-01 return (const wchar_t*)_fRep->Peek (); } template <> inline const Character* String::As () const { // I'm not sure of the Peek() semantics, so I'm not sure this is right, but document Peek() better so this is safe!!! -- LGP 2011-09-01 return (const Character*)_fRep->Peek (); } template <> inline string String::AsUTF8 () const { string r; AsUTF8 (&r); return r; } inline std::string String::AsUTF8 () const { return AsUTF8<std::string> (); } inline void String::AsUTF8 (std::string* into) const { AsUTF8<std::string> (into); } template <> inline string String::AsASCII () const { string r; AsASCII (&r); return r; } inline std::string String::AsASCII () const { return AsASCII<std::string> (); } inline void String::AsASCII (std::string* into) const { AsASCII<std::string> (into); } inline size_t String::length () const { return GetLength (); } inline size_t String::size () const { return GetLength (); } inline const wchar_t* String::data () const { return As<const wchar_t*> (); } inline size_t String::find (wchar_t c) const { return IndexOf (c); } inline size_t String::rfind (wchar_t c) const { return RIndexOf (c); } inline int String::Compare (const String& rhs, CompareOptions co) const { pair<const Character*, const Character*> d = rhs._fRep->GetData (); return _fRep->Compare (d.first, d.second, co); } inline int String::Compare (const Character* rhsStart, const Character* rhsEnd, CompareOptions co) const { return _fRep->Compare (rhsStart, rhsEnd, co); } inline int String::Compare (const wchar_t* rhsStart, const wchar_t* rhsEnd, CompareOptions co) const { static_assert (sizeof (Character) == sizeof (wchar_t), "Character and wchar_t must be same size"); return _fRep->Compare (reinterpret_cast<const Character*> (rhsStart), reinterpret_cast<const Character*> (rhsEnd), co); } inline bool operator== (const String& lhs, const String& rhs) { if (lhs._fRep == rhs._fRep) { return (true); } pair<const Character*, const Character*> d = rhs._fRep->GetData (); return lhs.Compare (d.first, d.second, String::eWithCase_CO) == 0; } inline bool operator== (const wchar_t* lhs, const String& rhs) { RequireNotNull (lhs); return rhs.Compare (lhs, lhs + ::wcslen (lhs), String::eWithCase_CO) == 0; } inline bool operator== (const String& lhs, const wchar_t* rhs) { RequireNotNull (rhs); return lhs.Compare (rhs, rhs + ::wcslen (rhs), String::eWithCase_CO) == 0; } inline bool operator< (const String& lhs, const String& rhs) { if (lhs._fRep == rhs._fRep) { return (false); } pair<const Character*, const Character*> d = rhs._fRep->GetData (); return lhs.Compare (d.first, d.second, String::eWithCase_CO) < 0; } inline bool operator< (const wchar_t* lhs, const String& rhs) { RequireNotNull (lhs); return rhs.Compare (lhs, lhs + ::wcslen (lhs), String::eWithCase_CO) >= 0; } inline bool operator< (const String& lhs, const wchar_t* rhs) { RequireNotNull (rhs); return lhs.Compare (rhs, rhs + ::wcslen (rhs), String::eWithCase_CO) < 0; } inline bool operator<= (const String& lhs, const String& rhs) { if (lhs._fRep == rhs._fRep) { return (false); } pair<const Character*, const Character*> d = rhs._fRep->GetData (); return lhs.Compare (d.first, d.second, String::eWithCase_CO) <= 0; } inline bool operator<= (const wchar_t* lhs, const String& rhs) { RequireNotNull (lhs); return rhs.Compare (lhs, lhs + ::wcslen (lhs), String::eWithCase_CO) > 0; } inline bool operator<= (const String& lhs, const wchar_t* rhs) { RequireNotNull (rhs); return lhs.Compare (rhs, rhs + ::wcslen (rhs), String::eWithCase_CO) <= 0; } inline bool operator!= (const String& lhs, const String& rhs) { return (bool (not (lhs == rhs))); } inline bool operator!= (const wchar_t* lhs, const String& rhs) { return (bool (not (lhs == rhs))); } inline bool operator!= (const String& lhs, const wchar_t* rhs) { return (bool (not (lhs == rhs))); } inline bool operator> (const String& lhs, const String& rhs) { return (bool (not (lhs <= rhs))); } inline bool operator> (const wchar_t* lhs, const String& rhs) { return (bool (not (lhs <= rhs))); } inline bool operator> (const String& lhs, const wchar_t* rhs) { return (bool (not (lhs <= rhs))); } inline bool operator>= (const String& lhs, const String& rhs) { return (bool (not (lhs < rhs))); } inline bool operator>= (const wchar_t* lhs, const String& rhs) { return (bool (not (lhs < rhs))); } inline bool operator>= (const String& lhs, const wchar_t* rhs) { return (bool (not (lhs < rhs))); } #if 0 // class String_CharArray inline String_CharArray::String_CharArray (const String_CharArray& s) : String (s) { } inline String_CharArray& String_CharArray::operator= (const String_CharArray& s) { String::operator= (s); return (*this); } #endif // class String_BufferedArray inline String_BufferedArray::String_BufferedArray (const String_BufferedArray& s) : String (s) { } inline String_BufferedArray& String_BufferedArray::operator= (const String_BufferedArray& s) { String::operator= (s); return (*this); } // class String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly inline String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly::String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly (const String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly& s) : String (s) { } inline String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly& String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly::operator= (const String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly& s) { String::operator= (s); return (*this); } // class String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite inline String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite::String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite (const String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite& s) : String (s) { } inline String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite& String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite::operator= (const String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite& s) { String::operator= (s); return (*this); } } } } #endif // _Stroika_Foundation_Characters_String_inl_ <commit_msg>Include BlockAllocated.h in Strings.inl - though not directly used - because the BlockAllocation moduleneeds to be INITIALIZED before calls to teh Strings code is used, and the ModuleInit<> mechanism requires these #includes to get the ModuleInit<> stuff called at the right point<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved */ #ifndef _Stroika_Foundation_Characters_String_inl_ #define _Stroika_Foundation_Characters_String_inl_ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" #include "../Memory/BlockAllocated.h" // #include here because the CPP module depends on BlockAllocated, and this #include needed assure ModuleInit<> proper order namespace Stroika { namespace Foundation { namespace Characters { template <> inline size_t C_String::Length (const char* p) { RequireNotNull (p); return ::strlen (p); } template <> inline size_t C_String::Length (const wchar_t* p) { RequireNotNull (p); return ::wcslen (p); } // class String::_Rep inline String::_Rep::_Rep () { } inline String::_Rep::~_Rep () { } inline void String::_Rep::CopyTo (Character* bufFrom, Character* bufTo) const { RequireNotNull (bufFrom); Require (bufFrom + GetLength () >= bufTo); size_t nChars = GetLength (); (void)::memcpy (bufFrom, Peek (), nChars * sizeof (Character)); } inline void String::_Rep::CopyTo (wchar_t* bufFrom, wchar_t* bufTo) const { RequireNotNull (bufFrom); Require (bufFrom + GetLength () >= bufTo); size_t nChars = GetLength (); (void)::memcpy (bufFrom, Peek (), nChars * sizeof (Character)); } // class String inline String::String (const String& from) : _fRep (from._fRep) { } inline String& String::operator= (const String& newString) { _fRep = newString._fRep; return (*this); } inline String::~String () { } inline String::_Rep* String::Clone_ (const _Rep& rep) { return (rep.Clone ()); } inline void String::CopyTo (Character* bufFrom, Character* bufTo) const { RequireNotNull (bufFrom); Require (bufFrom + GetLength () >= bufTo); _fRep->CopyTo (bufFrom, bufTo); } inline void String::CopyTo (wchar_t* bufFrom, wchar_t* bufTo) const { RequireNotNull (bufFrom); Require (bufFrom + GetLength () >= bufTo); _fRep->CopyTo (bufFrom, bufTo); } inline size_t String::GetLength () const { return (_fRep->GetLength ()); } inline bool String::empty () const { return _fRep->GetLength () == 0; } inline void String::clear () { *this = String (); } inline void String::InsertAt (Character c, size_t at) { InsertAt (&c, &c + 1, at); } inline void String::InsertAt (const String& s, size_t at) { // NB: I don't THINK we need be careful if s.fRep == this->fRep because when we first derefence this->fRep it will force a CLONE, so OUR fRep will be unique // And no need to worry about lifetime of 'p' because we don't allow changes to 's' from two different threads at a time, and the rep would rep if accessed from // another thread could only change that other envelopes copy pair<const Character*, const Character*> d = s._fRep->GetData (); InsertAt (d.first, d.second, at); } inline void String::InsertAt (const wchar_t* from, const wchar_t* to, size_t at) { InsertAt (reinterpret_cast<const Character*> (from), reinterpret_cast<const Character*> (to), at); } inline String& String::operator+= (Character appendage) { InsertAt (appendage, GetLength ()); return (*this); } inline String& String::operator+= (const String& appendage) { InsertAt (appendage, GetLength ()); return (*this); } inline Character String::operator[] (size_t i) const { Require (i >= 0); Require (i < GetLength ()); return (_fRep->GetAt (i)); } template <> inline void String::As (wstring* into) const { RequireNotNull (into); size_t n = GetLength (); const Character* cp = _fRep->Peek (); Assert (sizeof (Character) == sizeof (wchar_t)); // going to want to clean this up!!! --LGP 2011-09-01 const wchar_t* wcp = (const wchar_t*)cp; into->assign (wcp, wcp + n); } template <> inline wstring String::As () const { wstring r; As (&r); return r; } template <> inline const wchar_t* String::As () const { // I'm not sure of the Peek() semantics, so I'm not sure this is right, but document Peek() better so this is safe!!! -- LGP 2011-09-01 return (const wchar_t*)_fRep->Peek (); } template <> inline const Character* String::As () const { // I'm not sure of the Peek() semantics, so I'm not sure this is right, but document Peek() better so this is safe!!! -- LGP 2011-09-01 return (const Character*)_fRep->Peek (); } template <> inline string String::AsUTF8 () const { string r; AsUTF8 (&r); return r; } inline std::string String::AsUTF8 () const { return AsUTF8<std::string> (); } inline void String::AsUTF8 (std::string* into) const { AsUTF8<std::string> (into); } template <> inline string String::AsASCII () const { string r; AsASCII (&r); return r; } inline std::string String::AsASCII () const { return AsASCII<std::string> (); } inline void String::AsASCII (std::string* into) const { AsASCII<std::string> (into); } inline size_t String::length () const { return GetLength (); } inline size_t String::size () const { return GetLength (); } inline const wchar_t* String::data () const { return As<const wchar_t*> (); } inline size_t String::find (wchar_t c) const { return IndexOf (c); } inline size_t String::rfind (wchar_t c) const { return RIndexOf (c); } inline int String::Compare (const String& rhs, CompareOptions co) const { pair<const Character*, const Character*> d = rhs._fRep->GetData (); return _fRep->Compare (d.first, d.second, co); } inline int String::Compare (const Character* rhsStart, const Character* rhsEnd, CompareOptions co) const { return _fRep->Compare (rhsStart, rhsEnd, co); } inline int String::Compare (const wchar_t* rhsStart, const wchar_t* rhsEnd, CompareOptions co) const { static_assert (sizeof (Character) == sizeof (wchar_t), "Character and wchar_t must be same size"); return _fRep->Compare (reinterpret_cast<const Character*> (rhsStart), reinterpret_cast<const Character*> (rhsEnd), co); } inline bool operator== (const String& lhs, const String& rhs) { if (lhs._fRep == rhs._fRep) { return (true); } pair<const Character*, const Character*> d = rhs._fRep->GetData (); return lhs.Compare (d.first, d.second, String::eWithCase_CO) == 0; } inline bool operator== (const wchar_t* lhs, const String& rhs) { RequireNotNull (lhs); return rhs.Compare (lhs, lhs + ::wcslen (lhs), String::eWithCase_CO) == 0; } inline bool operator== (const String& lhs, const wchar_t* rhs) { RequireNotNull (rhs); return lhs.Compare (rhs, rhs + ::wcslen (rhs), String::eWithCase_CO) == 0; } inline bool operator< (const String& lhs, const String& rhs) { if (lhs._fRep == rhs._fRep) { return (false); } pair<const Character*, const Character*> d = rhs._fRep->GetData (); return lhs.Compare (d.first, d.second, String::eWithCase_CO) < 0; } inline bool operator< (const wchar_t* lhs, const String& rhs) { RequireNotNull (lhs); return rhs.Compare (lhs, lhs + ::wcslen (lhs), String::eWithCase_CO) >= 0; } inline bool operator< (const String& lhs, const wchar_t* rhs) { RequireNotNull (rhs); return lhs.Compare (rhs, rhs + ::wcslen (rhs), String::eWithCase_CO) < 0; } inline bool operator<= (const String& lhs, const String& rhs) { if (lhs._fRep == rhs._fRep) { return (false); } pair<const Character*, const Character*> d = rhs._fRep->GetData (); return lhs.Compare (d.first, d.second, String::eWithCase_CO) <= 0; } inline bool operator<= (const wchar_t* lhs, const String& rhs) { RequireNotNull (lhs); return rhs.Compare (lhs, lhs + ::wcslen (lhs), String::eWithCase_CO) > 0; } inline bool operator<= (const String& lhs, const wchar_t* rhs) { RequireNotNull (rhs); return lhs.Compare (rhs, rhs + ::wcslen (rhs), String::eWithCase_CO) <= 0; } inline bool operator!= (const String& lhs, const String& rhs) { return (bool (not (lhs == rhs))); } inline bool operator!= (const wchar_t* lhs, const String& rhs) { return (bool (not (lhs == rhs))); } inline bool operator!= (const String& lhs, const wchar_t* rhs) { return (bool (not (lhs == rhs))); } inline bool operator> (const String& lhs, const String& rhs) { return (bool (not (lhs <= rhs))); } inline bool operator> (const wchar_t* lhs, const String& rhs) { return (bool (not (lhs <= rhs))); } inline bool operator> (const String& lhs, const wchar_t* rhs) { return (bool (not (lhs <= rhs))); } inline bool operator>= (const String& lhs, const String& rhs) { return (bool (not (lhs < rhs))); } inline bool operator>= (const wchar_t* lhs, const String& rhs) { return (bool (not (lhs < rhs))); } inline bool operator>= (const String& lhs, const wchar_t* rhs) { return (bool (not (lhs < rhs))); } #if 0 // class String_CharArray inline String_CharArray::String_CharArray (const String_CharArray& s) : String (s) { } inline String_CharArray& String_CharArray::operator= (const String_CharArray& s) { String::operator= (s); return (*this); } #endif // class String_BufferedArray inline String_BufferedArray::String_BufferedArray (const String_BufferedArray& s) : String (s) { } inline String_BufferedArray& String_BufferedArray::operator= (const String_BufferedArray& s) { String::operator= (s); return (*this); } // class String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly inline String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly::String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly (const String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly& s) : String (s) { } inline String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly& String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly::operator= (const String_ExternalMemoryOwnership_ApplicationLifetime_ReadOnly& s) { String::operator= (s); return (*this); } // class String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite inline String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite::String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite (const String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite& s) : String (s) { } inline String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite& String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite::operator= (const String_ExternalMemoryOwnership_ApplicationLifetime_ReadWrite& s) { String::operator= (s); return (*this); } } } } #endif // _Stroika_Foundation_Characters_String_inl_ <|endoftext|>
<commit_before>/* Copyright (c) 2014, J.D. Koftinoff Software, Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "JDKSAvdeccMCU_World.hpp" #include "JDKSAvdeccMCU_Apc.hpp" #if defined( __APPLE__ ) namespace JDKSAvdeccMCU { void ApcStateMachine::start() {} void ApcStateMachine::finish() {} void ApcStateMachine::executeState() { switch ( m_state ) { case StateBegin: executeStateBegin(); break; case StateInitialize: executeStateInitialize(); break; case StateWaitForConnect: executeStateWaitForConnect(); break; case StateAccept: executeStateAccept(); break; case StateStartTransfer: executeStateStartTransfer(); break; case StateWaiting: executeStateWaiting(); break; case StateClosed: executeStateClosed(); break; case StateLinkStatus: executeStateLinkStatus(); break; case StateReceiveMsg: executeStateReceiveMsg(); break; case StateSendMsg: executeStateSendMsg(); break; case StateEntityIdAssigned: executeStateEntityIdAssigned(); break; case StateSendNop: executeStateSendNop(); break; case StateFinish: executeStateFinish(); break; case StateEnd: executeStateEnd(); break; default: executeStateEnd(); break; } } void ApcStateMachine::gotoStateBegin() { m_state = StateBegin; } void ApcStateMachine::executeStateBegin() { gotoStateInitialize(); } void ApcStateMachine::gotoStateInitialize() { m_state = StateInitialize; initialize(); connectToProxy( m_addr ); } void ApcStateMachine::executeStateInitialize() { gotoStateWaitForConnect(); } void ApcStateMachine::gotoStateWaitForConnect() { m_state = StateWaitForConnect; } void ApcStateMachine::executeStateWaitForConnect() { if ( m_tcpConnected ) { gotoStateAccept(); } else if ( m_finished ) { gotoStateFinish(); } } void ApcStateMachine::gotoStateAccept() { m_state = StateAccept; sendHttpRequest( m_addr ); } void ApcStateMachine::executeStateAccept() { if ( getHttpResponse() ) { gotoStateStartTransfer(); } else { gotoStateClosed(); } } void ApcStateMachine::gotoStateStartTransfer() { } void ApcStateMachine::executeStateStartTransfer() { } void ApcStateMachine::gotoStateWaiting() { } } #endif <commit_msg>clang-format applied<commit_after>/* Copyright (c) 2014, J.D. Koftinoff Software, Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "JDKSAvdeccMCU_World.hpp" #include "JDKSAvdeccMCU_Apc.hpp" #if defined( __APPLE__ ) namespace JDKSAvdeccMCU { void ApcStateMachine::start() {} void ApcStateMachine::finish() {} void ApcStateMachine::executeState() { switch ( m_state ) { case StateBegin: executeStateBegin(); break; case StateInitialize: executeStateInitialize(); break; case StateWaitForConnect: executeStateWaitForConnect(); break; case StateAccept: executeStateAccept(); break; case StateStartTransfer: executeStateStartTransfer(); break; case StateWaiting: executeStateWaiting(); break; case StateClosed: executeStateClosed(); break; case StateLinkStatus: executeStateLinkStatus(); break; case StateReceiveMsg: executeStateReceiveMsg(); break; case StateSendMsg: executeStateSendMsg(); break; case StateEntityIdAssigned: executeStateEntityIdAssigned(); break; case StateSendNop: executeStateSendNop(); break; case StateFinish: executeStateFinish(); break; case StateEnd: executeStateEnd(); break; default: executeStateEnd(); break; } } void ApcStateMachine::gotoStateBegin() { m_state = StateBegin; } void ApcStateMachine::executeStateBegin() { gotoStateInitialize(); } void ApcStateMachine::gotoStateInitialize() { m_state = StateInitialize; initialize(); connectToProxy( m_addr ); } void ApcStateMachine::executeStateInitialize() { gotoStateWaitForConnect(); } void ApcStateMachine::gotoStateWaitForConnect() { m_state = StateWaitForConnect; } void ApcStateMachine::executeStateWaitForConnect() { if ( m_tcpConnected ) { gotoStateAccept(); } else if ( m_finished ) { gotoStateFinish(); } } void ApcStateMachine::gotoStateAccept() { m_state = StateAccept; sendHttpRequest( m_addr ); } void ApcStateMachine::executeStateAccept() { if ( getHttpResponse() ) { gotoStateStartTransfer(); } else { gotoStateClosed(); } } void ApcStateMachine::gotoStateStartTransfer() {} void ApcStateMachine::executeStateStartTransfer() {} void ApcStateMachine::gotoStateWaiting() {} } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2015 Dilyan Rusev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "scene.h" #include "json/json.h" #include "tinyxml2.h" #include <fstream> #include <memory> #include "SDL_log.h" using namespace std; namespace foo { Scene::Scene() {} Scene::Scene(Scene &&other) { swap(*this, other); } Scene::~Scene() {} Scene& Scene::operator=(Scene &&other) { if (this != &other) { id_.clear(); title_.clear(); textures_.clear(); spritesheets_.clear(); objects_.clear(); swap(*this, other); } return *this; } void Scene::LoadFromFile(const char *file_name) { SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "Loading scene from %s...\n", file_name); string prefix(file_name); auto last_separator = prefix.find_last_of('\\'); if (string::npos == last_separator) { last_separator = prefix.find_last_of('/'); } if (string::npos != last_separator) { prefix.erase(last_separator + 1, string::npos); } ifstream in_file(file_name); Json::Value in; in_file >> in; const Json::Value &json_id = in["id"]; if (!json_id.isNull()) { id_ = json_id.asString(); } title_ = in["title"].asString(); width_ = in["width"].asInt(); height_ = in["height"].asInt(); ProcessSpritesheets(prefix, in["spritesheets"]); ProcessTextures(prefix, in["textures"]); ProcessSceneObjects(prefix, in["objects"]); } void Scene::ProcessTextures( const string &prefix, const Json::Value &in) { SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "Processing scene textures...\n"); textures_.clear(); if (in.isNull() || !in.isArray()) { return; } for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) { const auto &json_object = in[i]; SceneTexture texture; texture.id = json_object["id"].asString(); texture.path = prefix + json_object["path"].asString(); textures_.emplace_back(std::move(texture)); } } void Scene::ProcessSpritesheets( const string &prefix, const Json::Value &in) { SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "Processing scene spritesheets...\n"); spritesheets_.clear(); if (in.isNull() || !in.isArray()) { return; } for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) { const auto &json_object = in[i]; SceneSpritesheet sheet; sheet.id = json_object["id"].asString(); sheet.path = prefix + json_object["path"].asString(); ProcessTextureAtlasXml(prefix, sheet); } } void Scene::ProcessTextureAtlasXml( const string &prefix, SceneSpritesheet &out) const { SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "Processing XML texture atlas %s...\n", out.path.c_str()); using namespace tinyxml2; out.regions.clear(); XMLDocument doc; XMLError error; error = doc.LoadFile(out.path.c_str()); if (error != XML_NO_ERROR) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "Failed to load atlas %s: %d\n", out.path.c_str(), error); throw runtime_error("Failed to load atlas file"); } XMLElement *root = doc.RootElement(); if (!root) { throw runtime_error("Atlas file has no root XML element"); } const char *raw_path = root->Attribute("imagePath"); if (!raw_path) { throw runtime_error("Failed to get TextureAtlas.imagePath"); } out.image_path = prefix + string(raw_path); for (XMLElement *current = root->FirstChildElement("SubTexture"); current; current = current->NextSiblingElement("SubTexture")) { SceneSceneSpritesheetRegion region; const char *raw_name = current->Attribute("name"); if (!raw_name) { throw runtime_error("Failed to get SubTexture.name"); } region.name = raw_name; if (current->QueryAttribute("x", &region.x) != XML_NO_ERROR) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "Failed on element %s\n", raw_name); throw runtime_error("Failed to get SubTexture.x"); } if (current->QueryAttribute("y", &region.y) != XML_NO_ERROR) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "Failed on element %s\n", raw_name); throw runtime_error("Failed to get SubTexture.y"); } if (current->QueryAttribute("width", &region.width) != XML_NO_ERROR) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "Failed on element %s\n", raw_name); throw runtime_error("Failed to get SubTexture.width"); } if (current->QueryAttribute("height", &region.height) != XML_NO_ERROR) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "Failed on element %s\n", raw_name); throw runtime_error("Failed to get SubTexture.height"); } out.regions.emplace_back(move(region)); } SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "Processed %lu SubTexture-s.\n", static_cast<unsigned long>(out.regions.size())); } void Scene::ProcessSceneObjects( const string &prefix, const Json::Value &in) { SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "Processing scene objects...\n"); objects_.clear(); if (in.isNull() || !in.isArray()) { return; } for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) { const auto &json_object = in[i]; SceneObject object; object.id = json_object["id"].asString(); if (!object.id.size()) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Empty object id: skipping\n"); continue; } const auto &json_position = json_object["position"]; if (json_position.isNull() || !json_position.isArray() || 2 != json_position.size() || !json_position[0].isInt() || !json_position[1].isInt()) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Missing or malformatted position for %s: skipping\n", object.id.c_str()); continue; } object.x = json_position[0].asInt(); object.y = json_position[1].asInt(); ProcessObjectComponents(prefix, json_object["components"], object); objects_.emplace_back(move(object)); } } void Scene::ProcessObjectComponents( const string &prefix, const Json::Value &in, SceneObject &out) const { if (in.isNull()) { return; } for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) { const auto &json_object = in[i]; const auto &json_type = json_object["type"]; if (json_type.isNull() || !json_type.isString()) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Missing or malformatted component type for" " %s: skipping\n", out.id.c_str()); continue; } const auto &type = json_type.asString(); if (type == "texture") { if (out.texture) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Redefined texture component for %s: ignoring\n", out.id.c_str()); continue; } out.texture = ProcessTextureComponent( out, json_object); } else if (type == "texture_repeat") { if (out.texture_repeat) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Redefined texture_repeat component for %s: ignoring\n", out.id.c_str()); continue; } out.texture_repeat = ProcessTextureRepeatComponent( out, json_object); } else { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Unknown component type %s for %s: ignoring\n", type.c_str(), out.id.c_str()); } } } unique_ptr<SceneComponentTexture> Scene::ProcessTextureComponent( const SceneObject &object, const Json::Value &in) const { const auto &json_texture_id = in["texture_id"]; if (json_texture_id.isNull() || !json_texture_id.isString()) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Missing texture_id for texture component " "in %s\n", object.id.c_str()); return nullptr; } auto ptr = unique_ptr<SceneComponentTexture>( new SceneComponentTexture); ptr->texture_id = json_texture_id.asString(); return move(ptr); } unique_ptr<SceneComponentTextureRepeat> Scene::ProcessTextureRepeatComponent( const SceneObject &object, const Json::Value &in) const { const auto &json_repeat = in["repeat"]; if (json_repeat.isNull() || !json_repeat.isArray() || json_repeat.size() != 2 || !json_repeat[0].isInt() || !json_repeat[1].isInt()) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Missing or malformated repeat texture_repeat " "comonent in %s\n", object.id.c_str()); return nullptr; } auto ptr = unique_ptr<SceneComponentTextureRepeat>( new SceneComponentTextureRepeat); ptr->repeat_x = json_repeat[0].asInt(); ptr->repeat_y = json_repeat[1].asInt(); return move(ptr); } } // namespace foo<commit_msg>fix bug: not adding to list<commit_after>/* Copyright (c) 2015 Dilyan Rusev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "scene.h" #include "json/json.h" #include "tinyxml2.h" #include <fstream> #include <memory> #include "SDL_log.h" using namespace std; namespace foo { Scene::Scene() {} Scene::Scene(Scene &&other) { swap(*this, other); } Scene::~Scene() {} Scene& Scene::operator=(Scene &&other) { if (this != &other) { id_.clear(); title_.clear(); textures_.clear(); spritesheets_.clear(); objects_.clear(); swap(*this, other); } return *this; } void Scene::LoadFromFile(const char *file_name) { SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "Loading scene from %s...\n", file_name); string prefix(file_name); auto last_separator = prefix.find_last_of('\\'); if (string::npos == last_separator) { last_separator = prefix.find_last_of('/'); } if (string::npos != last_separator) { prefix.erase(last_separator + 1, string::npos); } ifstream in_file(file_name); Json::Value in; in_file >> in; const Json::Value &json_id = in["id"]; if (!json_id.isNull()) { id_ = json_id.asString(); } title_ = in["title"].asString(); width_ = in["width"].asInt(); height_ = in["height"].asInt(); ProcessSpritesheets(prefix, in["spritesheets"]); ProcessTextures(prefix, in["textures"]); ProcessSceneObjects(prefix, in["objects"]); } void Scene::ProcessTextures( const string &prefix, const Json::Value &in) { SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "Processing scene textures...\n"); textures_.clear(); if (in.isNull() || !in.isArray()) { return; } for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) { const auto &json_object = in[i]; SceneTexture texture; texture.id = json_object["id"].asString(); texture.path = prefix + json_object["path"].asString(); textures_.emplace_back(std::move(texture)); } } void Scene::ProcessSpritesheets( const string &prefix, const Json::Value &in) { SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "Processing scene spritesheets...\n"); spritesheets_.clear(); if (in.isNull() || !in.isArray()) { return; } for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) { const auto &json_object = in[i]; SceneSpritesheet sheet; sheet.id = json_object["id"].asString(); sheet.path = prefix + json_object["path"].asString(); ProcessTextureAtlasXml(prefix, sheet); spritesheets_.emplace_back(move(sheet)); } } void Scene::ProcessTextureAtlasXml( const string &prefix, SceneSpritesheet &out) const { SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "Processing XML texture atlas %s...\n", out.path.c_str()); using namespace tinyxml2; out.regions.clear(); XMLDocument doc; XMLError error; error = doc.LoadFile(out.path.c_str()); if (error != XML_NO_ERROR) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "Failed to load atlas %s: %d\n", out.path.c_str(), error); throw runtime_error("Failed to load atlas file"); } XMLElement *root = doc.RootElement(); if (!root) { throw runtime_error("Atlas file has no root XML element"); } const char *raw_path = root->Attribute("imagePath"); if (!raw_path) { throw runtime_error("Failed to get TextureAtlas.imagePath"); } out.image_path = prefix + string(raw_path); for (XMLElement *current = root->FirstChildElement("SubTexture"); current; current = current->NextSiblingElement("SubTexture")) { SceneSceneSpritesheetRegion region; const char *raw_name = current->Attribute("name"); if (!raw_name) { throw runtime_error("Failed to get SubTexture.name"); } region.name = raw_name; if (current->QueryAttribute("x", &region.x) != XML_NO_ERROR) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "Failed on element %s\n", raw_name); throw runtime_error("Failed to get SubTexture.x"); } if (current->QueryAttribute("y", &region.y) != XML_NO_ERROR) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "Failed on element %s\n", raw_name); throw runtime_error("Failed to get SubTexture.y"); } if (current->QueryAttribute("width", &region.width) != XML_NO_ERROR) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "Failed on element %s\n", raw_name); throw runtime_error("Failed to get SubTexture.width"); } if (current->QueryAttribute("height", &region.height) != XML_NO_ERROR) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "Failed on element %s\n", raw_name); throw runtime_error("Failed to get SubTexture.height"); } out.regions.emplace_back(move(region)); } SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "Processed %lu SubTexture-s.\n", static_cast<unsigned long>(out.regions.size())); } void Scene::ProcessSceneObjects( const string &prefix, const Json::Value &in) { SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "Processing scene objects...\n"); objects_.clear(); if (in.isNull() || !in.isArray()) { return; } for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) { const auto &json_object = in[i]; SceneObject object; object.id = json_object["id"].asString(); if (!object.id.size()) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Empty object id: skipping\n"); continue; } const auto &json_position = json_object["position"]; if (json_position.isNull() || !json_position.isArray() || 2 != json_position.size() || !json_position[0].isInt() || !json_position[1].isInt()) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Missing or malformatted position for %s: skipping\n", object.id.c_str()); continue; } object.x = json_position[0].asInt(); object.y = json_position[1].asInt(); ProcessObjectComponents(prefix, json_object["components"], object); objects_.emplace_back(move(object)); } } void Scene::ProcessObjectComponents( const string &prefix, const Json::Value &in, SceneObject &out) const { if (in.isNull()) { return; } for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) { const auto &json_object = in[i]; const auto &json_type = json_object["type"]; if (json_type.isNull() || !json_type.isString()) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Missing or malformatted component type for" " %s: skipping\n", out.id.c_str()); continue; } const auto &type = json_type.asString(); if (type == "texture") { if (out.texture) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Redefined texture component for %s: ignoring\n", out.id.c_str()); continue; } out.texture = ProcessTextureComponent( out, json_object); } else if (type == "texture_repeat") { if (out.texture_repeat) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Redefined texture_repeat component for %s: ignoring\n", out.id.c_str()); continue; } out.texture_repeat = ProcessTextureRepeatComponent( out, json_object); } else { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Unknown component type %s for %s: ignoring\n", type.c_str(), out.id.c_str()); } } } unique_ptr<SceneComponentTexture> Scene::ProcessTextureComponent( const SceneObject &object, const Json::Value &in) const { const auto &json_texture_id = in["texture_id"]; if (json_texture_id.isNull() || !json_texture_id.isString()) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Missing texture_id for texture component " "in %s\n", object.id.c_str()); return nullptr; } auto ptr = unique_ptr<SceneComponentTexture>( new SceneComponentTexture); ptr->texture_id = json_texture_id.asString(); return move(ptr); } unique_ptr<SceneComponentTextureRepeat> Scene::ProcessTextureRepeatComponent( const SceneObject &object, const Json::Value &in) const { const auto &json_repeat = in["repeat"]; if (json_repeat.isNull() || !json_repeat.isArray() || json_repeat.size() != 2 || !json_repeat[0].isInt() || !json_repeat[1].isInt()) { SDL_LogWarn( SDL_LOG_CATEGORY_SYSTEM, "Missing or malformated repeat texture_repeat " "comonent in %s\n", object.id.c_str()); return nullptr; } auto ptr = unique_ptr<SceneComponentTextureRepeat>( new SceneComponentTextureRepeat); ptr->repeat_x = json_repeat[0].asInt(); ptr->repeat_y = json_repeat[1].asInt(); return move(ptr); } } // namespace foo<|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include "absl/cleanup/cleanup.h" #include "absl/types/span.h" #include "tensorflow/compiler/xla/service/compiler.h" #include "tensorflow/compiler/xla/service/executable.h" #include "tensorflow/compiler/xla/service/hlo_cost_analysis.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_module_group.h" #include "tensorflow/compiler/xla/service/shaped_buffer.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/stream_executor/device_memory_allocator.h" #include "tensorflow/compiler/xla/stream_executor/tpu/c_api_conversions.h" #include "tensorflow/compiler/xla/stream_executor/tpu/c_api_decl.h" #include "tensorflow/compiler/xla/stream_executor/tpu/proto_helper.h" #include "tensorflow/compiler/xla/stream_executor/tpu/status_helper.h" #include "tensorflow/compiler/xla/stream_executor/tpu/tpu_executable.h" #include "tensorflow/compiler/xla/stream_executor/tpu/tpu_executor.h" #include "tensorflow/compiler/xla/stream_executor/tpu/tpu_executor_c_api.h" #include "tensorflow/compiler/xla/stream_executor/tpu/tpu_platform.h" #include "tensorflow/compiler/xla/stream_executor/tpu/tpu_platform_id.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" namespace xla { namespace { using ::tensorflow::tpu::ExecutorApiFn; class TpuCompiler : public Compiler { public: TpuCompiler() { compiler_ = ExecutorApiFn()->TpuCompiler_NewFn(); } ~TpuCompiler() override { ExecutorApiFn()->TpuCompiler_FreeFn(compiler_); } stream_executor::Platform::Id PlatformId() const override { return tensorflow::tpu::GetTpuPlatformId(); } StatusOr<std::unique_ptr<HloModule>> RunHloPasses( std::unique_ptr<HloModule> module, stream_executor::StreamExecutor* executor, const CompileOptions& options) override { XLA_HloModule hlo_module; auto cleanup = absl::MakeCleanup([&hlo_module]() { stream_executor::tpu::SerializedProto_Free(hlo_module.proto); ApiConverter::Destroy(&hlo_module.module_config); }); hlo_module.module_config = ApiConverter::ToC(module->config()); hlo_module.proto = stream_executor::tpu::SerializeProto(module->ToProto()); auto allocator = ApiConverter::ToC(options.device_allocator); XLA_HloModule result; StatusHelper status; ExecutorApiFn()->TpuCompiler_RunHloPassesFn( compiler_, &hlo_module, static_cast<tensorflow::tpu::TpuExecutor*>(executor->implementation()) ->se_executor(), &allocator, &result, status.c_status); if (!status.ok()) { return status.status(); } HloModuleProto result_proto = stream_executor::tpu::DeserializeProto<HloModuleProto>(result.proto); stream_executor::tpu::SerializedProto_Free(result.proto); return HloModule::CreateFromProto(result_proto, module->config()); } StatusOr<std::unique_ptr<Executable>> RunBackend( std::unique_ptr<HloModule> module, stream_executor::StreamExecutor* executor, const CompileOptions& options) override { XLA_HloModule hlo_module; auto cleanup = absl::MakeCleanup([&hlo_module]() { stream_executor::tpu::SerializedProto_Free(hlo_module.proto); ApiConverter::Destroy(&hlo_module.module_config); }); SE_Executable* result; hlo_module.module_config = ApiConverter::ToC(module->config()); hlo_module.proto = stream_executor::tpu::SerializeProto(module->ToProto()); auto allocator = ApiConverter::ToC(options.device_allocator); StatusHelper status; ExecutorApiFn()->TpuCompiler_RunBackendFn( compiler_, &hlo_module, static_cast<tensorflow::tpu::TpuExecutor*>(executor->implementation()) ->se_executor(), &allocator, &result, status.c_status); if (!status.ok()) { return status.status(); } std::unique_ptr<Executable> exec = std::make_unique<TpuExecutable>(result, std::move(module)); return exec; } StatusOr<std::vector<std::unique_ptr<Executable>>> Compile( std::unique_ptr<HloModuleGroup> module_group, std::vector<std::vector<stream_executor::StreamExecutor*>> stream_exec, const CompileOptions& options) override { XLA_HloModuleGroup se_module_group; se_module_group.proto = stream_executor::tpu::SerializeProto(module_group->ToProto()); se_module_group.module_config = new XLA_HloModuleConfig[module_group->size()]; int module_group_size = module_group->size(); auto cleanup_config = absl::MakeCleanup([&se_module_group, module_group_size]() { for (auto i = 0; i < module_group_size; ++i) { ApiConverter::Destroy(&se_module_group.module_config[i]); } delete[] se_module_group.module_config; }); for (int i = 0; i < module_group->size(); ++i) { const auto& config = module_group->module(i).config(); se_module_group.module_config[i] = ApiConverter::ToC(config); } std::vector<SE_StreamExecutorList> se_lists(stream_exec.size()); std::vector<std::vector<SE_StreamExecutor*>> se_lists_storage; for (int i = 0; i < stream_exec.size(); ++i) { se_lists[i].count = stream_exec[i].size(); se_lists_storage.emplace_back(stream_exec[i].size()); se_lists[i].exec = se_lists_storage.back().data(); for (int j = 0; j < stream_exec[i].size(); ++j) { se_lists[i].exec[j] = static_cast<tensorflow::tpu::TpuExecutor*>( stream_exec[i][j]->implementation()) ->se_executor(); } } SE_DeviceMemoryAllocator allocator = ApiConverter::ToC(options.device_allocator); SE_Executable** se_executables = new SE_Executable*[module_group->size()]; StatusHelper status; ExecutorApiFn()->TpuCompiler_CompileFn( compiler_, &se_module_group, se_lists.data(), stream_exec.size(), &allocator, se_executables, status.c_status); if (!status.ok()) { return status.status(); } std::vector<std::unique_ptr<Executable>> executables; for (int i = 0; i < module_group->size(); ++i) { // We get the HloModule from the compiled executable, rather than reusing // the input module from 'module_group', in case the module changed in // some way. For example, if the computation is automatically partitioned // via XLA, the executable's module may have different input/output shapes // than the input module. XLA_HloModule c_module = ExecutorApiFn()->TpuExecutable_HloModuleFn(se_executables[i]); auto cleanup_c_module = absl::MakeCleanup( [&c_module]() { ApiConverter::Destroy(&c_module); }); TF_ASSIGN_OR_RETURN(std::unique_ptr<HloModule> module, ApiConverter::FromC(c_module)); std::shared_ptr<HloModule> module_shared(module.release()); executables.emplace_back(std::make_unique<TpuExecutable>( se_executables[i], std::move(module_shared))); } stream_executor::tpu::SerializedProto_Free(se_module_group.proto); delete[] se_executables; return executables; } // Compiles the HLO module group for ahead-of-time execution. This is // intended for use in static compilation. StatusOr<std::vector<std::unique_ptr<AotCompilationResult>>> CompileAheadOfTime(std::unique_ptr<HloModuleGroup> module_group, const AotCompilationOptions& options) override { return Unimplemented("This compiler does not support CompileAheadOfTime."); } // Returns a function that computes the size in bytes of the logical // buffer that contains a shape. HloCostAnalysis::ShapeSizeFunction ShapeSizeBytesFunction() const override { return [this](const xla::Shape& shape) { XLA_Shape c_shape; ApiConverter::ToC(shape, &c_shape); int64_t bytes = ExecutorApiFn()->TpuCompiler_ShapeSizeFn(compiler_, &c_shape); ApiConverter::Destroy(&c_shape); return bytes; }; } Shape DefaultDeviceShapeRepresentation(const Shape& shape) const override { XLA_Shape host_shape, device_shape; ApiConverter::ToC(shape, &host_shape); ExecutorApiFn()->TpuCompiler_DefaultDeviceShapeRepresentationFn( compiler_, &host_shape, &device_shape); return ApiConverter::FromC(&device_shape); } private: Tpu_Compiler* compiler_; }; static bool InitModule() { xla::Compiler::RegisterCompilerFactory( tensorflow::tpu::GetTpuPlatformId(), []() { return std::make_unique<TpuCompiler>(); }); return true; } static bool module_initialized = InitModule(); } // namespace } // namespace xla <commit_msg>[libtpu] Fix some memory leaks<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include "absl/cleanup/cleanup.h" #include "absl/types/span.h" #include "tensorflow/compiler/xla/service/compiler.h" #include "tensorflow/compiler/xla/service/executable.h" #include "tensorflow/compiler/xla/service/hlo_cost_analysis.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_module_group.h" #include "tensorflow/compiler/xla/service/shaped_buffer.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/stream_executor/device_memory_allocator.h" #include "tensorflow/compiler/xla/stream_executor/tpu/c_api_conversions.h" #include "tensorflow/compiler/xla/stream_executor/tpu/c_api_decl.h" #include "tensorflow/compiler/xla/stream_executor/tpu/proto_helper.h" #include "tensorflow/compiler/xla/stream_executor/tpu/status_helper.h" #include "tensorflow/compiler/xla/stream_executor/tpu/tpu_executable.h" #include "tensorflow/compiler/xla/stream_executor/tpu/tpu_executor.h" #include "tensorflow/compiler/xla/stream_executor/tpu/tpu_executor_c_api.h" #include "tensorflow/compiler/xla/stream_executor/tpu/tpu_platform.h" #include "tensorflow/compiler/xla/stream_executor/tpu/tpu_platform_id.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" namespace xla { namespace { using ::tensorflow::tpu::ExecutorApiFn; class TpuCompiler : public Compiler { public: TpuCompiler() { compiler_ = ExecutorApiFn()->TpuCompiler_NewFn(); } ~TpuCompiler() override { ExecutorApiFn()->TpuCompiler_FreeFn(compiler_); } stream_executor::Platform::Id PlatformId() const override { return tensorflow::tpu::GetTpuPlatformId(); } StatusOr<std::unique_ptr<HloModule>> RunHloPasses( std::unique_ptr<HloModule> module, stream_executor::StreamExecutor* executor, const CompileOptions& options) override { XLA_HloModule hlo_module; auto cleanup = absl::MakeCleanup([&hlo_module]() { stream_executor::tpu::SerializedProto_Free(hlo_module.proto); ApiConverter::Destroy(&hlo_module.module_config); }); hlo_module.module_config = ApiConverter::ToC(module->config()); hlo_module.proto = stream_executor::tpu::SerializeProto(module->ToProto()); auto allocator = ApiConverter::ToC(options.device_allocator); XLA_HloModule result; StatusHelper status; ExecutorApiFn()->TpuCompiler_RunHloPassesFn( compiler_, &hlo_module, static_cast<tensorflow::tpu::TpuExecutor*>(executor->implementation()) ->se_executor(), &allocator, &result, status.c_status); if (!status.ok()) { return status.status(); } HloModuleProto result_proto = stream_executor::tpu::DeserializeProto<HloModuleProto>(result.proto); stream_executor::tpu::SerializedProto_Free(result.proto); return HloModule::CreateFromProto(result_proto, module->config()); } StatusOr<std::unique_ptr<Executable>> RunBackend( std::unique_ptr<HloModule> module, stream_executor::StreamExecutor* executor, const CompileOptions& options) override { XLA_HloModule hlo_module; auto cleanup = absl::MakeCleanup([&hlo_module]() { stream_executor::tpu::SerializedProto_Free(hlo_module.proto); ApiConverter::Destroy(&hlo_module.module_config); }); SE_Executable* result; hlo_module.module_config = ApiConverter::ToC(module->config()); hlo_module.proto = stream_executor::tpu::SerializeProto(module->ToProto()); auto allocator = ApiConverter::ToC(options.device_allocator); StatusHelper status; ExecutorApiFn()->TpuCompiler_RunBackendFn( compiler_, &hlo_module, static_cast<tensorflow::tpu::TpuExecutor*>(executor->implementation()) ->se_executor(), &allocator, &result, status.c_status); if (!status.ok()) { return status.status(); } std::unique_ptr<Executable> exec = std::make_unique<TpuExecutable>(result, std::move(module)); return exec; } StatusOr<std::vector<std::unique_ptr<Executable>>> Compile( std::unique_ptr<HloModuleGroup> module_group, std::vector<std::vector<stream_executor::StreamExecutor*>> stream_exec, const CompileOptions& options) override { XLA_HloModuleGroup se_module_group; se_module_group.proto = stream_executor::tpu::SerializeProto(module_group->ToProto()); se_module_group.module_config = new XLA_HloModuleConfig[module_group->size()]; int module_group_size = module_group->size(); auto cleanup_config = absl::MakeCleanup([&se_module_group, module_group_size]() { for (auto i = 0; i < module_group_size; ++i) { ApiConverter::Destroy(&se_module_group.module_config[i]); } delete[] se_module_group.module_config; }); for (int i = 0; i < module_group->size(); ++i) { const auto& config = module_group->module(i).config(); se_module_group.module_config[i] = ApiConverter::ToC(config); } std::vector<SE_StreamExecutorList> se_lists(stream_exec.size()); std::vector<std::vector<SE_StreamExecutor*>> se_lists_storage; for (int i = 0; i < stream_exec.size(); ++i) { se_lists[i].count = stream_exec[i].size(); se_lists_storage.emplace_back(stream_exec[i].size()); se_lists[i].exec = se_lists_storage.back().data(); for (int j = 0; j < stream_exec[i].size(); ++j) { se_lists[i].exec[j] = static_cast<tensorflow::tpu::TpuExecutor*>( stream_exec[i][j]->implementation()) ->se_executor(); } } SE_DeviceMemoryAllocator allocator = ApiConverter::ToC(options.device_allocator); SE_Executable** se_executables = new SE_Executable*[module_group->size()]; StatusHelper status; ExecutorApiFn()->TpuCompiler_CompileFn( compiler_, &se_module_group, se_lists.data(), stream_exec.size(), &allocator, se_executables, status.c_status); if (!status.ok()) { return status.status(); } std::vector<std::unique_ptr<Executable>> executables; for (int i = 0; i < module_group->size(); ++i) { // We get the HloModule from the compiled executable, rather than reusing // the input module from 'module_group', in case the module changed in // some way. For example, if the computation is automatically partitioned // via XLA, the executable's module may have different input/output shapes // than the input module. XLA_HloModule c_module = ExecutorApiFn()->TpuExecutable_HloModuleFn(se_executables[i]); auto cleanup_c_module = absl::MakeCleanup( [&c_module]() { ApiConverter::Destroy(&c_module); }); TF_ASSIGN_OR_RETURN(std::unique_ptr<HloModule> module, ApiConverter::FromC(c_module)); std::shared_ptr<HloModule> module_shared(module.release()); executables.emplace_back(std::make_unique<TpuExecutable>( se_executables[i], std::move(module_shared))); } stream_executor::tpu::SerializedProto_Free(se_module_group.proto); delete[] se_executables; return executables; } // Compiles the HLO module group for ahead-of-time execution. This is // intended for use in static compilation. StatusOr<std::vector<std::unique_ptr<AotCompilationResult>>> CompileAheadOfTime(std::unique_ptr<HloModuleGroup> module_group, const AotCompilationOptions& options) override { return Unimplemented("This compiler does not support CompileAheadOfTime."); } // Returns a function that computes the size in bytes of the logical // buffer that contains a shape. HloCostAnalysis::ShapeSizeFunction ShapeSizeBytesFunction() const override { return [this](const xla::Shape& shape) { XLA_Shape c_shape; ApiConverter::ToC(shape, &c_shape); int64_t bytes = ExecutorApiFn()->TpuCompiler_ShapeSizeFn(compiler_, &c_shape); ApiConverter::Destroy(&c_shape); return bytes; }; } Shape DefaultDeviceShapeRepresentation(const Shape& shape) const override { XLA_Shape host_shape, device_shape; ApiConverter::ToC(shape, &host_shape); ExecutorApiFn()->TpuCompiler_DefaultDeviceShapeRepresentationFn( compiler_, &host_shape, &device_shape); ApiConverter::Destroy(&host_shape); Shape result = ApiConverter::FromC(&device_shape); ApiConverter::Destroy(&device_shape); return result; } private: Tpu_Compiler* compiler_; }; static bool InitModule() { xla::Compiler::RegisterCompilerFactory( tensorflow::tpu::GetTpuPlatformId(), []() { return std::make_unique<TpuCompiler>(); }); return true; } static bool module_initialized = InitModule(); } // namespace } // namespace xla <|endoftext|>
<commit_before>#include "MainForm.moc" #include <QtGui> #include <iostream> #include <sstream> #include <tbb/tbb.h> #include <png.h> MainForm::MainForm(QGraphicsScene* img, nbt* bf, QWidget* parent_) : QGraphicsView(img, parent_), scene_(), bf_(bf), scale_(1), images() { connect(this, SIGNAL(scaleSig()), this, SLOT(scale())); connect(this, SIGNAL(renderNewImage()), this, SLOT(populateSceneItem())); connect(this, SIGNAL(saveToFileSignal()), this, SLOT(saveToFile())); setTransformationAnchor(QGraphicsView::AnchorUnderMouse); } class ApplyFoo { MainForm* mainform_; int i_; tbb::atomic<int>* index_; public: void operator()( const tbb::blocked_range<int32_t>& r ) const { for(int32_t j=r.begin(); j!=r.end(); ++j) { bool result = false; QPoint bp = mainform_->projectCoords(QPoint(j, i_), (4 - mainform_->bf_->set().rotate) % 4); const Image<uint8_t>& image = mainform_->bf_-> getImage(bp.x(), bp.y(), &result); if (!result) { continue; } *index_ += 1; mainform_->images.push(MainForm::image_coords(image, QPoint(bp.x(), bp.y()))); mainform_->renderNewImageEmitter(); } } ApplyFoo(MainForm* mainform, int i, tbb::atomic<int>* index) : mainform_(mainform), i_(i), index_(index) {} /* just for the compiler */ ApplyFoo(const ApplyFoo& rhs) : mainform_(rhs.mainform_), i_(rhs.i_), index_(rhs.index_) {} private: ApplyFoo& operator=(const ApplyFoo&); }; void MainForm::populateScene() { tbb::atomic<int> index; index = 0; QPoint min(bf_->xPos_min(), bf_->zPos_min()); min = projectCoords(min, bf_->set().rotate); QPoint max(bf_->xPos_max(), bf_->zPos_max()); max = projectCoords(max, bf_->set().rotate); min_norm = QPoint(std::min(min.x(), max.x()), std::min(min.y(), max.y())); max_norm = QPoint(std::max(min.x(), max.x()), std::max(min.y(), max.y())); std::stringstream ss; int width = (max_norm.x() - min_norm.x() + 1) * 16; int height = (max_norm.y() - min_norm.y() + 1) * 16; if (bf_->set().oblique) height += 128; ss << "P7\n" << "WIDTH " << width << "\n" << "HEIGHT " << height << "\n" << "DEPTH " << 4 << "\n" << "MAXVAL " << 255 << "\n" << "TUPLTYPE " << "RGB_ALPHA" << "\n" << "ENDHDR" << "\n"; header_size = ss.str().size(); FILE* pam = fopen("test.ppm", "w"); fwrite(ss.str().c_str(), 1, header_size, pam); fseek(pam, width * height * 4 - 1, SEEK_CUR); fwrite("", 1, 1, pam); fclose(pam); for (int i = min_norm.y(); i <= max_norm.y(); ++i) { tbb::parallel_for(tbb::blocked_range<int32_t>(min_norm.x(), max_norm.x() + 1), ApplyFoo(this, i, &index)); if (index > 10000) { std::cerr << "cache cleared!" << std::endl; index = 0; bf_->clearCache(); } } bf_->clearCache(); emit saveToFileSignal(); // QPen pen; // pen.setColor(QColor(255, 0, 0, 255)); // scene()->addEllipse(185, 50, 5, 5, pen); // rotate(270.0f); // 187 52 // setTransform(QTransform().scale(1, 1)); size_t nr_pixels = width * height; pam = fopen("test.ppm", "r"); FILE* out = fopen("test.png", "w"); fseek(pam, header_size, SEEK_CUR); png_struct* pngP; png_info* infoP; pngP = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); infoP = png_create_info_struct(pngP); png_set_IHDR(pngP, infoP, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_init_io(pngP, out); png_write_info(pngP, infoP); png_byte* pngRow = reinterpret_cast<png_byte*>(malloc(width * 4)); for (int i = 0; i < height; ++i) { fread(pngRow, 4, width, pam); png_write_row(pngP, pngRow); } free(pngRow); png_write_end(pngP, infoP); png_destroy_write_struct(&pngP, &infoP); fclose(pam); fclose(out); } void MainForm::renderNewImageEmitter() { emit renderNewImage(); } void MainForm::saveToFile() { scale_ = 1; scale(); QImage image(mapFromScene(scene()->sceneRect()).boundingRect().adjusted(0, 0, -1, -1).size(), QImage::Format_ARGB32); image.fill(0); QPainter painter(&image); render(&painter, painter.viewport(), mapFromScene(scene()->sceneRect()).boundingRect().adjusted(0, 0, -1, -1)); // image.save("image.png"); // exit(1); } QPoint MainForm::projectCoords(QPoint p, int phi) { return projectCoords(p.x(), p.y(), phi); } QPoint MainForm::projectCoords(int _x, int _y, int phi) { if (phi == 0) return QPoint(_x, _y); int cos_phi = phi % 2 - 1; if (!phi) cos_phi = 1; int sin_phi = phi % 2; if (phi == 3) sin_phi = -1; QPoint ret; ret.setX(_x * cos_phi - _y * sin_phi); ret.setY(_x * sin_phi + _y * cos_phi); return ret; } void MainForm::populateSceneItem() { MainForm::image_coords img_coor; if (images.try_pop(img_coor)) { QImage img(&(img_coor.first.data[0]), img_coor.first.cols, img_coor.first.rows, QImage::Format_ARGB32); QGraphicsPixmapItem* pi = scene()->addPixmap(QPixmap::fromImage(img)); pi->setFlag(QGraphicsItem::ItemIsMovable, false); pi->setFlag(QGraphicsItem::ItemIsSelectable, false); QPoint projected = projectCoords(16 * img_coor.second.x(), 16 * img_coor.second.y(), bf_->set().rotate); pi->setPos(projected); if (bf_->set().rotate == 0) { pi->setZValue(img_coor.second.y()); } else if (bf_->set().rotate == 1) { pi->setZValue(img_coor.second.x()); } else if (bf_->set().rotate == 2) { pi->setZValue(-img_coor.second.y()); } else if (bf_->set().rotate == 3) { pi->setZValue(-img_coor.second.x()); } size_t width = img_coor.first.cols; size_t height = img_coor.first.rows; size_t nr_pixels = width * height; int offset_x = projected.x() - min_norm.x() * 16; int offset_y = projected.y() - min_norm.y() * 16; int g_width = (max_norm.x() - min_norm.x() + 1) * 16; int g_height = (max_norm.y() - min_norm.y() + 1) * 16; FILE* pam = fopen("test.ppm", "r+"); fseek(pam, header_size, SEEK_CUR); for (size_t i = 0; i < nr_pixels; ++i) { size_t index = i * 4; std::swap(img_coor.first.data[index], img_coor.first.data[index + 2]); } fseek(pam, offset_y * g_width * 4 + offset_x * 4, SEEK_CUR); for (size_t i = 0; i < height; ++i) { for (size_t j = 0; j < width; ++j) { if (img_coor.first.data[i * width * 4 + j * 4 + 3] != 0) { fwrite(&(img_coor.first.data[i * width * 4 + j * 4]), 4, 1, pam); } else { fseek(pam, 4, SEEK_CUR); } } fseek(pam, g_width * 4 - width * 4, SEEK_CUR); } fclose(pam); } else { std::cerr << "must not happen!" << std::endl; exit(1); } } void MainForm::scale() { if (scale_ <= 0) { setTransform(QTransform().scale(1.0 / pow(2.0, abs(scale_ - 1)), 1.0 / pow(2.0, abs(scale_ - 1)))); } else { setTransform(QTransform().scale(scale_, scale_)); } } void MainForm::mousePressEvent(QMouseEvent* mevent) { switch (mevent->button()) { case Qt::LeftButton: ++scale_; emit scaleSig(); break; case Qt::MidButton: break; case Qt::RightButton: --scale_; emit scaleSig(); break; default: break; } return; } void MainForm::mouseDoubleClickEvent(QMouseEvent* mevent) { mousePressEvent(mevent); return; } <commit_msg>render scene not view, remove png/pam stuff from MainForm<commit_after>#include "MainForm.moc" #include <QtGui> #include <iostream> #include <sstream> #include <tbb/tbb.h> #include <png.h> MainForm::MainForm(QGraphicsScene* img, nbt* bf, QWidget* parent_) : QGraphicsView(img, parent_), scene_(), bf_(bf), scale_(1), images() { connect(this, SIGNAL(scaleSig()), this, SLOT(scale())); connect(this, SIGNAL(renderNewImage()), this, SLOT(populateSceneItem())); connect(this, SIGNAL(saveToFileSignal()), this, SLOT(saveToFile())); setTransformationAnchor(QGraphicsView::AnchorUnderMouse); } class ApplyFoo { MainForm* mainform_; int i_; tbb::atomic<int>* index_; public: void operator()( const tbb::blocked_range<int32_t>& r ) const { for(int32_t j=r.begin(); j!=r.end(); ++j) { bool result = false; QPoint bp = mainform_->projectCoords(QPoint(j, i_), (4 - mainform_->bf_->set().rotate) % 4); const Image<uint8_t>& image = mainform_->bf_-> getImage(bp.x(), bp.y(), &result); if (!result) { continue; } *index_ += 1; mainform_->images.push(MainForm::image_coords(image, QPoint(bp.x(), bp.y()))); mainform_->renderNewImageEmitter(); } } ApplyFoo(MainForm* mainform, int i, tbb::atomic<int>* index) : mainform_(mainform), i_(i), index_(index) {} /* just for the compiler */ ApplyFoo(const ApplyFoo& rhs) : mainform_(rhs.mainform_), i_(rhs.i_), index_(rhs.index_) {} private: ApplyFoo& operator=(const ApplyFoo&); }; void MainForm::populateScene() { tbb::atomic<int> index; index = 0; QPoint min(bf_->xPos_min(), bf_->zPos_min()); min = projectCoords(min, bf_->set().rotate); QPoint max(bf_->xPos_max(), bf_->zPos_max()); max = projectCoords(max, bf_->set().rotate); min_norm = QPoint(std::min(min.x(), max.x()), std::min(min.y(), max.y())); max_norm = QPoint(std::max(min.x(), max.x()), std::max(min.y(), max.y())); for (int i = min_norm.y(); i <= max_norm.y(); ++i) { tbb::parallel_for(tbb::blocked_range<int32_t>(min_norm.x(), max_norm.x() + 1), ApplyFoo(this, i, &index)); if (index > 10000) { std::cerr << "cache cleared!" << std::endl; index = 0; bf_->clearCache(); } } bf_->clearCache(); emit saveToFileSignal(); } void MainForm::renderNewImageEmitter() { emit renderNewImage(); } void MainForm::saveToFile() { QImage image(scene()->sceneRect().toRect().size(), QImage::Format_ARGB32); image.fill(0); QPainter painter(&image); scene()->render(&painter, painter.viewport(), scene()->sceneRect()); image.save("image.png"); fprintf(stderr, "image saved!\n"); // exit(1); } QPoint MainForm::projectCoords(QPoint p, int phi) { return projectCoords(p.x(), p.y(), phi); } QPoint MainForm::projectCoords(int _x, int _y, int phi) { if (phi == 0) return QPoint(_x, _y); int cos_phi = phi % 2 - 1; if (!phi) cos_phi = 1; int sin_phi = phi % 2; if (phi == 3) sin_phi = -1; QPoint ret; ret.setX(_x * cos_phi - _y * sin_phi); ret.setY(_x * sin_phi + _y * cos_phi); return ret; } void MainForm::populateSceneItem() { MainForm::image_coords img_coor; if (images.try_pop(img_coor)) { QImage img(&(img_coor.first.data[0]), img_coor.first.cols, img_coor.first.rows, QImage::Format_ARGB32); QGraphicsPixmapItem* pi = scene()->addPixmap(QPixmap::fromImage(img)); pi->setFlag(QGraphicsItem::ItemIsMovable, false); pi->setFlag(QGraphicsItem::ItemIsSelectable, false); QPoint projected = projectCoords(16 * img_coor.second.x(), 16 * img_coor.second.y(), bf_->set().rotate); pi->setPos(projected); if (bf_->set().rotate == 0) { pi->setZValue(img_coor.second.y()); } else if (bf_->set().rotate == 1) { pi->setZValue(img_coor.second.x()); } else if (bf_->set().rotate == 2) { pi->setZValue(-img_coor.second.y()); } else if (bf_->set().rotate == 3) { pi->setZValue(-img_coor.second.x()); } } else { std::cerr << "must not happen!" << std::endl; exit(1); } } void MainForm::scale() { if (scale_ <= 0) { setTransform(QTransform().scale(1.0 / pow(2.0, abs(scale_ - 1)), 1.0 / pow(2.0, abs(scale_ - 1)))); } else { setTransform(QTransform().scale(scale_, scale_)); } } void MainForm::mousePressEvent(QMouseEvent* mevent) { switch (mevent->button()) { case Qt::LeftButton: ++scale_; emit scaleSig(); break; case Qt::MidButton: break; case Qt::RightButton: --scale_; emit scaleSig(); break; default: break; } return; } void MainForm::mouseDoubleClickEvent(QMouseEvent* mevent) { mousePressEvent(mevent); return; } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "MortarGapHeatTransferAction.h" #include "AddVariableAction.h" #include "FEProblem.h" #include "libmesh/string_to_enum.h" #include "NonlinearSystem.h" #include "ModularGapConductanceConstraint.h" #include "GapFluxModelRadiation.h" #include "GapFluxModelConduction.h" // Counter for modular user objects static unsigned int thermal_action_userobject_radiation_counter = 0; static unsigned int thermal_action_userobject_conduction_counter = 0; registerMooseAction("HeatConductionApp", MortarGapHeatTransferAction, "append_mesh_generator"); registerMooseAction("HeatConductionApp", MortarGapHeatTransferAction, "add_mortar_variable"); registerMooseAction("HeatConductionApp", MortarGapHeatTransferAction, "add_constraint"); registerMooseAction("HeatConductionApp", MortarGapHeatTransferAction, "add_user_object"); InputParameters MortarGapHeatTransferAction::validParams() { InputParameters params = Action::validParams(); params.addClassDescription( "Action that controls the creation of all of the necessary objects for " "calculation of heat transfer through an open/closed gap"); // Modular mortar gap conductance MooseEnum gap_heat_transfer_formulation("point_segment mortar", "mortar"); params.addParam<MooseEnum>( "formulation", gap_heat_transfer_formulation, "The gap heat transfer formulation to be used"); params.addParam<Real>("thermal_lm_scaling", 1., "Scaling factor to apply to the thermal Lagrange multiplier variable"); params += ModularGapConductanceConstraint::validParams(); params += GapFluxModelRadiation::validParams(); params += GapFluxModelConduction::validParams(); // params.makeParamNotRequired<std::vector<BoundaryName>>("boundary"); params.makeParamNotRequired<BoundaryName>("primary_boundary"); params.makeParamNotRequired<SubdomainName>("primary_subdomain"); params.makeParamNotRequired<BoundaryName>("secondary_boundary"); params.makeParamNotRequired<SubdomainName>("secondary_subdomain"); params.makeParamNotRequired<std::vector<VariableName>>("temperature"); params.addParam<std::vector<UserObjectName>>( "user_object_physics", "The list of physical contributions to gap heat transfer implemented in user objects"); return params; } MortarGapHeatTransferAction::MortarGapHeatTransferAction(const InputParameters & params) : Action(params), _formulation(getParam<MooseEnum>("formulation").getEnum<GapHeatTransferFormulation>()), _user_provided_mortar_meshes(false) { if (params.isParamSetByUser("primary_subdomain") && params.isParamSetByUser("secondary_subdomain")) { mooseInfo("Mortar gap heat transfer action is using the lower-dimensional domains provided by " "the user"); _user_provided_mortar_meshes = true; } else mooseInfo("Mortar gap heat transfer action is creating new lower-dimensional domains"); } void MortarGapHeatTransferAction::act() { if (_formulation == GapHeatTransferFormulation::MORTAR) { if (_current_task == "append_mesh_generator") addMortarMesh(); else if (_current_task == "add_mortar_variable") addMortarVariable(); if (_current_task == "add_constraint") addConstraints(); else if (_current_task == "add_user_object") addUserObjects(); } else paramError( "formulation", "The formulation selected to solve gap heat transfer physics is not currently available."); } void MortarGapHeatTransferAction::coreMortarMesh() { if (!(_app.isRecovering() && _app.isUltimateMaster()) && !_app.masterMesh()) { std::string action_name = MooseUtils::shortName(name()); const MeshGeneratorName primary_name = action_name + "_primary_subdomain" + "_generator"; const MeshGeneratorName secondary_name = action_name + "_secondary_subdomain" + "_generator"; auto primary_params = _factory.getValidParams("LowerDBlockFromSidesetGenerator"); auto secondary_params = _factory.getValidParams("LowerDBlockFromSidesetGenerator"); primary_params.set<SubdomainName>("new_block_name") = action_name + "_primary_subdomain"; secondary_params.set<SubdomainName>("new_block_name") = action_name + "_secondary_subdomain"; primary_params.set<std::vector<BoundaryName>>("sidesets") = { getParam<BoundaryName>("primary_boundary")}; secondary_params.set<std::vector<BoundaryName>>("sidesets") = { getParam<BoundaryName>("secondary_boundary")}; _app.appendMeshGenerator("LowerDBlockFromSidesetGenerator", primary_name, primary_params); _app.appendMeshGenerator("LowerDBlockFromSidesetGenerator", secondary_name, secondary_params); } } void MortarGapHeatTransferAction::addRelationshipManagers(Moose::RelationshipManagerType input_rm_type) { checkForExistingSubdomains(); std::string action_name = MooseUtils::shortName(name()); auto params = MortarConstraintBase::validParams(); params.set<bool>("use_displaced_mesh") = getParam<bool>("use_displaced_mesh"); params.set<BoundaryName>("primary_boundary") = getParam<BoundaryName>("primary_boundary"); params.set<BoundaryName>("secondary_boundary") = getParam<BoundaryName>("secondary_boundary"); if (_user_provided_mortar_meshes) { params.set<SubdomainName>("primary_subdomain") = getParam<SubdomainName>("primary_subdomain"); params.set<SubdomainName>("secondary_subdomain") = getParam<SubdomainName>("secondary_subdomain"); } else { params.set<SubdomainName>("primary_subdomain") = action_name + "_primary_subdomain"; params.set<SubdomainName>("secondary_subdomain") = action_name + "_secondary_subdomain"; } addRelationshipManagers(input_rm_type, params); } void MortarGapHeatTransferAction::addMortarVariable() { checkForExistingSubdomains(); InputParameters params = _factory.getValidParams("MooseVariableBase"); const std::string & temperature = getParam<std::vector<VariableName>>("temperature")[0]; std::string action_name = MooseUtils::shortName(name()); mooseAssert(_problem->systemBaseNonlinear().hasVariable(temperature), "Temperature variable is missing"); const auto primal_type = _problem->systemBaseNonlinear().system().variable_type(temperature); const int lm_order = primal_type.order.get_order(); if (primal_type.family != LAGRANGE) mooseError("The mortar thermal action can only be used with LAGRANGE finite elements"); params.set<MooseEnum>("family") = Utility::enum_to_string<FEFamily>(primal_type.family); params.set<MooseEnum>("order") = Utility::enum_to_string<Order>(OrderWrapper{lm_order}); if (_user_provided_mortar_meshes) params.set<std::vector<SubdomainName>>("block") = { getParam<SubdomainName>("secondary_subdomain")}; else params.set<std::vector<SubdomainName>>("block") = {action_name + "_secondary_subdomain"}; params.set<std::vector<Real>>("scaling") = {getParam<Real>("thermal_lm_scaling")}; auto fe_type = AddVariableAction::feType(params); auto var_type = AddVariableAction::variableType(fe_type); _problem->addVariable(var_type, action_name + "_thermal_lm", params); } void MortarGapHeatTransferAction::addConstraints() { checkForExistingSubdomains(); InputParameters params = _factory.getValidParams("ModularGapConductanceConstraint"); const std::string action_name = MooseUtils::shortName(name()); params.applyParameters(parameters()); params.set<bool>("correct_edge_dropping") = true; params.set<bool>("use_displaced_mesh") = true; params.set<BoundaryName>("primary_boundary") = getParam<BoundaryName>("primary_boundary"); params.set<BoundaryName>("secondary_boundary") = getParam<BoundaryName>("secondary_boundary"); if (_user_provided_mortar_meshes) { params.set<SubdomainName>("primary_subdomain") = getParam<SubdomainName>("primary_subdomain"); params.set<SubdomainName>("secondary_subdomain") = getParam<SubdomainName>("secondary_subdomain"); } else { params.set<SubdomainName>("primary_subdomain") = action_name + "_primary_subdomain"; params.set<SubdomainName>("secondary_subdomain") = action_name + "_secondary_subdomain"; } params.set<NonlinearVariableName>("variable") = action_name + "_thermal_lm"; params.set<VariableName>("secondary_variable") = getParam<std::vector<VariableName>>("temperature")[0]; const std::vector<UserObjectName> user_object_vector = getParam<std::vector<UserObjectName>>("user_object_physics"); std::vector<UserObjectName> uoname_strings(0); unsigned int conduction_index = 0; unsigned int radiation_index = 0; for (const auto i : index_range(user_object_vector)) { if (user_object_vector[i] == "GapFluxModelConduction") uoname_strings.push_back("gap_flux_model_conduction_object_" + MooseUtils::shortName(name()) + "_" + Moose::stringify(conduction_index++)); else if (user_object_vector[i] == "GapFluxModelRadiation") uoname_strings.push_back("gap_flux_model_radiation_object_" + MooseUtils::shortName(name()) + "_" + Moose::stringify(radiation_index++)); } params.set<std::vector<UserObjectName>>("gap_flux_models") = uoname_strings; _problem->addConstraint( "ModularGapConductanceConstraint", action_name + "_ModularGapConductanceConstraint", params); } void MortarGapHeatTransferAction::addMortarMesh() { // Let's browse over existing mechanical actions to see if the primary and secondary // subdomains have been created checkForExistingSubdomains(); // We may have available lower-dimensional domains (e.g. from a mechanical contact action), whose // subdomains can be reused for adding mortar variables and constraints. if (!_user_provided_mortar_meshes) coreMortarMesh(); } void MortarGapHeatTransferAction::addUserObjects() { // It is risky to apply this optimization to contact problems // since the problem configuration may be changed during Jacobian // evaluation. We therefore turn it off for all contact problems so that // PETSc-3.8.4 or higher will have the same behavior as PETSc-3.8.3 or older. mooseAssert(_problem, "Problem pointer is null"); if (!_problem->isSNESMFReuseBaseSetbyUser()) _problem->setSNESMFReuseBase(false, false); const std::vector<UserObjectName> user_object_vector = getParam<std::vector<UserObjectName>>("user_object_physics"); for (const auto i : index_range(user_object_vector)) { if (user_object_vector[i] == "GapFluxModelConduction") { auto var_params = _factory.getValidParams("GapFluxModelConduction"); var_params.set<std::vector<VariableName>>("temperature") = getParam<std::vector<VariableName>>("temperature"); var_params.set<Real>("gap_conductivity") = getParam<Real>("gap_conductivity"); if (isParamValid("gap_conductivity_function")) var_params.set<FunctionName>("gap_conductivity_function") = getParam<FunctionName>("gap_conductivity_function"); if (isParamValid("gap_conductivity_function_variable")) var_params.set<std::vector<VariableName>>("gap_conductivity_function_variable") = getParam<std::vector<VariableName>>("gap_conductivity_function_variable"); var_params.set<Real>("min_gap") = getParam<Real>("min_gap"); var_params.set<unsigned int>("min_gap_order") = getParam<unsigned int>("min_gap_order"); var_params.set<std::vector<BoundaryName>>("boundary") = getParam<std::vector<BoundaryName>>("boundary"); var_params.set<bool>("use_displaced_mesh") = true; _problem->addUserObject("GapFluxModelConduction", "gap_flux_model_conduction_object_" + MooseUtils::shortName(name()) + "_" + Moose::stringify(thermal_action_userobject_conduction_counter++), var_params); } else if (user_object_vector[i] == "GapFluxModelRadiation") { auto var_params = _factory.getValidParams("GapFluxModelRadiation"); var_params.set<Real>("stefan_boltzmann") = getParam<Real>("stefan_boltzmann"); var_params.set<Real>("primary_emissivity") = getParam<Real>("primary_emissivity"); var_params.set<Real>("secondary_emissivity") = getParam<Real>("secondary_emissivity"); var_params.set<std::vector<BoundaryName>>("boundary") = getParam<std::vector<BoundaryName>>("boundary"); var_params.set<std::vector<VariableName>>("temperature") = getParam<std::vector<VariableName>>("temperature"); var_params.set<bool>("use_displaced_mesh") = true; _problem->addUserObject("GapFluxModelRadiation", "gap_flux_model_radiation_object_" + MooseUtils::shortName(name()) + "_" + Moose::stringify(thermal_action_userobject_radiation_counter++), var_params); } else paramError("user_object_physics", "At least one of the user objects provided to capture gap heat transfer physics " "using a mortar formulation are not currently supported"); } } void MortarGapHeatTransferAction::checkForExistingSubdomains() { if (parameters().isParamSetByUser("primary_subdomain") && parameters().isParamSetByUser("secondary_subdomain")) { _user_provided_mortar_meshes = true; } else _user_provided_mortar_meshes = false; } <commit_msg>Only subdomains are not required (can be created in the action)<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "MortarGapHeatTransferAction.h" #include "AddVariableAction.h" #include "FEProblem.h" #include "libmesh/string_to_enum.h" #include "NonlinearSystem.h" #include "ModularGapConductanceConstraint.h" #include "GapFluxModelRadiation.h" #include "GapFluxModelConduction.h" // Counter for modular user objects static unsigned int thermal_action_userobject_radiation_counter = 0; static unsigned int thermal_action_userobject_conduction_counter = 0; registerMooseAction("HeatConductionApp", MortarGapHeatTransferAction, "append_mesh_generator"); registerMooseAction("HeatConductionApp", MortarGapHeatTransferAction, "add_mortar_variable"); registerMooseAction("HeatConductionApp", MortarGapHeatTransferAction, "add_constraint"); registerMooseAction("HeatConductionApp", MortarGapHeatTransferAction, "add_user_object"); InputParameters MortarGapHeatTransferAction::validParams() { InputParameters params = Action::validParams(); params.addClassDescription( "Action that controls the creation of all of the necessary objects for " "calculation of heat transfer through an open/closed gap"); // Modular mortar gap conductance MooseEnum gap_heat_transfer_formulation("point_segment mortar", "mortar"); params.addParam<MooseEnum>( "formulation", gap_heat_transfer_formulation, "The gap heat transfer formulation to be used"); params.addParam<Real>("thermal_lm_scaling", 1., "Scaling factor to apply to the thermal Lagrange multiplier variable"); params += ModularGapConductanceConstraint::validParams(); params += GapFluxModelRadiation::validParams(); params += GapFluxModelConduction::validParams(); params.makeParamNotRequired<SubdomainName>("primary_subdomain"); params.makeParamNotRequired<SubdomainName>("secondary_subdomain"); params.addParam<std::vector<UserObjectName>>( "user_object_physics", "The list of physical contributions to gap heat transfer implemented in user objects"); return params; } MortarGapHeatTransferAction::MortarGapHeatTransferAction(const InputParameters & params) : Action(params), _formulation(getParam<MooseEnum>("formulation").getEnum<GapHeatTransferFormulation>()), _user_provided_mortar_meshes(false) { if (params.isParamSetByUser("primary_subdomain") && params.isParamSetByUser("secondary_subdomain")) { mooseInfo("Mortar gap heat transfer action is using the lower-dimensional domains provided by " "the user"); _user_provided_mortar_meshes = true; } else mooseInfo("Mortar gap heat transfer action is creating new lower-dimensional domains"); } void MortarGapHeatTransferAction::act() { if (_formulation == GapHeatTransferFormulation::MORTAR) { if (_current_task == "append_mesh_generator") addMortarMesh(); else if (_current_task == "add_mortar_variable") addMortarVariable(); if (_current_task == "add_constraint") addConstraints(); else if (_current_task == "add_user_object") addUserObjects(); } else paramError( "formulation", "The formulation selected to solve gap heat transfer physics is not currently available."); } void MortarGapHeatTransferAction::coreMortarMesh() { if (!(_app.isRecovering() && _app.isUltimateMaster()) && !_app.masterMesh()) { std::string action_name = MooseUtils::shortName(name()); const MeshGeneratorName primary_name = action_name + "_primary_subdomain" + "_generator"; const MeshGeneratorName secondary_name = action_name + "_secondary_subdomain" + "_generator"; auto primary_params = _factory.getValidParams("LowerDBlockFromSidesetGenerator"); auto secondary_params = _factory.getValidParams("LowerDBlockFromSidesetGenerator"); primary_params.set<SubdomainName>("new_block_name") = action_name + "_primary_subdomain"; secondary_params.set<SubdomainName>("new_block_name") = action_name + "_secondary_subdomain"; primary_params.set<std::vector<BoundaryName>>("sidesets") = { getParam<BoundaryName>("primary_boundary")}; secondary_params.set<std::vector<BoundaryName>>("sidesets") = { getParam<BoundaryName>("secondary_boundary")}; _app.appendMeshGenerator("LowerDBlockFromSidesetGenerator", primary_name, primary_params); _app.appendMeshGenerator("LowerDBlockFromSidesetGenerator", secondary_name, secondary_params); } } void MortarGapHeatTransferAction::addRelationshipManagers(Moose::RelationshipManagerType input_rm_type) { checkForExistingSubdomains(); std::string action_name = MooseUtils::shortName(name()); auto params = MortarConstraintBase::validParams(); params.set<bool>("use_displaced_mesh") = getParam<bool>("use_displaced_mesh"); params.set<BoundaryName>("primary_boundary") = getParam<BoundaryName>("primary_boundary"); params.set<BoundaryName>("secondary_boundary") = getParam<BoundaryName>("secondary_boundary"); if (_user_provided_mortar_meshes) { params.set<SubdomainName>("primary_subdomain") = getParam<SubdomainName>("primary_subdomain"); params.set<SubdomainName>("secondary_subdomain") = getParam<SubdomainName>("secondary_subdomain"); } else { params.set<SubdomainName>("primary_subdomain") = action_name + "_primary_subdomain"; params.set<SubdomainName>("secondary_subdomain") = action_name + "_secondary_subdomain"; } addRelationshipManagers(input_rm_type, params); } void MortarGapHeatTransferAction::addMortarVariable() { checkForExistingSubdomains(); InputParameters params = _factory.getValidParams("MooseVariableBase"); const std::string & temperature = getParam<std::vector<VariableName>>("temperature")[0]; std::string action_name = MooseUtils::shortName(name()); mooseAssert(_problem->systemBaseNonlinear().hasVariable(temperature), "Temperature variable is missing"); const auto primal_type = _problem->systemBaseNonlinear().system().variable_type(temperature); const int lm_order = primal_type.order.get_order(); if (primal_type.family != LAGRANGE) mooseError("The mortar thermal action can only be used with LAGRANGE finite elements"); params.set<MooseEnum>("family") = Utility::enum_to_string<FEFamily>(primal_type.family); params.set<MooseEnum>("order") = Utility::enum_to_string<Order>(OrderWrapper{lm_order}); if (_user_provided_mortar_meshes) params.set<std::vector<SubdomainName>>("block") = { getParam<SubdomainName>("secondary_subdomain")}; else params.set<std::vector<SubdomainName>>("block") = {action_name + "_secondary_subdomain"}; params.set<std::vector<Real>>("scaling") = {getParam<Real>("thermal_lm_scaling")}; auto fe_type = AddVariableAction::feType(params); auto var_type = AddVariableAction::variableType(fe_type); _problem->addVariable(var_type, action_name + "_thermal_lm", params); } void MortarGapHeatTransferAction::addConstraints() { checkForExistingSubdomains(); InputParameters params = _factory.getValidParams("ModularGapConductanceConstraint"); const std::string action_name = MooseUtils::shortName(name()); params.applyParameters(parameters()); params.set<bool>("correct_edge_dropping") = true; params.set<bool>("use_displaced_mesh") = true; params.set<BoundaryName>("primary_boundary") = getParam<BoundaryName>("primary_boundary"); params.set<BoundaryName>("secondary_boundary") = getParam<BoundaryName>("secondary_boundary"); if (_user_provided_mortar_meshes) { params.set<SubdomainName>("primary_subdomain") = getParam<SubdomainName>("primary_subdomain"); params.set<SubdomainName>("secondary_subdomain") = getParam<SubdomainName>("secondary_subdomain"); } else { params.set<SubdomainName>("primary_subdomain") = action_name + "_primary_subdomain"; params.set<SubdomainName>("secondary_subdomain") = action_name + "_secondary_subdomain"; } params.set<NonlinearVariableName>("variable") = action_name + "_thermal_lm"; params.set<VariableName>("secondary_variable") = getParam<std::vector<VariableName>>("temperature")[0]; const std::vector<UserObjectName> user_object_vector = getParam<std::vector<UserObjectName>>("user_object_physics"); std::vector<UserObjectName> uoname_strings(0); unsigned int conduction_index = 0; unsigned int radiation_index = 0; for (const auto i : index_range(user_object_vector)) { if (user_object_vector[i] == "GapFluxModelConduction") uoname_strings.push_back("gap_flux_model_conduction_object_" + MooseUtils::shortName(name()) + "_" + Moose::stringify(conduction_index++)); else if (user_object_vector[i] == "GapFluxModelRadiation") uoname_strings.push_back("gap_flux_model_radiation_object_" + MooseUtils::shortName(name()) + "_" + Moose::stringify(radiation_index++)); } params.set<std::vector<UserObjectName>>("gap_flux_models") = uoname_strings; _problem->addConstraint( "ModularGapConductanceConstraint", action_name + "_ModularGapConductanceConstraint", params); } void MortarGapHeatTransferAction::addMortarMesh() { // Let's browse over existing mechanical actions to see if the primary and secondary // subdomains have been created checkForExistingSubdomains(); // We may have available lower-dimensional domains (e.g. from a mechanical contact action), whose // subdomains can be reused for adding mortar variables and constraints. if (!_user_provided_mortar_meshes) coreMortarMesh(); } void MortarGapHeatTransferAction::addUserObjects() { // It is risky to apply this optimization to contact problems // since the problem configuration may be changed during Jacobian // evaluation. We therefore turn it off for all contact problems so that // PETSc-3.8.4 or higher will have the same behavior as PETSc-3.8.3 or older. mooseAssert(_problem, "Problem pointer is null"); if (!_problem->isSNESMFReuseBaseSetbyUser()) _problem->setSNESMFReuseBase(false, false); const std::vector<UserObjectName> user_object_vector = getParam<std::vector<UserObjectName>>("user_object_physics"); for (const auto i : index_range(user_object_vector)) { if (user_object_vector[i] == "GapFluxModelConduction") { auto var_params = _factory.getValidParams("GapFluxModelConduction"); var_params.set<std::vector<VariableName>>("temperature") = getParam<std::vector<VariableName>>("temperature"); var_params.set<Real>("gap_conductivity") = getParam<Real>("gap_conductivity"); if (isParamValid("gap_conductivity_function")) var_params.set<FunctionName>("gap_conductivity_function") = getParam<FunctionName>("gap_conductivity_function"); if (isParamValid("gap_conductivity_function_variable")) var_params.set<std::vector<VariableName>>("gap_conductivity_function_variable") = getParam<std::vector<VariableName>>("gap_conductivity_function_variable"); var_params.set<Real>("min_gap") = getParam<Real>("min_gap"); var_params.set<unsigned int>("min_gap_order") = getParam<unsigned int>("min_gap_order"); var_params.set<std::vector<BoundaryName>>("boundary") = getParam<std::vector<BoundaryName>>("boundary"); var_params.set<bool>("use_displaced_mesh") = true; _problem->addUserObject("GapFluxModelConduction", "gap_flux_model_conduction_object_" + MooseUtils::shortName(name()) + "_" + Moose::stringify(thermal_action_userobject_conduction_counter++), var_params); } else if (user_object_vector[i] == "GapFluxModelRadiation") { auto var_params = _factory.getValidParams("GapFluxModelRadiation"); var_params.set<Real>("stefan_boltzmann") = getParam<Real>("stefan_boltzmann"); var_params.set<Real>("primary_emissivity") = getParam<Real>("primary_emissivity"); var_params.set<Real>("secondary_emissivity") = getParam<Real>("secondary_emissivity"); var_params.set<std::vector<BoundaryName>>("boundary") = getParam<std::vector<BoundaryName>>("boundary"); var_params.set<std::vector<VariableName>>("temperature") = getParam<std::vector<VariableName>>("temperature"); var_params.set<bool>("use_displaced_mesh") = true; _problem->addUserObject("GapFluxModelRadiation", "gap_flux_model_radiation_object_" + MooseUtils::shortName(name()) + "_" + Moose::stringify(thermal_action_userobject_radiation_counter++), var_params); } else paramError("user_object_physics", "At least one of the user objects provided to capture gap heat transfer physics " "using a mortar formulation are not currently supported"); } } void MortarGapHeatTransferAction::checkForExistingSubdomains() { if (parameters().isParamSetByUser("primary_subdomain") && parameters().isParamSetByUser("secondary_subdomain")) { _user_provided_mortar_meshes = true; } else _user_provided_mortar_meshes = false; } <|endoftext|>
<commit_before>#include <boost/format.hpp> #include <boost/make_shared.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/range/adaptor/map.hpp> #include "ManipulatorMarker.h" #include "or_conversions.h" using boost::format; using boost::str; using boost::adaptors::map_values; using interactive_markers::InteractiveMarkerServer; using visualization_msgs::InteractiveMarkerControl; using visualization_msgs::InteractiveMarkerFeedback; using visualization_msgs::InteractiveMarkerFeedbackConstPtr; using OpenRAVE::EnvironmentBasePtr; using OpenRAVE::RobotBasePtr; using OpenRAVE::KinBody; using OpenRAVE::IkSolverBasePtr; typedef OpenRAVE::RobotBase::RobotStateSaver RobotStateSaver; typedef boost::shared_ptr<InteractiveMarkerServer> InteractiveMarkerServerPtr; typedef OpenRAVE::RobotBase::ManipulatorPtr ManipulatorPtr; typedef OpenRAVE::KinBody::Link::GeometryPtr GeometryPtr; typedef OpenRAVE::KinBody::LinkPtr LinkPtr; typedef OpenRAVE::KinBody::LinkInfo LinkInfo; typedef OpenRAVE::KinBody::LinkInfoConstPtr LinkInfoConstPtr; typedef OpenRAVE::KinBody::JointPtr JointPtr; typedef OpenRAVE::KinBody::JointInfo JointInfo; typedef OpenRAVE::KinBody::JointInfoConstPtr JointInfoConstPtr; typedef OpenRAVE::RobotBase::ManipulatorInfo ManipulatorInfo; typedef OpenRAVE::RobotBase::ManipulatorInfoConstPtr ManipulatorInfoConstPtr; typedef OpenRAVE::RobotBase::AttachedSensorInfo AttachedSensorInfo; typedef OpenRAVE::RobotBase::AttachedSensorInfoConstPtr AttachedSensorInfoConstPtr; // TODO: Don't hardcode this. static std::string const kWorldFrameId = "/world"; static std::string const kGhostKey = "interactive_marker::ghost"; namespace or_interactivemarker { OpenRAVE::Vector const ManipulatorMarker::kValidColor(0, 1, 0, 0.4); OpenRAVE::Vector const ManipulatorMarker::kInvalidColor(1, 0, 0, 0.4); ManipulatorMarker::ManipulatorMarker(InteractiveMarkerServerPtr server, ManipulatorPtr manipulator) : server_(server) , manipulator_(manipulator) , changed_pose_(true) , has_ik_(true) , current_pose_(manipulator->GetEndEffectorTransform()) { BOOST_ASSERT(server_); BOOST_ASSERT(manipulator); // Create the ghost manipulator. CreateGeometry(); // Create a 6-DOF pose control. ik_marker_.header.frame_id = kWorldFrameId; ik_marker_.name = id(); ik_marker_.description = manipulator_->GetName(); ik_marker_.pose = toROSPose(manipulator->GetEndEffectorTransform()); ik_marker_.scale = 0.25; { InteractiveMarkerControl control; control.orientation.w = 1; control.orientation.x = 1; control.orientation.y = 0; control.orientation.z = 0; control.name = "rotate_x"; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; ik_marker_.controls.push_back(control); control.name = "move_x"; control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS; ik_marker_.controls.push_back(control); control.orientation.w = 1; control.orientation.x = 0; control.orientation.y = 1; control.orientation.z = 0; control.name = "rotate_y"; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; ik_marker_.controls.push_back(control); control.name = "move_y"; control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS; ik_marker_.controls.push_back(control); control.orientation.w = 1; control.orientation.x = 0; control.orientation.y = 0; control.orientation.z = 1; control.name = "rotate_z"; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; ik_marker_.controls.push_back(control); control.name = "move_z"; control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS; ik_marker_.controls.push_back(control); } server_->insert(ik_marker_); server_->setCallback(ik_marker_.name, boost::bind(&ManipulatorMarker::IkFeedback, this, _1)); CreateMenu(); } ManipulatorMarker::~ManipulatorMarker() { server_->erase(ik_marker_.name); } std::string ManipulatorMarker::id() const { OpenRAVE::RobotBasePtr const robot = manipulator_->GetRobot(); OpenRAVE::EnvironmentBasePtr const env = robot->GetEnv(); int const environment_id = OpenRAVE::RaveGetEnvironmentId(env); return str(format("Environment[%d].KinBody[%s].Manipulator[%s]") % environment_id % robot->GetName() % manipulator_->GetName()); } bool ManipulatorMarker::EnvironmentSync() { ManipulatorPtr const manipulator = manipulator_; RobotBasePtr const robot = manipulator->GetRobot(); IkSolverBasePtr const ik_solver = manipulator->GetIkSolver(); RobotStateSaver const saver(robot, KinBody::Save_LinkTransformation); // Figure out what the free joints are. size_t const num_free = ik_solver->GetNumFreeParameters(); std::vector<JointPtr> free_joints; InferFreeJoints(&free_joints); BOOST_ASSERT(free_joints.size() == num_free); std::vector<int> free_dof_indices; for (JointPtr const &free_joint : free_joints) { free_dof_indices.push_back(free_joint->GetJointIndex()); } if (ik_solver) { RobotStateSaver const free_saver(robot, KinBody::Save_LinkTransformation); // Default to the current configuration of the robot. if (current_free_.size() != num_free) { robot->GetDOFValues(current_free_, free_dof_indices); } // Extract free parameters from the joint controls. bool changed_free = false; for (size_t ifree = 0; ifree < num_free; ++ifree) { JointPtr const &joint = free_joints[ifree]; auto const it = free_joint_markers_.find(joint.get()); if (it == free_joint_markers_.end()) { continue; } // Invalidate the IK solution if we change the free joint. JointMarkerPtr &joint_marker = it->second; if (joint_marker->angle() != current_free_[ifree]) { current_free_[ifree] = joint_marker->angle(); changed_free = true; } } // Set and clamp these joint values to be within limits. robot->SetDOFValues(current_free_, KinBody::CLA_CheckLimitsSilent, free_dof_indices); robot->GetDOFValues(current_free_, free_dof_indices); // Update our IK solution. if (changed_pose_ || changed_free) { std::vector<OpenRAVE::dReal> new_ik; OpenRAVE::IkParameterization ik_param; ik_param.SetTransform6D(current_pose_); std::vector<std::vector<OpenRAVE::dReal> > ik_solutions; has_ik_ = manipulator_->FindIKSolution(ik_param, new_ik, 0); if (has_ik_) { current_ik_ = new_ik; } } } changed_pose_ = false; // Update the pose of the ghost manipulator. auto const dof_indices = manipulator->GetArmIndices(); robot->SetDOFValues(current_ik_, 1, dof_indices); bool is_changed = false; for (LinkMarkerPtr const &link_marker : link_markers_ | map_values) { bool const is_link_changed = link_marker->EnvironmentSync(); if (!is_link_changed) { OpenRAVE::Transform const link_pose = link_marker->link()->GetTransform(); link_marker->set_pose(link_pose); } else { UpdateMenu(link_marker); } // Set the color to indicate whether we have a valid IK solution. if (has_ik_) { link_marker->set_color(kValidColor); } else { link_marker->set_color(kInvalidColor); } is_changed = is_changed || is_link_changed; } if (ik_solver) { for (JointPtr const &joint : free_joints) { if (!joint) { continue; } // Lazily create the marker if it is missing. JointMarkerPtr &joint_marker = free_joint_markers_[joint.get()]; if (!joint_marker) { joint_marker = boost::make_shared<JointMarker>(server_, joint); } // Update the pose of the control to match the ghost arm. OpenRAVE::Transform const joint_pose = JointMarker::GetJointPose(joint); joint_marker->set_pose(joint_pose); bool const is_joint_changed = joint_marker->EnvironmentSync(); is_changed = is_changed || is_joint_changed; } } return is_changed; } void ManipulatorMarker::CreateGeometry() { link_markers_.clear(); ManipulatorPtr const manipulator = manipulator_; RobotBasePtr const robot = manipulator->GetRobot(); // Get links in the manipulator chain. std::vector<LinkPtr> chain_links; LinkPtr const base_link = manipulator->GetBase(); LinkPtr const tip_link = manipulator->GetEndEffector(); bool const success = robot->GetChain( base_link->GetIndex(), tip_link->GetIndex(), chain_links); BOOST_ASSERT(success); // Get end-effector links. std::vector<LinkPtr> child_links; manipulator->GetChildLinks(child_links); // Remove duplicates in case the end-effector link is double-counted. std::set<LinkPtr> links; links.insert(chain_links.begin(), chain_links.end()); links.insert(child_links.begin(), child_links.end()); // Render each link using a LinkMarker. for (LinkPtr const &link : links) { link_markers_[link.get()] = boost::make_shared<LinkMarker>(server_, link, true); } } void ManipulatorMarker::CreateMenu() { auto const cb = boost::bind(&ManipulatorMarker::MenuCallback, this, _1); menu_set_ = menu_handler_.insert("Set DOF Values", cb); menu_reset_ = menu_handler_.insert("Restore DOF Values", cb); } void ManipulatorMarker::UpdateMenu() { for (LinkMarkerPtr const &link_marker : link_markers_ | map_values) { UpdateMenu(link_marker); } } void ManipulatorMarker::UpdateMenu(LinkMarkerPtr link_marker) { menu_handler_.apply(*server_, link_marker->interactive_marker()->name); } void ManipulatorMarker::MenuCallback(InteractiveMarkerFeedbackConstPtr const &feedback) { ManipulatorPtr const manipulator = manipulator_; RobotBasePtr const robot = manipulator->GetRobot(); std::vector<int> const &arm_indices = manipulator->GetArmIndices(); if (feedback->menu_entry_id == menu_set_) { robot->SetDOFValues(current_ik_, KinBody::CLA_CheckLimits, arm_indices); RAVELOG_DEBUG("Set manipulator '%s' to IK solution.\n", manipulator->GetName().c_str() ); } else if (feedback->menu_entry_id == menu_reset_) { robot->GetDOFValues(current_ik_, arm_indices); current_pose_ = manipulator_->GetEndEffectorTransform(); current_free_.clear(); RAVELOG_DEBUG("Snapped to current configuration of manipulator '%s'.\n", manipulator->GetName().c_str() ); } } void ManipulatorMarker::IkFeedback(InteractiveMarkerFeedbackConstPtr const &feedback) { if (feedback->event_type == InteractiveMarkerFeedback::POSE_UPDATE) { current_pose_ = toORPose<OpenRAVE::dReal>(feedback->pose); changed_pose_ = true; } } void ManipulatorMarker::InferFreeJoints(std::vector<JointPtr> *free_joints) const { static OpenRAVE::dReal const kEpsilon = 1e-3; ManipulatorPtr const manipulator = manipulator_; RobotBasePtr const robot = manipulator->GetRobot(); IkSolverBasePtr const ik_solver = manipulator->GetIkSolver(); std::vector<OpenRAVE::dReal> lower_limits, upper_limits; robot->GetDOFLimits(lower_limits, upper_limits); // We'll only accept a joint if it changes the value by at least kEpsilon. size_t const num_free = ik_solver->GetNumFreeParameters(); std::vector<OpenRAVE::dReal> best_ratio(num_free, kEpsilon); std::vector<JointPtr> &best_joints = *free_joints; best_joints.assign(num_free, JointPtr()); // Calculate the sensitivity of the free parameters to each joint. std::vector<int> const &arm_indices = manipulator->GetArmIndices(); std::vector<OpenRAVE::dReal> free_motion; for (int const dof_index : arm_indices) { RobotStateSaver const saver(robot, KinBody::Save_LinkTransformation); std::vector<OpenRAVE::dReal> dof_values; robot->GetDOFValues(dof_values); // Move the joint to its limits. std::vector<OpenRAVE::dReal> lower_free; dof_values[dof_index] = lower_limits[dof_index]; robot->SetDOFValues(dof_values); ik_solver->GetFreeParameters(lower_free); BOOST_ASSERT(lower_free.size() == num_free); std::vector<OpenRAVE::dReal> upper_free; dof_values[dof_index] = upper_limits[dof_index]; robot->SetDOFValues(dof_values); ik_solver->GetFreeParameters(upper_free); BOOST_ASSERT(upper_free.size() == num_free); // Calculate the relative change in free parameters. for (size_t ifree = 0; ifree < num_free; ++ifree) { double const delta_param = upper_free[ifree] - lower_free[ifree]; double const delta_value = upper_limits[ifree] - lower_limits[ifree]; BOOST_ASSERT(delta_value > 0); double const ratio = std::fabs(delta_param / delta_value); if (ratio > best_ratio[ifree]) { best_ratio[ifree] = ratio; best_joints[ifree] = robot->GetJointFromDOFIndex(dof_index); } } } } } <commit_msg>Hack to avoid crashing with a NULL IK solver (#3)<commit_after>#include <boost/format.hpp> #include <boost/make_shared.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/range/adaptor/map.hpp> #include "ManipulatorMarker.h" #include "or_conversions.h" using boost::format; using boost::str; using boost::adaptors::map_values; using interactive_markers::InteractiveMarkerServer; using visualization_msgs::InteractiveMarkerControl; using visualization_msgs::InteractiveMarkerFeedback; using visualization_msgs::InteractiveMarkerFeedbackConstPtr; using OpenRAVE::EnvironmentBasePtr; using OpenRAVE::RobotBasePtr; using OpenRAVE::KinBody; using OpenRAVE::IkSolverBasePtr; typedef OpenRAVE::RobotBase::RobotStateSaver RobotStateSaver; typedef boost::shared_ptr<InteractiveMarkerServer> InteractiveMarkerServerPtr; typedef OpenRAVE::RobotBase::ManipulatorPtr ManipulatorPtr; typedef OpenRAVE::KinBody::Link::GeometryPtr GeometryPtr; typedef OpenRAVE::KinBody::LinkPtr LinkPtr; typedef OpenRAVE::KinBody::LinkInfo LinkInfo; typedef OpenRAVE::KinBody::LinkInfoConstPtr LinkInfoConstPtr; typedef OpenRAVE::KinBody::JointPtr JointPtr; typedef OpenRAVE::KinBody::JointInfo JointInfo; typedef OpenRAVE::KinBody::JointInfoConstPtr JointInfoConstPtr; typedef OpenRAVE::RobotBase::ManipulatorInfo ManipulatorInfo; typedef OpenRAVE::RobotBase::ManipulatorInfoConstPtr ManipulatorInfoConstPtr; typedef OpenRAVE::RobotBase::AttachedSensorInfo AttachedSensorInfo; typedef OpenRAVE::RobotBase::AttachedSensorInfoConstPtr AttachedSensorInfoConstPtr; // TODO: Don't hardcode this. static std::string const kWorldFrameId = "/world"; static std::string const kGhostKey = "interactive_marker::ghost"; namespace or_interactivemarker { OpenRAVE::Vector const ManipulatorMarker::kValidColor(0, 1, 0, 0.4); OpenRAVE::Vector const ManipulatorMarker::kInvalidColor(1, 0, 0, 0.4); ManipulatorMarker::ManipulatorMarker(InteractiveMarkerServerPtr server, ManipulatorPtr manipulator) : server_(server) , manipulator_(manipulator) , changed_pose_(true) , has_ik_(true) , current_pose_(manipulator->GetEndEffectorTransform()) { BOOST_ASSERT(server_); BOOST_ASSERT(manipulator); // Create the ghost manipulator. CreateGeometry(); // Create a 6-DOF pose control. ik_marker_.header.frame_id = kWorldFrameId; ik_marker_.name = id(); ik_marker_.description = manipulator_->GetName(); ik_marker_.pose = toROSPose(manipulator->GetEndEffectorTransform()); ik_marker_.scale = 0.25; { InteractiveMarkerControl control; control.orientation.w = 1; control.orientation.x = 1; control.orientation.y = 0; control.orientation.z = 0; control.name = "rotate_x"; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; ik_marker_.controls.push_back(control); control.name = "move_x"; control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS; ik_marker_.controls.push_back(control); control.orientation.w = 1; control.orientation.x = 0; control.orientation.y = 1; control.orientation.z = 0; control.name = "rotate_y"; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; ik_marker_.controls.push_back(control); control.name = "move_y"; control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS; ik_marker_.controls.push_back(control); control.orientation.w = 1; control.orientation.x = 0; control.orientation.y = 0; control.orientation.z = 1; control.name = "rotate_z"; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; ik_marker_.controls.push_back(control); control.name = "move_z"; control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS; ik_marker_.controls.push_back(control); } server_->insert(ik_marker_); server_->setCallback(ik_marker_.name, boost::bind(&ManipulatorMarker::IkFeedback, this, _1)); CreateMenu(); } ManipulatorMarker::~ManipulatorMarker() { server_->erase(ik_marker_.name); } std::string ManipulatorMarker::id() const { OpenRAVE::RobotBasePtr const robot = manipulator_->GetRobot(); OpenRAVE::EnvironmentBasePtr const env = robot->GetEnv(); int const environment_id = OpenRAVE::RaveGetEnvironmentId(env); return str(format("Environment[%d].KinBody[%s].Manipulator[%s]") % environment_id % robot->GetName() % manipulator_->GetName()); } bool ManipulatorMarker::EnvironmentSync() { ManipulatorPtr const manipulator = manipulator_; RobotBasePtr const robot = manipulator->GetRobot(); IkSolverBasePtr const ik_solver = manipulator->GetIkSolver(); RobotStateSaver const saver(robot, KinBody::Save_LinkTransformation); // Hack to avoid crashing if no IK solver is set. if (!ik_solver) { return false; } // Figure out what the free joints are. size_t const num_free = ik_solver->GetNumFreeParameters(); std::vector<JointPtr> free_joints; InferFreeJoints(&free_joints); BOOST_ASSERT(free_joints.size() == num_free); std::vector<int> free_dof_indices; for (JointPtr const &free_joint : free_joints) { free_dof_indices.push_back(free_joint->GetJointIndex()); } if (ik_solver) { RobotStateSaver const free_saver(robot, KinBody::Save_LinkTransformation); // Default to the current configuration of the robot. if (current_free_.size() != num_free) { robot->GetDOFValues(current_free_, free_dof_indices); } // Extract free parameters from the joint controls. bool changed_free = false; for (size_t ifree = 0; ifree < num_free; ++ifree) { JointPtr const &joint = free_joints[ifree]; auto const it = free_joint_markers_.find(joint.get()); if (it == free_joint_markers_.end()) { continue; } // Invalidate the IK solution if we change the free joint. JointMarkerPtr &joint_marker = it->second; if (joint_marker->angle() != current_free_[ifree]) { current_free_[ifree] = joint_marker->angle(); changed_free = true; } } // Set and clamp these joint values to be within limits. robot->SetDOFValues(current_free_, KinBody::CLA_CheckLimitsSilent, free_dof_indices); robot->GetDOFValues(current_free_, free_dof_indices); // Update our IK solution. if (changed_pose_ || changed_free) { std::vector<OpenRAVE::dReal> new_ik; OpenRAVE::IkParameterization ik_param; ik_param.SetTransform6D(current_pose_); std::vector<std::vector<OpenRAVE::dReal> > ik_solutions; has_ik_ = manipulator_->FindIKSolution(ik_param, new_ik, 0); if (has_ik_) { current_ik_ = new_ik; } } } changed_pose_ = false; // Update the pose of the ghost manipulator. auto const dof_indices = manipulator->GetArmIndices(); robot->SetDOFValues(current_ik_, 1, dof_indices); bool is_changed = false; for (LinkMarkerPtr const &link_marker : link_markers_ | map_values) { bool const is_link_changed = link_marker->EnvironmentSync(); if (!is_link_changed) { OpenRAVE::Transform const link_pose = link_marker->link()->GetTransform(); link_marker->set_pose(link_pose); } else { UpdateMenu(link_marker); } // Set the color to indicate whether we have a valid IK solution. if (has_ik_) { link_marker->set_color(kValidColor); } else { link_marker->set_color(kInvalidColor); } is_changed = is_changed || is_link_changed; } if (ik_solver) { for (JointPtr const &joint : free_joints) { if (!joint) { continue; } // Lazily create the marker if it is missing. JointMarkerPtr &joint_marker = free_joint_markers_[joint.get()]; if (!joint_marker) { joint_marker = boost::make_shared<JointMarker>(server_, joint); } // Update the pose of the control to match the ghost arm. OpenRAVE::Transform const joint_pose = JointMarker::GetJointPose(joint); joint_marker->set_pose(joint_pose); bool const is_joint_changed = joint_marker->EnvironmentSync(); is_changed = is_changed || is_joint_changed; } } return is_changed; } void ManipulatorMarker::CreateGeometry() { link_markers_.clear(); ManipulatorPtr const manipulator = manipulator_; RobotBasePtr const robot = manipulator->GetRobot(); // Get links in the manipulator chain. std::vector<LinkPtr> chain_links; LinkPtr const base_link = manipulator->GetBase(); LinkPtr const tip_link = manipulator->GetEndEffector(); bool const success = robot->GetChain( base_link->GetIndex(), tip_link->GetIndex(), chain_links); BOOST_ASSERT(success); // Get end-effector links. std::vector<LinkPtr> child_links; manipulator->GetChildLinks(child_links); // Remove duplicates in case the end-effector link is double-counted. std::set<LinkPtr> links; links.insert(chain_links.begin(), chain_links.end()); links.insert(child_links.begin(), child_links.end()); // Render each link using a LinkMarker. for (LinkPtr const &link : links) { link_markers_[link.get()] = boost::make_shared<LinkMarker>(server_, link, true); } } void ManipulatorMarker::CreateMenu() { auto const cb = boost::bind(&ManipulatorMarker::MenuCallback, this, _1); menu_set_ = menu_handler_.insert("Set DOF Values", cb); menu_reset_ = menu_handler_.insert("Restore DOF Values", cb); } void ManipulatorMarker::UpdateMenu() { for (LinkMarkerPtr const &link_marker : link_markers_ | map_values) { UpdateMenu(link_marker); } } void ManipulatorMarker::UpdateMenu(LinkMarkerPtr link_marker) { menu_handler_.apply(*server_, link_marker->interactive_marker()->name); } void ManipulatorMarker::MenuCallback(InteractiveMarkerFeedbackConstPtr const &feedback) { ManipulatorPtr const manipulator = manipulator_; RobotBasePtr const robot = manipulator->GetRobot(); std::vector<int> const &arm_indices = manipulator->GetArmIndices(); if (feedback->menu_entry_id == menu_set_) { robot->SetDOFValues(current_ik_, KinBody::CLA_CheckLimits, arm_indices); RAVELOG_DEBUG("Set manipulator '%s' to IK solution.\n", manipulator->GetName().c_str() ); } else if (feedback->menu_entry_id == menu_reset_) { robot->GetDOFValues(current_ik_, arm_indices); current_pose_ = manipulator_->GetEndEffectorTransform(); current_free_.clear(); RAVELOG_DEBUG("Snapped to current configuration of manipulator '%s'.\n", manipulator->GetName().c_str() ); } } void ManipulatorMarker::IkFeedback(InteractiveMarkerFeedbackConstPtr const &feedback) { if (feedback->event_type == InteractiveMarkerFeedback::POSE_UPDATE) { current_pose_ = toORPose<OpenRAVE::dReal>(feedback->pose); changed_pose_ = true; } } void ManipulatorMarker::InferFreeJoints(std::vector<JointPtr> *free_joints) const { static OpenRAVE::dReal const kEpsilon = 1e-3; ManipulatorPtr const manipulator = manipulator_; RobotBasePtr const robot = manipulator->GetRobot(); IkSolverBasePtr const ik_solver = manipulator->GetIkSolver(); std::vector<OpenRAVE::dReal> lower_limits, upper_limits; robot->GetDOFLimits(lower_limits, upper_limits); // We'll only accept a joint if it changes the value by at least kEpsilon. size_t const num_free = ik_solver->GetNumFreeParameters(); std::vector<OpenRAVE::dReal> best_ratio(num_free, kEpsilon); std::vector<JointPtr> &best_joints = *free_joints; best_joints.assign(num_free, JointPtr()); // Calculate the sensitivity of the free parameters to each joint. std::vector<int> const &arm_indices = manipulator->GetArmIndices(); std::vector<OpenRAVE::dReal> free_motion; for (int const dof_index : arm_indices) { RobotStateSaver const saver(robot, KinBody::Save_LinkTransformation); std::vector<OpenRAVE::dReal> dof_values; robot->GetDOFValues(dof_values); // Move the joint to its limits. std::vector<OpenRAVE::dReal> lower_free; dof_values[dof_index] = lower_limits[dof_index]; robot->SetDOFValues(dof_values); ik_solver->GetFreeParameters(lower_free); BOOST_ASSERT(lower_free.size() == num_free); std::vector<OpenRAVE::dReal> upper_free; dof_values[dof_index] = upper_limits[dof_index]; robot->SetDOFValues(dof_values); ik_solver->GetFreeParameters(upper_free); BOOST_ASSERT(upper_free.size() == num_free); // Calculate the relative change in free parameters. for (size_t ifree = 0; ifree < num_free; ++ifree) { double const delta_param = upper_free[ifree] - lower_free[ifree]; double const delta_value = upper_limits[ifree] - lower_limits[ifree]; BOOST_ASSERT(delta_value > 0); double const ratio = std::fabs(delta_param / delta_value); if (ratio > best_ratio[ifree]) { best_ratio[ifree] = ratio; best_joints[ifree] = robot->GetJointFromDOFIndex(dof_index); } } } } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* * spiral_reference_line_smoother.cc */ #include "modules/planning/reference_line/spiral_reference_line_smoother.h" #include <algorithm> #include <iomanip> #include <utility> #include "IpIpoptApplication.hpp" #include "IpSolveStatistics.hpp" #include "modules/common/time/time.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/curve1d/quintic_spiral_path.h" #include "modules/planning/reference_line/spiral_problem_interface.h" namespace apollo { namespace planning { using apollo::common::time::Clock; SpiralReferenceLineSmoother::SpiralReferenceLineSmoother( const double max_point_deviation) : default_max_point_deviation_(max_point_deviation) { CHECK(max_point_deviation >= 0.0); } bool SpiralReferenceLineSmoother::Smooth( const ReferenceLine& raw_reference_line, ReferenceLine* const smoothed_reference_line) { const double start_timestamp = Clock::NowInSeconds(); std::vector<double> opt_x; std::vector<double> opt_y; std::vector<double> opt_theta; std::vector<double> opt_kappa; std::vector<double> opt_dkappa; std::vector<double> opt_s; if (anchor_points_.empty()) { const double piecewise_length = FLAGS_spiral_smoother_piecewise_length; const double length = raw_reference_line.Length(); ADEBUG << "Length = " << length; uint32_t num_of_pieces = std::max(1u, static_cast<uint32_t>(length / piecewise_length)); const double delta_s = length / num_of_pieces; double s = 0.0; std::vector<Eigen::Vector2d> raw_point2d; for (std::uint32_t i = 0; i <= num_of_pieces; ++i, s = std::fmin(s + delta_s, length)) { ReferencePoint rlp = raw_reference_line.GetReferencePoint(s); raw_point2d.emplace_back(rlp.x(), rlp.y()); } Smooth(raw_point2d, &opt_theta, &opt_kappa, &opt_dkappa, &opt_s, &opt_x, &opt_y); } else { std::size_t start_index = 0; for (const auto& anchor_point : anchor_points_) { if (anchor_point.enforced) { start_index++; } else { break; } } std::vector<Eigen::Vector2d> raw_point2d; if (start_index == 0) { for (const auto& anchor_point : anchor_points_) { raw_point2d.emplace_back(anchor_point.path_point.x(), anchor_point.path_point.y()); } } else { std::vector<double> overhead_s; for (std::size_t i = 0; i + 1 < start_index; ++i) { const auto& p0 = anchor_points_[i]; const auto& p1 = anchor_points_[i + 1]; overhead_s.push_back(p1.path_point.s() - p0.path_point.s()); } std::vector<double> overhead_theta; std::vector<double> overhead_kappa; std::vector<double> overhead_dkappa; std::vector<double> overhead_x; std::vector<double> overhead_y; for (std::size_t i = 0; i < anchor_points_.size(); ++i) { const auto& p = anchor_points_[i]; if (i + 1 < start_index) { overhead_theta.push_back(p.path_point.theta()); overhead_kappa.push_back(p.path_point.kappa()); overhead_dkappa.push_back(p.path_point.dkappa()); overhead_x.push_back(p.path_point.x()); overhead_y.push_back(p.path_point.y()); } else { raw_point2d.emplace_back(p.path_point.x(), p.path_point.y()); } } fixed_start_point_ = true; fixed_start_x_ = anchor_points_[start_index - 1].path_point.x(); fixed_start_y_ = anchor_points_[start_index - 1].path_point.y(); fixed_start_theta_ = common::math::NormalizeAngle( anchor_points_[start_index - 1].path_point.theta()); fixed_start_kappa_ = anchor_points_[start_index - 1].path_point.kappa(); fixed_start_dkappa_ = anchor_points_[start_index - 1].path_point.dkappa(); Smooth(raw_point2d, &opt_theta, &opt_kappa, &opt_dkappa, &opt_s, &opt_x, &opt_y); opt_theta.insert(opt_theta.begin(), overhead_theta.begin(), overhead_theta.end()); opt_kappa.insert(opt_kappa.begin(), overhead_kappa.begin(), overhead_kappa.end()); opt_dkappa.insert(opt_dkappa.begin(), overhead_dkappa.begin(), overhead_dkappa.end()); opt_s.insert(opt_s.begin(), overhead_s.begin(), overhead_s.end()); opt_x.insert(opt_x.begin(), overhead_x.begin(), overhead_x.end()); opt_y.insert(opt_y.begin(), overhead_y.begin(), overhead_y.end()); std::for_each(opt_x.begin(), opt_x.end(), [this](double& x){ x += zero_x_; }); std::for_each(opt_y.begin(), opt_y.end(), [this](double& y){ y += zero_y_; }); } } std::vector<common::PathPoint> smoothed_point2d = Interpolate(opt_theta, opt_kappa, opt_dkappa, opt_s, opt_x, opt_y, FLAGS_spiral_reference_line_resolution); std::vector<ReferencePoint> ref_points; for (const auto& p : smoothed_point2d) { const double heading = p.theta(); const double kappa = p.kappa(); const double dkappa = p.dkappa(); common::SLPoint ref_sl_point; if (!raw_reference_line.XYToSL({p.x(), p.y()}, &ref_sl_point)) { return false; } if (ref_sl_point.s() < 0 || ref_sl_point.s() > raw_reference_line.Length()) { continue; } ReferencePoint rlp = raw_reference_line.GetReferencePoint(ref_sl_point.s()); ref_points.emplace_back( ReferencePoint(hdmap::MapPathPoint(common::math::Vec2d(p.x(), p.y()), heading, rlp.lane_waypoints()), kappa, dkappa, 0.0, 0.0)); } ReferencePoint::RemoveDuplicates(&ref_points); if (ref_points.size() < 2) { AERROR << "Fail to generate smoothed reference line."; return false; } *smoothed_reference_line = ReferenceLine(ref_points); const double end_timestamp = Clock::NowInSeconds(); ADEBUG << "Spiral reference line smoother time: " << (end_timestamp - start_timestamp) * 1000 << " ms."; return true; } bool SpiralReferenceLineSmoother::Smooth(std::vector<Eigen::Vector2d> point2d, std::vector<double>* ptr_theta, std::vector<double>* ptr_kappa, std::vector<double>* ptr_dkappa, std::vector<double>* ptr_s, std::vector<double>* ptr_x, std::vector<double>* ptr_y) const { CHECK_GT(point2d.size(), 1); SpiralProblemInterface* ptop = new SpiralProblemInterface(point2d); ptop->set_default_max_point_deviation(default_max_point_deviation_); if (fixed_start_point_) { ptop->set_start_point(fixed_start_x_, fixed_start_y_, fixed_start_theta_, fixed_start_kappa_, fixed_start_dkappa_); } Ipopt::SmartPtr<Ipopt::TNLP> problem = ptop; // Create an instance of the IpoptApplication Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetStringValue("hessian_approximation", "limited-memory"); // app->Options()->SetStringValue("derivative_test", "first-order"); // app->Options()->SetNumericValue("derivative_test_perturbation", 1.0e-7); // app->Options()->SetStringValue("derivative_test", "second-order"); app->Options()->SetIntegerValue("print_level", 0); int num_iterations = FLAGS_spiral_smoother_num_iteration; app->Options()->SetIntegerValue("max_iter", num_iterations); app->Options()->SetIntegerValue("acceptable_iter", 5); app->Options()->SetNumericValue("tol", 1.0e-3); app->Options()->SetNumericValue("acceptable_tol", 1.0e-3); Ipopt::ApplicationReturnStatus status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { ADEBUG << "*** Error during initialization!"; return static_cast<int>(status); } status = app->OptimizeTNLP(problem); if (status == Ipopt::Solve_Succeeded || status == Ipopt::Solved_To_Acceptable_Level) { // Retrieve some statistics about the solve Ipopt::Index iter_count = app->Statistics()->IterationCount(); ADEBUG << "*** The problem solved in " << iter_count << " iterations!"; Ipopt::Number final_obj = app->Statistics()->FinalObjective(); ADEBUG << "*** The final value of the objective function is " << final_obj << '.'; } else { ADEBUG << "Return status: " << int(status); } ptop->get_optimization_results(ptr_theta, ptr_kappa, ptr_dkappa, ptr_s, ptr_x, ptr_y); return status == Ipopt::Solve_Succeeded || status == Ipopt::Solved_To_Acceptable_Level; } std::vector<common::PathPoint> SpiralReferenceLineSmoother::Interpolate( const std::vector<double>& theta, const std::vector<double>& kappa, const std::vector<double>& dkappa, const std::vector<double>& s, const std::vector<double>& x, const std::vector<double>& y, const double resolution) const { std::vector<common::PathPoint> smoothed_point2d; double start_s = 0.0; common::PathPoint first_point = to_path_point(x.front(), y.front(), start_s, theta.front(), kappa.front(), dkappa.front()); smoothed_point2d.push_back(first_point); for (std::size_t i = 0; i + 1 < theta.size(); ++i) { double start_x = x[i]; double start_y = y[i]; auto path_point_seg = Interpolate( start_x, start_y, start_s, theta[i], kappa[i], dkappa[i], theta[i + 1], kappa[i + 1], dkappa[i + 1], s[i], resolution); smoothed_point2d.insert(smoothed_point2d.end(), path_point_seg.begin(), path_point_seg.end()); start_s = smoothed_point2d.back().s(); } return smoothed_point2d; } std::vector<common::PathPoint> SpiralReferenceLineSmoother::Interpolate( const double start_x, const double start_y, const double start_s, const double theta0, const double kappa0, const double dkappa0, const double theta1, const double kappa1, const double dkappa1, const double delta_s, const double resolution) const { std::vector<common::PathPoint> path_points; QuinticSpiralPath spiral_curve(theta0, kappa0, dkappa0, theta1, kappa1, dkappa1, delta_s); std::size_t num_of_points = std::ceil(delta_s / resolution) + 1; for (std::size_t i = 1; i <= num_of_points; ++i) { const double inter_s = delta_s / num_of_points * i; const double dx = spiral_curve.ComputeCartesianDeviationX<10>(inter_s); const double dy = spiral_curve.ComputeCartesianDeviationY<10>(inter_s); const double theta = common::math::NormalizeAngle(spiral_curve.Evaluate(0, inter_s)); const double kappa = spiral_curve.Evaluate(1, inter_s); const double dkappa = spiral_curve.Evaluate(2, inter_s); auto path_point = to_path_point(start_x + dx, start_y + dy, start_s + inter_s, theta, kappa, dkappa); path_points.push_back(std::move(path_point)); } return path_points; } common::PathPoint SpiralReferenceLineSmoother::to_path_point( const double x, const double y, const double s, const double theta, const double kappa, const double dkappa) const { common::PathPoint point; point.set_x(x); point.set_y(y); point.set_s(s); point.set_theta(theta); point.set_kappa(kappa); point.set_dkappa(dkappa); return point; } void SpiralReferenceLineSmoother::SetAnchorPoints( const std::vector<AnchorPoint>& anchor_points) { anchor_points_ = std::move(anchor_points); CHECK_GT(anchor_points_.size(), 1); zero_x_ = anchor_points_.front().path_point.x(); zero_y_ = anchor_points_.front().path_point.y(); std::for_each(anchor_points_.begin(), anchor_points_.end(), [this](AnchorPoint& p) { auto curr_x = p.path_point.x(); auto curr_y = p.path_point.y(); p.path_point.set_x(curr_x - zero_x_); p.path_point.set_y(curr_y - zero_y_);}); } } // namespace planning } // namespace apollo <commit_msg>planning: further tuned parameters for spiral reference line smoother<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* * spiral_reference_line_smoother.cc */ #include "modules/planning/reference_line/spiral_reference_line_smoother.h" #include <algorithm> #include <iomanip> #include <utility> #include "IpIpoptApplication.hpp" #include "IpSolveStatistics.hpp" #include "modules/common/time/time.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/curve1d/quintic_spiral_path.h" #include "modules/planning/reference_line/spiral_problem_interface.h" namespace apollo { namespace planning { using apollo::common::time::Clock; SpiralReferenceLineSmoother::SpiralReferenceLineSmoother( const double max_point_deviation) : default_max_point_deviation_(max_point_deviation) { CHECK(max_point_deviation >= 0.0); } bool SpiralReferenceLineSmoother::Smooth( const ReferenceLine& raw_reference_line, ReferenceLine* const smoothed_reference_line) { const double start_timestamp = Clock::NowInSeconds(); std::vector<double> opt_x; std::vector<double> opt_y; std::vector<double> opt_theta; std::vector<double> opt_kappa; std::vector<double> opt_dkappa; std::vector<double> opt_s; if (anchor_points_.empty()) { const double piecewise_length = FLAGS_spiral_smoother_piecewise_length; const double length = raw_reference_line.Length(); ADEBUG << "Length = " << length; uint32_t num_of_pieces = std::max(1u, static_cast<uint32_t>(length / piecewise_length)); const double delta_s = length / num_of_pieces; double s = 0.0; std::vector<Eigen::Vector2d> raw_point2d; for (std::uint32_t i = 0; i <= num_of_pieces; ++i, s = std::fmin(s + delta_s, length)) { ReferencePoint rlp = raw_reference_line.GetReferencePoint(s); raw_point2d.emplace_back(rlp.x(), rlp.y()); } Smooth(raw_point2d, &opt_theta, &opt_kappa, &opt_dkappa, &opt_s, &opt_x, &opt_y); } else { std::size_t start_index = 0; for (const auto& anchor_point : anchor_points_) { if (anchor_point.enforced) { start_index++; } else { break; } } std::vector<Eigen::Vector2d> raw_point2d; if (start_index == 0) { for (const auto& anchor_point : anchor_points_) { raw_point2d.emplace_back(anchor_point.path_point.x(), anchor_point.path_point.y()); } } else { std::vector<double> overhead_s; for (std::size_t i = 0; i + 1 < start_index; ++i) { const auto& p0 = anchor_points_[i]; const auto& p1 = anchor_points_[i + 1]; overhead_s.push_back(p1.path_point.s() - p0.path_point.s()); } std::vector<double> overhead_theta; std::vector<double> overhead_kappa; std::vector<double> overhead_dkappa; std::vector<double> overhead_x; std::vector<double> overhead_y; for (std::size_t i = 0; i < anchor_points_.size(); ++i) { const auto& p = anchor_points_[i]; if (i + 1 < start_index) { overhead_theta.push_back(p.path_point.theta()); overhead_kappa.push_back(p.path_point.kappa()); overhead_dkappa.push_back(p.path_point.dkappa()); overhead_x.push_back(p.path_point.x()); overhead_y.push_back(p.path_point.y()); } else { raw_point2d.emplace_back(p.path_point.x(), p.path_point.y()); } } fixed_start_point_ = true; fixed_start_x_ = anchor_points_[start_index - 1].path_point.x(); fixed_start_y_ = anchor_points_[start_index - 1].path_point.y(); fixed_start_theta_ = common::math::NormalizeAngle( anchor_points_[start_index - 1].path_point.theta()); fixed_start_kappa_ = anchor_points_[start_index - 1].path_point.kappa(); fixed_start_dkappa_ = anchor_points_[start_index - 1].path_point.dkappa(); Smooth(raw_point2d, &opt_theta, &opt_kappa, &opt_dkappa, &opt_s, &opt_x, &opt_y); opt_theta.insert(opt_theta.begin(), overhead_theta.begin(), overhead_theta.end()); opt_kappa.insert(opt_kappa.begin(), overhead_kappa.begin(), overhead_kappa.end()); opt_dkappa.insert(opt_dkappa.begin(), overhead_dkappa.begin(), overhead_dkappa.end()); opt_s.insert(opt_s.begin(), overhead_s.begin(), overhead_s.end()); opt_x.insert(opt_x.begin(), overhead_x.begin(), overhead_x.end()); opt_y.insert(opt_y.begin(), overhead_y.begin(), overhead_y.end()); std::for_each(opt_x.begin(), opt_x.end(), [this](double& x){ x += zero_x_; }); std::for_each(opt_y.begin(), opt_y.end(), [this](double& y){ y += zero_y_; }); } } std::vector<common::PathPoint> smoothed_point2d = Interpolate(opt_theta, opt_kappa, opt_dkappa, opt_s, opt_x, opt_y, FLAGS_spiral_reference_line_resolution); std::vector<ReferencePoint> ref_points; for (const auto& p : smoothed_point2d) { const double heading = p.theta(); const double kappa = p.kappa(); const double dkappa = p.dkappa(); common::SLPoint ref_sl_point; if (!raw_reference_line.XYToSL({p.x(), p.y()}, &ref_sl_point)) { return false; } if (ref_sl_point.s() < 0 || ref_sl_point.s() > raw_reference_line.Length()) { continue; } ReferencePoint rlp = raw_reference_line.GetReferencePoint(ref_sl_point.s()); ref_points.emplace_back( ReferencePoint(hdmap::MapPathPoint(common::math::Vec2d(p.x(), p.y()), heading, rlp.lane_waypoints()), kappa, dkappa, 0.0, 0.0)); } ReferencePoint::RemoveDuplicates(&ref_points); if (ref_points.size() < 2) { AERROR << "Fail to generate smoothed reference line."; return false; } *smoothed_reference_line = ReferenceLine(ref_points); const double end_timestamp = Clock::NowInSeconds(); ADEBUG << "Spiral reference line smoother time: " << (end_timestamp - start_timestamp) * 1000 << " ms."; return true; } bool SpiralReferenceLineSmoother::Smooth(std::vector<Eigen::Vector2d> point2d, std::vector<double>* ptr_theta, std::vector<double>* ptr_kappa, std::vector<double>* ptr_dkappa, std::vector<double>* ptr_s, std::vector<double>* ptr_x, std::vector<double>* ptr_y) const { CHECK_GT(point2d.size(), 1); SpiralProblemInterface* ptop = new SpiralProblemInterface(point2d); ptop->set_default_max_point_deviation(default_max_point_deviation_); if (fixed_start_point_) { ptop->set_start_point(fixed_start_x_, fixed_start_y_, fixed_start_theta_, fixed_start_kappa_, fixed_start_dkappa_); } Ipopt::SmartPtr<Ipopt::TNLP> problem = ptop; // Create an instance of the IpoptApplication Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetStringValue("hessian_approximation", "limited-memory"); // app->Options()->SetStringValue("derivative_test", "first-order"); // app->Options()->SetNumericValue("derivative_test_perturbation", 1.0e-7); // app->Options()->SetStringValue("derivative_test", "second-order"); app->Options()->SetIntegerValue("print_level", 0); int num_iterations = FLAGS_spiral_smoother_num_iteration; app->Options()->SetIntegerValue("max_iter", num_iterations); app->Options()->SetIntegerValue("acceptable_iter", 5); app->Options()->SetNumericValue("tol", 1.0e-4); app->Options()->SetNumericValue("acceptable_tol", 1.0e-5); Ipopt::ApplicationReturnStatus status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { ADEBUG << "*** Error during initialization!"; return static_cast<int>(status); } status = app->OptimizeTNLP(problem); if (status == Ipopt::Solve_Succeeded || status == Ipopt::Solved_To_Acceptable_Level) { // Retrieve some statistics about the solve Ipopt::Index iter_count = app->Statistics()->IterationCount(); ADEBUG << "*** The problem solved in " << iter_count << " iterations!"; Ipopt::Number final_obj = app->Statistics()->FinalObjective(); ADEBUG << "*** The final value of the objective function is " << final_obj << '.'; } else { ADEBUG << "Return status: " << int(status); } ptop->get_optimization_results(ptr_theta, ptr_kappa, ptr_dkappa, ptr_s, ptr_x, ptr_y); return status == Ipopt::Solve_Succeeded || status == Ipopt::Solved_To_Acceptable_Level; } std::vector<common::PathPoint> SpiralReferenceLineSmoother::Interpolate( const std::vector<double>& theta, const std::vector<double>& kappa, const std::vector<double>& dkappa, const std::vector<double>& s, const std::vector<double>& x, const std::vector<double>& y, const double resolution) const { std::vector<common::PathPoint> smoothed_point2d; double start_s = 0.0; common::PathPoint first_point = to_path_point(x.front(), y.front(), start_s, theta.front(), kappa.front(), dkappa.front()); smoothed_point2d.push_back(first_point); for (std::size_t i = 0; i + 1 < theta.size(); ++i) { double start_x = x[i]; double start_y = y[i]; auto path_point_seg = Interpolate( start_x, start_y, start_s, theta[i], kappa[i], dkappa[i], theta[i + 1], kappa[i + 1], dkappa[i + 1], s[i], resolution); smoothed_point2d.insert(smoothed_point2d.end(), path_point_seg.begin(), path_point_seg.end()); start_s = smoothed_point2d.back().s(); } return smoothed_point2d; } std::vector<common::PathPoint> SpiralReferenceLineSmoother::Interpolate( const double start_x, const double start_y, const double start_s, const double theta0, const double kappa0, const double dkappa0, const double theta1, const double kappa1, const double dkappa1, const double delta_s, const double resolution) const { std::vector<common::PathPoint> path_points; QuinticSpiralPath spiral_curve(theta0, kappa0, dkappa0, theta1, kappa1, dkappa1, delta_s); std::size_t num_of_points = std::ceil(delta_s / resolution) + 1; for (std::size_t i = 1; i <= num_of_points; ++i) { const double inter_s = delta_s / num_of_points * i; const double dx = spiral_curve.ComputeCartesianDeviationX<10>(inter_s); const double dy = spiral_curve.ComputeCartesianDeviationY<10>(inter_s); const double theta = common::math::NormalizeAngle(spiral_curve.Evaluate(0, inter_s)); const double kappa = spiral_curve.Evaluate(1, inter_s); const double dkappa = spiral_curve.Evaluate(2, inter_s); auto path_point = to_path_point(start_x + dx, start_y + dy, start_s + inter_s, theta, kappa, dkappa); path_points.push_back(std::move(path_point)); } return path_points; } common::PathPoint SpiralReferenceLineSmoother::to_path_point( const double x, const double y, const double s, const double theta, const double kappa, const double dkappa) const { common::PathPoint point; point.set_x(x); point.set_y(y); point.set_s(s); point.set_theta(theta); point.set_kappa(kappa); point.set_dkappa(dkappa); return point; } void SpiralReferenceLineSmoother::SetAnchorPoints( const std::vector<AnchorPoint>& anchor_points) { anchor_points_ = std::move(anchor_points); CHECK_GT(anchor_points_.size(), 1); zero_x_ = anchor_points_.front().path_point.x(); zero_y_ = anchor_points_.front().path_point.y(); std::for_each(anchor_points_.begin(), anchor_points_.end(), [this](AnchorPoint& p) { auto curr_x = p.path_point.x(); auto curr_y = p.path_point.y(); p.path_point.set_x(curr_x - zero_x_); p.path_point.set_y(curr_y - zero_y_);}); } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>// // Exponent.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Exponential.h" Exponential::Exponential(Expression* base, Rational* exponent){ this->type = "exponential"; this->base = base; this->exponent = exponent; this->exde = new Integer(exponent->getDenominator()); if (exde->getValue() != 1) { //if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1 Integer* baseAsInteger = (Integer *) base; base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1); Integer* one = new Integer(1); exponent->setDenominator(one); } this->exnu = new Integer(exponent->getNumerator()); if (canExponentiate()) { exponentiate(); } } Exponential::~Exponential(){ } bool Exponential::canExponentiate() { if(base->type == "euler"){ return false; }else if(base->type == "exponential"){ Exponential* ex = (Exponential *) base; this->exponent->multiply(ex->getExponent()); Integer* numSum = new Integer (1); ex->getExponent()->setNumerator(numSum); return false; // false is returned because the base itself would have already been exponentiated if it were possible }else if(base->type == "integer"){ return true; }else if(base->type == "logarithm"){ return false; }else if(base->type == "nthRoot"){ nthRoot* nr = (nthRoot *) base; Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator()); //makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one this->exponent = r; nr->setRoot(1); return false; }else if(base->type == "pi"){ return false; }else if(base->type == "rational"){ Rational* r = (Rational *) base; if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") { Exponential* nu = new Exponential(r->geteNumerator(), this->exponent); r->setNumerator(nu); Exponential* de = new Exponential(r->geteDenominator(), this->exponent); r->setDenominator(de); } }else{ cout << "type not recognized" << endl; } return false; } void Exponential::exponentiate(){ Integer* one = new Integer(1); Rational* oneRat = new Rational(1, 1); if (this->base->type == "rational") { Rational* ratBase = (Rational *) this->base; Exponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent)); //no matching constructor for exponential Exponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent)); //same error Rational* newRatBase = new Rational(numAsExponential, denAsExponential); this->base = newRatBase; this->exponent = oneRat; } else { if (this->exponent->getNumerator()==0) { this->exponent=oneRat; this->base=one; } bool toFlip = false; if (exnu->getValue()<0) { exnu->setValue(exnu->getValue()*-1); toFlip = true; //handles negative exponents } Expression* constantBase = 0; if (base->type == "integer") { //fixed the problem for integers but nothing else Integer *a = (Integer *)base; constantBase = new Integer(a->getValue()); } while (exponent->getNumerator()>1) { base->multiply(constantBase); exponent->setNumerator(exponent->geteNumerator()->subtract(one)); } if (toFlip) { Integer* one = new Integer(1); Rational* mouse = new Rational(one, base); base = mouse; } } } Expression* Exponential::add(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if ((ex->getBase()->type == this->base->type) && ((this->base->type == "euler") || (this->base->type == "pi"))) { if (ex->getExponent()==this->exponent) { Integer* two = new Integer(2); this->multiply(two); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::subtract(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if ((ex->getBase()->type == this->base->type) && ((this->base->type == "euler") || (this->base->type == "pi"))) { if (ex->getExponent()==this->exponent) { Integer* zero = new Integer(0); this->multiply(zero); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::multiply(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; //if (this->base == ex->getBase()) { // this->exponent->add(ex->getExponent()); //} if (ex->base->type == this->base->type) { if ((ex->base->type == "euler") || (ex->base->type == "pi")) { this->exponent->add(ex->exponent); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* numToSet = r->geteNumerator(); numToSet->multiply(this); r->setNumerator(numToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::divide(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; //if (this->base == ex->getBase()) { // this->exponent->subtract(ex->getExponent()); //} if (ex->base->type == this->base->type) { if ((ex->base->type == "euler") || (ex->base->type == "pi")) { this->exponent->subtract(ex->exponent); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* denToSet = r->geteDenominator(); denToSet->multiply(this); r->setDenominator(denToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Rational* Exponential::getExponent() { return exponent; } Expression* Exponential::getBase() { return base; } Integer* Exponential::getExnu() { return exnu; } Integer* Exponential::getExde() { return exde; } void Exponential::setExnu(Integer* n) { exnu = n; } void Exponential::setExde(Integer* n) { exde = n; } void Exponential::setExponent(Rational* e) { exponent = e; } void Exponential::setBase(Expression* e) { base = e; } string Exponential::toString() { stringstream str; if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){ str << *base; } else if(exponent->getDenominator() == 1){ str << *base << "^" << *exponent->geteNumerator(); }else{ str << *base << "^" << *exponent; } return str.str(); } ostream& Exponential::print(std::ostream& output) const{ Exponential *a = (Exponential *)this; output << a->toString(); return output; } bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression) if (this->type == b->type && this->type != "logarithm") { if (this->type == "nthRoot") { } return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canSubtract(Expression* b){ if (this->type == b->type) { return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canMultiply(Expression* b){ if (this->type == b->type) { return true; } else if (this->base->type == b->type) { return true; } else if(this->type == "integer" && b->type == "rational") return true; else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canDivide(Expression* b){ if (this->type == b->type) { return true; } else if (this->base->type == b->type) { return true; } else if(this->type == "integer"){ if( b->type == "rational") return true; } else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } <commit_msg>Fixed zero power case<commit_after>// // Exponent.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Exponential.h" Exponential::Exponential(Expression* base, Rational* exponent){ this->type = "exponential"; this->base = base; this->exponent = exponent; this->exde = new Integer(exponent->getDenominator()); if (exde->getValue() != 1) { //if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1 Integer* baseAsInteger = (Integer *) base; base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1); Integer* one = new Integer(1); exponent->setDenominator(one); } this->exnu = new Integer(exponent->getNumerator()); if (canExponentiate()) { exponentiate(); } } Exponential::~Exponential(){ } bool Exponential::canExponentiate() { this->exponent->getNumerator() if (this->exNu == 0) { return true; } if(base->type == "euler"){ return false; }else if(base->type == "exponential"){ Exponential* ex = (Exponential *) base; this->exponent->multiply(ex->getExponent()); Integer* numSum = new Integer (1); ex->getExponent()->setNumerator(numSum); return false; // false is returned because the base itself would have already been exponentiated if it were possible }else if(base->type == "integer"){ return true; }else if(base->type == "logarithm"){ return false; }else if(base->type == "nthRoot"){ nthRoot* nr = (nthRoot *) base; Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator()); //makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one this->exponent = r; nr->setRoot(1); return false; }else if(base->type == "pi"){ return false; }else if(base->type == "rational"){ Rational* r = (Rational *) base; if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") { Exponential* nu = new Exponential(r->geteNumerator(), this->exponent); r->setNumerator(nu); Exponential* de = new Exponential(r->geteDenominator(), this->exponent); r->setDenominator(de); } }else{ cout << "type not recognized" << endl; } return false; } void Exponential::exponentiate(){ Integer* one = new Integer(1); if (this->exNu == 0) { return one; } Rational* oneRat = new Rational(1, 1); if (this->base->type == "rational") { Rational* ratBase = (Rational *) this->base; Exponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent)); //no matching constructor for exponential Exponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent)); //same error Rational* newRatBase = new Rational(numAsExponential, denAsExponential); this->base = newRatBase; this->exponent = oneRat; } else { if (this->exponent->getNumerator()==0) { this->exponent=oneRat; this->base=one; } bool toFlip = false; if (exnu->getValue()<0) { exnu->setValue(exnu->getValue()*-1); toFlip = true; //handles negative exponents } Expression* constantBase = 0; if (base->type == "integer") { //fixed the problem for integers but nothing else Integer *a = (Integer *)base; constantBase = new Integer(a->getValue()); } while (exponent->getNumerator()>1) { base->multiply(constantBase); exponent->setNumerator(exponent->geteNumerator()->subtract(one)); } if (toFlip) { Integer* one = new Integer(1); Rational* mouse = new Rational(one, base); base = mouse; } } } Expression* Exponential::add(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if ((ex->getBase()->type == this->base->type) && ((this->base->type == "euler") || (this->base->type == "pi"))) { if (ex->getExponent()==this->exponent) { Integer* two = new Integer(2); this->multiply(two); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::subtract(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if ((ex->getBase()->type == this->base->type) && ((this->base->type == "euler") || (this->base->type == "pi"))) { if (ex->getExponent()==this->exponent) { Integer* zero = new Integer(0); this->multiply(zero); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::multiply(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; //if (this->base == ex->getBase()) { // this->exponent->add(ex->getExponent()); //} if (ex->base->type == this->base->type) { if ((ex->base->type == "euler") || (ex->base->type == "pi")) { this->exponent->add(ex->exponent); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* numToSet = r->geteNumerator(); numToSet->multiply(this); r->setNumerator(numToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::divide(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; //if (this->base == ex->getBase()) { // this->exponent->subtract(ex->getExponent()); //} if (ex->base->type == this->base->type) { if ((ex->base->type == "euler") || (ex->base->type == "pi")) { this->exponent->subtract(ex->exponent); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* denToSet = r->geteDenominator(); denToSet->multiply(this); r->setDenominator(denToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Rational* Exponential::getExponent() { return exponent; } Expression* Exponential::getBase() { return base; } Integer* Exponential::getExnu() { return exnu; } Integer* Exponential::getExde() { return exde; } void Exponential::setExnu(Integer* n) { exnu = n; } void Exponential::setExde(Integer* n) { exde = n; } void Exponential::setExponent(Rational* e) { exponent = e; } void Exponential::setBase(Expression* e) { base = e; } string Exponential::toString() { stringstream str; if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){ str << *base; } else if(exponent->getDenominator() == 1){ str << *base << "^" << *exponent->geteNumerator(); }else{ str << *base << "^" << *exponent; } return str.str(); } ostream& Exponential::print(std::ostream& output) const{ Exponential *a = (Exponential *)this; output << a->toString(); return output; } bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression) if (this->type == b->type && this->type != "logarithm") { if (this->type == "nthRoot") { } return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canSubtract(Expression* b){ if (this->type == b->type) { return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canMultiply(Expression* b){ if (this->type == b->type) { return true; } else if (this->base->type == b->type) { return true; } else if(this->type == "integer" && b->type == "rational") return true; else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canDivide(Expression* b){ if (this->type == b->type) { return true; } else if (this->base->type == b->type) { return true; } else if(this->type == "integer"){ if( b->type == "rational") return true; } else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <algorithm> // template<BidirectionalIterator Iter, StrictWeakOrder<auto, Iter::value_type> Compare> // requires ShuffleIterator<Iter> // && CopyConstructible<Compare> // void // inplace_merge(Iter first, Iter middle, Iter last, Compare comp); #include <algorithm> #include <functional> #include <random> #include <cassert> #include "test_macros.h" #if TEST_STD_VER >= 11 #include <memory> struct indirect_less { template <class P> bool operator()(const P& x, const P& y) {return *x < *y;} }; struct S { S() : i_(0) {} S(int i) : i_(i) {} S(const S& rhs) : i_(rhs.i_) {} S( S&& rhs) : i_(rhs.i_) { rhs.i_ = -1; } S& operator =(const S& rhs) { i_ = rhs.i_; return *this; } S& operator =( S&& rhs) { i_ = rhs.i_; rhs.i_ = -2; assert(this != &rhs); return *this; } S& operator =(int i) { i_ = i; return *this; } bool operator <(const S& rhs) const { return i_ < rhs.i_; } bool operator >(const S& rhs) const { return i_ > rhs.i_; } bool operator ==(const S& rhs) const { return i_ == rhs.i_; } bool operator ==(int i) const { return i_ == i; } void set(int i) { i_ = i; } int i_; }; #endif // TEST_STD_VER >= 11 #include "test_iterators.h" #include "counting_predicates.hpp" std::mt19937 randomness; template <class Iter> void test_one(unsigned N, unsigned M) { assert(M <= N); typedef typename std::iterator_traits<Iter>::value_type value_type; value_type* ia = new value_type[N]; for (unsigned i = 0; i < N; ++i) ia[i] = i; std::shuffle(ia, ia+N, randomness); std::sort(ia, ia+M, std::greater<value_type>()); std::sort(ia+M, ia+N, std::greater<value_type>()); binary_counting_predicate<std::greater<value_type>, value_type, value_type> pred((std::greater<value_type>())); std::inplace_merge(Iter(ia), Iter(ia+M), Iter(ia+N), std::ref(pred)); if(N > 0) { assert(ia[0] == static_cast<int>(N)-1); assert(ia[N-1] == 0); assert(std::is_sorted(ia, ia+N, std::greater<value_type>())); assert(pred.count() <= (N-1)); } delete [] ia; } template <class Iter> void test(unsigned N) { test_one<Iter>(N, 0); test_one<Iter>(N, N/4); test_one<Iter>(N, N/2); test_one<Iter>(N, 3*N/4); test_one<Iter>(N, N); } template <class Iter> void test() { test_one<Iter>(0, 0); test_one<Iter>(1, 0); test_one<Iter>(1, 1); test_one<Iter>(2, 0); test_one<Iter>(2, 1); test_one<Iter>(2, 2); test_one<Iter>(3, 0); test_one<Iter>(3, 1); test_one<Iter>(3, 2); test_one<Iter>(3, 3); test<Iter>(4); test<Iter>(20); test<Iter>(100); test<Iter>(1000); } struct less_by_first { template <typename Pair> bool operator()(const Pair& lhs, const Pair& rhs) { return std::less<typename Pair::first_type>()(lhs.first, rhs.first); } }; void test_PR31166 () { typedef std::pair<int, int> P; typedef std::vector<P> V; const V vec {{1, 0}, {2, 0}, {2, 1}, {2, 2}, {2, 3}}; for ( int i = 0; i < 5; ++i ) { V res = vec; std::inplace_merge(res.begin(), res.begin() + i, res.end(), less_by_first()); assert(res == vec); } } int main() { test<bidirectional_iterator<int*> >(); test<random_access_iterator<int*> >(); test<int*>(); #if TEST_STD_VER >= 11 test<bidirectional_iterator<S*> >(); test<random_access_iterator<S*> >(); test<S*>(); { int N = 100; unsigned M = 50; std::unique_ptr<int>* ia = new std::unique_ptr<int>[N]; for (int i = 0; i < N; ++i) ia[i].reset(new int(i)); std::shuffle(ia, ia+N, randomness); std::sort(ia, ia+M, indirect_less()); std::sort(ia+M, ia+N, indirect_less()); std::inplace_merge(ia, ia+M, ia+N, indirect_less()); if(N > 0) { assert(*ia[0] == 0); assert(*ia[N-1] == N-1); assert(std::is_sorted(ia, ia+N, indirect_less())); } delete [] ia; } #endif // TEST_STD_VER >= 11 test_PR31166(); } <commit_msg>Fix test for C++03<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <algorithm> // template<BidirectionalIterator Iter, StrictWeakOrder<auto, Iter::value_type> Compare> // requires ShuffleIterator<Iter> // && CopyConstructible<Compare> // void // inplace_merge(Iter first, Iter middle, Iter last, Compare comp); #include <algorithm> #include <functional> #include <random> #include <cassert> #include "test_macros.h" #if TEST_STD_VER >= 11 #include <memory> struct indirect_less { template <class P> bool operator()(const P& x, const P& y) {return *x < *y;} }; struct S { S() : i_(0) {} S(int i) : i_(i) {} S(const S& rhs) : i_(rhs.i_) {} S( S&& rhs) : i_(rhs.i_) { rhs.i_ = -1; } S& operator =(const S& rhs) { i_ = rhs.i_; return *this; } S& operator =( S&& rhs) { i_ = rhs.i_; rhs.i_ = -2; assert(this != &rhs); return *this; } S& operator =(int i) { i_ = i; return *this; } bool operator <(const S& rhs) const { return i_ < rhs.i_; } bool operator >(const S& rhs) const { return i_ > rhs.i_; } bool operator ==(const S& rhs) const { return i_ == rhs.i_; } bool operator ==(int i) const { return i_ == i; } void set(int i) { i_ = i; } int i_; }; #endif // TEST_STD_VER >= 11 #include "test_iterators.h" #include "counting_predicates.hpp" std::mt19937 randomness; template <class Iter> void test_one(unsigned N, unsigned M) { assert(M <= N); typedef typename std::iterator_traits<Iter>::value_type value_type; value_type* ia = new value_type[N]; for (unsigned i = 0; i < N; ++i) ia[i] = i; std::shuffle(ia, ia+N, randomness); std::sort(ia, ia+M, std::greater<value_type>()); std::sort(ia+M, ia+N, std::greater<value_type>()); binary_counting_predicate<std::greater<value_type>, value_type, value_type> pred((std::greater<value_type>())); std::inplace_merge(Iter(ia), Iter(ia+M), Iter(ia+N), std::ref(pred)); if(N > 0) { assert(ia[0] == static_cast<int>(N)-1); assert(ia[N-1] == 0); assert(std::is_sorted(ia, ia+N, std::greater<value_type>())); assert(pred.count() <= (N-1)); } delete [] ia; } template <class Iter> void test(unsigned N) { test_one<Iter>(N, 0); test_one<Iter>(N, N/4); test_one<Iter>(N, N/2); test_one<Iter>(N, 3*N/4); test_one<Iter>(N, N); } template <class Iter> void test() { test_one<Iter>(0, 0); test_one<Iter>(1, 0); test_one<Iter>(1, 1); test_one<Iter>(2, 0); test_one<Iter>(2, 1); test_one<Iter>(2, 2); test_one<Iter>(3, 0); test_one<Iter>(3, 1); test_one<Iter>(3, 2); test_one<Iter>(3, 3); test<Iter>(4); test<Iter>(20); test<Iter>(100); test<Iter>(1000); } struct less_by_first { template <typename Pair> bool operator()(const Pair& lhs, const Pair& rhs) { return std::less<typename Pair::first_type>()(lhs.first, rhs.first); } }; void test_PR31166 () { typedef std::pair<int, int> P; typedef std::vector<P> V; P vec[5] = {P(1, 0), P(2, 0), P(2, 1), P(2, 2), P(2, 3)}; for ( int i = 0; i < 5; ++i ) { V res(vec, vec + 5); std::inplace_merge(res.begin(), res.begin() + i, res.end(), less_by_first()); assert(res.size() == 5); assert(std::equal(res.begin(), res.end(), vec)); } } int main() { test<bidirectional_iterator<int*> >(); test<random_access_iterator<int*> >(); test<int*>(); #if TEST_STD_VER >= 11 test<bidirectional_iterator<S*> >(); test<random_access_iterator<S*> >(); test<S*>(); { int N = 100; unsigned M = 50; std::unique_ptr<int>* ia = new std::unique_ptr<int>[N]; for (int i = 0; i < N; ++i) ia[i].reset(new int(i)); std::shuffle(ia, ia+N, randomness); std::sort(ia, ia+M, indirect_less()); std::sort(ia+M, ia+N, indirect_less()); std::inplace_merge(ia, ia+M, ia+N, indirect_less()); if(N > 0) { assert(*ia[0] == 0); assert(*ia[N-1] == N-1); assert(std::is_sorted(ia, ia+N, indirect_less())); } delete [] ia; } #endif // TEST_STD_VER >= 11 test_PR31166(); } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other GpuMaterials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or bpied warranties, including, but not limited to, the bpied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #include "precomp.hpp" using namespace std; using namespace cv; using namespace cv::gpu; #if !defined (HAVE_CUDA) || defined (CUDA_DISABLER) cv::gpu::PyrLKOpticalFlow::PyrLKOpticalFlow() { throw_nogpu(); } void cv::gpu::PyrLKOpticalFlow::sparse(const GpuMat&, const GpuMat&, const GpuMat&, GpuMat&, GpuMat&, GpuMat*) { throw_nogpu(); } void cv::gpu::PyrLKOpticalFlow::dense(const GpuMat&, const GpuMat&, GpuMat&, GpuMat&, GpuMat*) { throw_nogpu(); } void cv::gpu::PyrLKOpticalFlow::releaseMemory() {} #else /* !defined (HAVE_CUDA) */ namespace cv { namespace gpu { namespace device { namespace pyrlk { void loadConstants(int2 winSize, int iters); void lkSparse1_gpu(PtrStepSzf I, PtrStepSzf J, const float2* prevPts, float2* nextPts, uchar* status, float* err, int ptcount, int level, dim3 block, dim3 patch, cudaStream_t stream = 0); void lkSparse4_gpu(PtrStepSz<float4> I, PtrStepSz<float4> J, const float2* prevPts, float2* nextPts, uchar* status, float* err, int ptcount, int level, dim3 block, dim3 patch, cudaStream_t stream = 0); void lkDense_gpu(PtrStepSzb I, PtrStepSzf J, PtrStepSzf u, PtrStepSzf v, PtrStepSzf prevU, PtrStepSzf prevV, PtrStepSzf err, int2 winSize, cudaStream_t stream = 0); } }}} cv::gpu::PyrLKOpticalFlow::PyrLKOpticalFlow() { winSize = Size(21, 21); maxLevel = 3; iters = 30; useInitialFlow = false; isDeviceArch11_ = !DeviceInfo().supports(FEATURE_SET_COMPUTE_12); } namespace { void calcPatchSize(cv::Size winSize, dim3& block, dim3& patch, bool isDeviceArch11) { if (winSize.width > 32 && winSize.width > 2 * winSize.height) { block.x = isDeviceArch11 ? 16 : 32; block.y = 8; } else { block.x = 16; block.y = isDeviceArch11 ? 8 : 16; } patch.x = (winSize.width + block.x - 1) / block.x; patch.y = (winSize.height + block.y - 1) / block.y; block.z = patch.z = 1; } } void cv::gpu::PyrLKOpticalFlow::sparse(const GpuMat& prevImg, const GpuMat& nextImg, const GpuMat& prevPts, GpuMat& nextPts, GpuMat& status, GpuMat* err) { using namespace cv::gpu::device::pyrlk; if (prevPts.empty()) { nextPts.release(); status.release(); if (err) err->release(); return; } dim3 block, patch; calcPatchSize(winSize, block, patch, isDeviceArch11_); CV_Assert(prevImg.type() == CV_8UC1 || prevImg.type() == CV_8UC3 || prevImg.type() == CV_8UC4); CV_Assert(prevImg.size() == nextImg.size() && prevImg.type() == nextImg.type()); CV_Assert(maxLevel >= 0); CV_Assert(winSize.width > 2 && winSize.height > 2); CV_Assert(patch.x > 0 && patch.x < 6 && patch.y > 0 && patch.y < 6); CV_Assert(prevPts.rows == 1 && prevPts.type() == CV_32FC2); if (useInitialFlow) CV_Assert(nextPts.size() == prevPts.size() && nextPts.type() == CV_32FC2); else ensureSizeIsEnough(1, prevPts.cols, prevPts.type(), nextPts); GpuMat temp1 = (useInitialFlow ? nextPts : prevPts).reshape(1); GpuMat temp2 = nextPts.reshape(1); multiply(temp1, Scalar::all(1.0 / (1 << maxLevel) / 2.0), temp2); ensureSizeIsEnough(1, prevPts.cols, CV_8UC1, status); status.setTo(Scalar::all(1)); if (err) ensureSizeIsEnough(1, prevPts.cols, CV_32FC1, *err); // build the image pyramids. prevPyr_.resize(maxLevel + 1); nextPyr_.resize(maxLevel + 1); int cn = prevImg.channels(); if (cn == 1 || cn == 4) { prevImg.convertTo(prevPyr_[0], CV_32F); nextImg.convertTo(nextPyr_[0], CV_32F); } else { cvtColor(prevImg, buf_, COLOR_BGR2BGRA); buf_.convertTo(prevPyr_[0], CV_32F); cvtColor(nextImg, buf_, COLOR_BGR2BGRA); buf_.convertTo(nextPyr_[0], CV_32F); } for (int level = 1; level <= maxLevel; ++level) { pyrDown(prevPyr_[level - 1], prevPyr_[level]); pyrDown(nextPyr_[level - 1], nextPyr_[level]); } loadConstants(make_int2(winSize.width, winSize.height), iters); for (int level = maxLevel; level >= 0; level--) { if (cn == 1) { lkSparse1_gpu(prevPyr_[level], nextPyr_[level], prevPts.ptr<float2>(), nextPts.ptr<float2>(), status.ptr(), level == 0 && err ? err->ptr<float>() : 0, prevPts.cols, level, block, patch); } else { lkSparse4_gpu(prevPyr_[level], nextPyr_[level], prevPts.ptr<float2>(), nextPts.ptr<float2>(), status.ptr(), level == 0 && err ? err->ptr<float>() : 0, prevPts.cols, level, block, patch); } } } void cv::gpu::PyrLKOpticalFlow::dense(const GpuMat& prevImg, const GpuMat& nextImg, GpuMat& u, GpuMat& v, GpuMat* err) { using namespace cv::gpu::device::pyrlk; CV_Assert(prevImg.type() == CV_8UC1); CV_Assert(prevImg.size() == nextImg.size() && prevImg.type() == nextImg.type()); CV_Assert(maxLevel >= 0); CV_Assert(winSize.width > 2 && winSize.height > 2); if (err) err->create(prevImg.size(), CV_32FC1); // build the image pyramids. prevPyr_.resize(maxLevel + 1); nextPyr_.resize(maxLevel + 1); prevPyr_[0] = prevImg; nextImg.convertTo(nextPyr_[0], CV_32F); for (int level = 1; level <= maxLevel; ++level) { pyrDown(prevPyr_[level - 1], prevPyr_[level]); pyrDown(nextPyr_[level - 1], nextPyr_[level]); } uPyr_.resize(2); vPyr_.resize(2); ensureSizeIsEnough(prevImg.size(), CV_32FC1, uPyr_[0]); ensureSizeIsEnough(prevImg.size(), CV_32FC1, vPyr_[0]); ensureSizeIsEnough(prevImg.size(), CV_32FC1, uPyr_[1]); ensureSizeIsEnough(prevImg.size(), CV_32FC1, vPyr_[1]); uPyr_[1].setTo(Scalar::all(0)); vPyr_[1].setTo(Scalar::all(0)); int2 winSize2i = make_int2(winSize.width, winSize.height); loadConstants(winSize2i, iters); PtrStepSzf derr = err ? *err : PtrStepSzf(); int idx = 0; for (int level = maxLevel; level >= 0; level--) { int idx2 = (idx + 1) & 1; lkDense_gpu(prevPyr_[level], nextPyr_[level], uPyr_[idx], vPyr_[idx], uPyr_[idx2], vPyr_[idx2], level == 0 ? derr : PtrStepSzf(), winSize2i); if (level > 0) idx = idx2; } uPyr_[idx].copyTo(u); vPyr_[idx].copyTo(v); } void cv::gpu::PyrLKOpticalFlow::releaseMemory() { prevPyr_.clear(); nextPyr_.clear(); buf_.release(); uPyr_[0].release(); vPyr_[0].release(); uPyr_[1].release(); vPyr_[1].release(); } #endif /* !defined (HAVE_CUDA) */ <commit_msg>Revert "Merge pull request #141 from jet47/gpu-pyrlk-fix" because this bug appears only in 2.4<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other GpuMaterials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or bpied warranties, including, but not limited to, the bpied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #include "precomp.hpp" using namespace std; using namespace cv; using namespace cv::gpu; #if !defined (HAVE_CUDA) || defined (CUDA_DISABLER) cv::gpu::PyrLKOpticalFlow::PyrLKOpticalFlow() { throw_nogpu(); } void cv::gpu::PyrLKOpticalFlow::sparse(const GpuMat&, const GpuMat&, const GpuMat&, GpuMat&, GpuMat&, GpuMat*) { throw_nogpu(); } void cv::gpu::PyrLKOpticalFlow::dense(const GpuMat&, const GpuMat&, GpuMat&, GpuMat&, GpuMat*) { throw_nogpu(); } void cv::gpu::PyrLKOpticalFlow::releaseMemory() {} #else /* !defined (HAVE_CUDA) */ namespace cv { namespace gpu { namespace device { namespace pyrlk { void loadConstants(int2 winSize, int iters); void lkSparse1_gpu(PtrStepSzf I, PtrStepSzf J, const float2* prevPts, float2* nextPts, uchar* status, float* err, int ptcount, int level, dim3 block, dim3 patch, cudaStream_t stream = 0); void lkSparse4_gpu(PtrStepSz<float4> I, PtrStepSz<float4> J, const float2* prevPts, float2* nextPts, uchar* status, float* err, int ptcount, int level, dim3 block, dim3 patch, cudaStream_t stream = 0); void lkDense_gpu(PtrStepSzb I, PtrStepSzf J, PtrStepSzf u, PtrStepSzf v, PtrStepSzf prevU, PtrStepSzf prevV, PtrStepSzf err, int2 winSize, cudaStream_t stream = 0); } }}} cv::gpu::PyrLKOpticalFlow::PyrLKOpticalFlow() { winSize = Size(21, 21); maxLevel = 3; iters = 30; useInitialFlow = false; isDeviceArch11_ = !DeviceInfo().supports(FEATURE_SET_COMPUTE_12); } namespace { void calcPatchSize(cv::Size winSize, dim3& block, dim3& patch, bool isDeviceArch11) { if (winSize.width > 32 && winSize.width > 2 * winSize.height) { block.x = isDeviceArch11 ? 16 : 32; block.y = 8; } else { block.x = 16; block.y = isDeviceArch11 ? 8 : 16; } patch.x = (winSize.width + block.x - 1) / block.x; patch.y = (winSize.height + block.y - 1) / block.y; block.z = patch.z = 1; } } void cv::gpu::PyrLKOpticalFlow::sparse(const GpuMat& prevImg, const GpuMat& nextImg, const GpuMat& prevPts, GpuMat& nextPts, GpuMat& status, GpuMat* err) { using namespace cv::gpu::device::pyrlk; if (prevPts.empty()) { nextPts.release(); status.release(); if (err) err->release(); return; } dim3 block, patch; calcPatchSize(winSize, block, patch, isDeviceArch11_); CV_Assert(prevImg.type() == CV_8UC1 || prevImg.type() == CV_8UC3 || prevImg.type() == CV_8UC4); CV_Assert(prevImg.size() == nextImg.size() && prevImg.type() == nextImg.type()); CV_Assert(maxLevel >= 0); CV_Assert(winSize.width > 2 && winSize.height > 2); CV_Assert(patch.x > 0 && patch.x < 6 && patch.y > 0 && patch.y < 6); CV_Assert(prevPts.rows == 1 && prevPts.type() == CV_32FC2); if (useInitialFlow) CV_Assert(nextPts.size() == prevPts.size() && nextPts.type() == CV_32FC2); else ensureSizeIsEnough(1, prevPts.cols, prevPts.type(), nextPts); GpuMat temp1 = (useInitialFlow ? nextPts : prevPts).reshape(1); GpuMat temp2 = nextPts.reshape(1); multiply(temp1, Scalar::all(1.0 / (1 << maxLevel) / 2.0), temp2); ensureSizeIsEnough(1, prevPts.cols, CV_8UC1, status); status.setTo(Scalar::all(1)); if (err) ensureSizeIsEnough(1, prevPts.cols, CV_32FC1, *err); // build the image pyramids. prevPyr_.resize(maxLevel + 1); nextPyr_.resize(maxLevel + 1); int cn = prevImg.channels(); if (cn == 1 || cn == 4) { prevImg.convertTo(prevPyr_[0], CV_32F); nextImg.convertTo(nextPyr_[0], CV_32F); } else { cvtColor(prevImg, buf_, COLOR_BGR2BGRA); buf_.convertTo(prevPyr_[0], CV_32F); cvtColor(nextImg, buf_, COLOR_BGR2BGRA); buf_.convertTo(nextPyr_[0], CV_32F); } for (int level = 1; level <= maxLevel; ++level) { pyrDown(prevPyr_[level - 1], prevPyr_[level]); pyrDown(nextPyr_[level - 1], nextPyr_[level]); } loadConstants(make_int2(winSize.width, winSize.height), iters); for (int level = maxLevel; level >= 0; level--) { if (cn == 1) { lkSparse1_gpu(prevPyr_[level], nextPyr_[level], prevPts.ptr<float2>(), nextPts.ptr<float2>(), status.ptr(), level == 0 && err ? err->ptr<float>() : 0, prevPts.cols, level, block, patch); } else { lkSparse4_gpu(prevPyr_[level], nextPyr_[level], prevPts.ptr<float2>(), nextPts.ptr<float2>(), status.ptr(), level == 0 && err ? err->ptr<float>() : 0, prevPts.cols, level, block, patch); } } } void cv::gpu::PyrLKOpticalFlow::dense(const GpuMat& prevImg, const GpuMat& nextImg, GpuMat& u, GpuMat& v, GpuMat* err) { using namespace cv::gpu::device::pyrlk; CV_Assert(prevImg.type() == CV_8UC1); CV_Assert(prevImg.size() == nextImg.size() && prevImg.type() == nextImg.type()); CV_Assert(maxLevel >= 0); CV_Assert(winSize.width > 2 && winSize.height > 2); if (err) err->create(prevImg.size(), CV_32FC1); // build the image pyramids. prevPyr_.resize(maxLevel + 1); nextPyr_.resize(maxLevel + 1); prevPyr_[0] = prevImg; nextImg.convertTo(nextPyr_[0], CV_32F); for (int level = 1; level <= maxLevel; ++level) { pyrDown(prevPyr_[level - 1], prevPyr_[level]); pyrDown(nextPyr_[level - 1], nextPyr_[level]); } ensureSizeIsEnough(prevImg.size(), CV_32FC1, uPyr_[0]); ensureSizeIsEnough(prevImg.size(), CV_32FC1, vPyr_[0]); ensureSizeIsEnough(prevImg.size(), CV_32FC1, uPyr_[1]); ensureSizeIsEnough(prevImg.size(), CV_32FC1, vPyr_[1]); uPyr_[1].setTo(Scalar::all(0)); vPyr_[1].setTo(Scalar::all(0)); int2 winSize2i = make_int2(winSize.width, winSize.height); loadConstants(winSize2i, iters); PtrStepSzf derr = err ? *err : PtrStepSzf(); int idx = 0; for (int level = maxLevel; level >= 0; level--) { int idx2 = (idx + 1) & 1; lkDense_gpu(prevPyr_[level], nextPyr_[level], uPyr_[idx], vPyr_[idx], uPyr_[idx2], vPyr_[idx2], level == 0 ? derr : PtrStepSzf(), winSize2i); if (level > 0) idx = idx2; } uPyr_[idx].copyTo(u); vPyr_[idx].copyTo(v); } void cv::gpu::PyrLKOpticalFlow::releaseMemory() { prevPyr_.clear(); nextPyr_.clear(); buf_.release(); uPyr_[0].release(); vPyr_[0].release(); uPyr_[1].release(); vPyr_[1].release(); } #endif /* !defined (HAVE_CUDA) */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cf_service.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2005-11-02 12:46:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "osl/mutex.hxx" #include "cppuhelper/implementationentry.hxx" #include "cppuhelper/factory.hxx" #include "cppuhelper/implbase3.hxx" #include "vcl/configsettings.hxx" #include "com/sun/star/uno/XComponentContext.hpp" #include "com/sun/star/lang/XServiceInfo.hpp" #include "com/sun/star/lang/XSingleComponentFactory.hpp" #include "com/sun/star/container/XContentEnumerationAccess.hpp" #include "com/sun/star/container/XNameAccess.hpp" #include "com/sun/star/beans/PropertyValue.hpp" #include <vector> #include <algorithm> #define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) ) #define ARLEN(x) (sizeof (x) / sizeof *(x)) using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using ::rtl::OUString; namespace { OUString SAL_CALL getImplName() { return OUSTR("com.sun.star.comp.rendering.CanvasFactory"); } Sequence<OUString> SAL_CALL getSuppServices() { OUString name = OUSTR("com.sun.star.rendering.CanvasFactory"); return Sequence<OUString>(&name, 1); } //============================================================================== class CanvasFactory : public ::cppu::WeakImplHelper3< lang::XServiceInfo, lang::XMultiComponentFactory, lang::XMultiServiceFactory > { ::osl::Mutex m_mutex; Reference<XComponentContext> m_xContext; Sequence<OUString> m_services; OUString m_serviceName; Reference<lang::XSingleComponentFactory> m_xFactory; Reference<XInterface> use( Reference<lang::XSingleComponentFactory> const & xFactory, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ); Reference<XInterface> lookupAndUse( OUString const & serviceName, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ); public: virtual ~CanvasFactory(); CanvasFactory( Reference<XComponentContext> const & xContext ); // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw (RuntimeException); virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName ) throw (RuntimeException); virtual Sequence<OUString> SAL_CALL getSupportedServiceNames() throw (RuntimeException); // XMultiComponentFactory virtual Sequence<OUString> SAL_CALL getAvailableServiceNames() throw (RuntimeException); virtual Reference<XInterface> SAL_CALL createInstanceWithContext( OUString const & name, Reference<XComponentContext> const & xContext ) throw (Exception); virtual Reference<XInterface> SAL_CALL createInstanceWithArgumentsAndContext( OUString const & name, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ) throw (Exception); // XMultiServiceFactory virtual Reference<XInterface> SAL_CALL createInstance( OUString const & name ) throw (Exception); virtual Reference<XInterface> SAL_CALL createInstanceWithArguments( OUString const & name, Sequence<Any> const & args ) throw (Exception); // virtual Sequence<OUString> SAL_CALL getAvailableServiceNames() // throw (RuntimeException); }; CanvasFactory::CanvasFactory( Reference<XComponentContext> const & xContext ) : m_xContext(xContext) { ::rtl::OUString preferredServices; try { // read out configuration for preferred services: Reference<lang::XMultiServiceFactory> xConfigProvider( m_xContext->getServiceManager()->createInstanceWithContext( OUSTR("com.sun.star.configuration.ConfigurationProvider"), m_xContext ), UNO_QUERY_THROW ); Any propValue( makeAny( beans::PropertyValue( OUSTR("nodepath"), -1, makeAny( OUSTR("/org.openoffice.VCL/Settings/Canvas") ), beans::PropertyState_DIRECT_VALUE ) ) ); Reference<container::XNameAccess> xNameAccess( xConfigProvider->createInstanceWithArguments( OUSTR("com.sun.star.configuration.ConfigurationAccess"), Sequence<Any>( &propValue, 1 ) ), UNO_QUERY ); if (xNameAccess.is()) xNameAccess->getByName( OUSTR("PreferredServices") ) >>= preferredServices; } catch (RuntimeException &) { throw; } catch (Exception & exc) { (void) exc; } ::std::vector< ::rtl::OUString > services; sal_Int32 tokenPos = 0; do { ::rtl::OUString oneService = preferredServices.getToken( 0, ';', tokenPos ); if ( oneService.getLength() ) services.push_back( oneService ); } while ( tokenPos > 0 ); m_services.realloc( services.size() ); ::std::copy( services.begin(), services.end(), m_services.getArray() ); // append the usual preferred ones: sal_Int32 pos = m_services.getLength(); #if defined WNT m_services.realloc( pos + 4 ); m_services[ pos++ ] = OUSTR("com.sun.star.rendering.DXCanvas"); m_services[ pos++ ] = OUSTR("com.sun.star.rendering.GLCanvas"); #else m_services.realloc( pos + 3 ); m_services[ pos++ ] = OUSTR("com.sun.star.rendering.GLCanvas"); #endif m_services[ pos++ ] = OUSTR("com.sun.star.rendering.JavaCanvas"); m_services[ pos ] = OUSTR("com.sun.star.rendering.VCLCanvas"); } CanvasFactory::~CanvasFactory() { } //------------------------------------------------------------------------------ Reference<XInterface> create( Reference<XComponentContext> const & xContext ) { return static_cast< ::cppu::OWeakObject * >( new CanvasFactory( xContext ) ); } // XServiceInfo //______________________________________________________________________________ OUString CanvasFactory::getImplementationName() throw (RuntimeException) { return getImplName(); } //______________________________________________________________________________ sal_Bool CanvasFactory::supportsService( OUString const & serviceName ) throw (RuntimeException) { return serviceName.equals(getSuppServices()[0]); } //______________________________________________________________________________ Sequence<OUString> CanvasFactory::getSupportedServiceNames() throw (RuntimeException) { return getSuppServices(); } // XMultiComponentFactory //______________________________________________________________________________ Sequence<OUString> CanvasFactory::getAvailableServiceNames() throw (RuntimeException) { return m_services; } //______________________________________________________________________________ Reference<XInterface> CanvasFactory::createInstanceWithContext( OUString const & name, Reference<XComponentContext> const & xContext ) throw (Exception) { return createInstanceWithArgumentsAndContext( name, Sequence<Any>(), xContext ); } //______________________________________________________________________________ Reference<XInterface> CanvasFactory::use( Reference<lang::XSingleComponentFactory> const & xFactory, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ) { try { return xFactory->createInstanceWithArgumentsAndContext(args, xContext); } catch (RuntimeException &) { throw; } catch (Exception &) { return Reference<XInterface>(); } } //______________________________________________________________________________ Reference<XInterface> CanvasFactory::lookupAndUse( OUString const & serviceName, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ) { { // try to reuse: ::osl::ClearableMutexGuard guard(m_mutex); if (m_serviceName.equals(serviceName)) { Reference<lang::XSingleComponentFactory> xFac(m_xFactory); guard.clear(); Reference<XInterface> xCanvas( use( xFac, args, xContext ) ); if (xCanvas.is()) return xCanvas; } } Reference<container::XContentEnumerationAccess> xEnumAccess( // use service manager of factory: m_xContext->getServiceManager(), UNO_QUERY_THROW ); Reference<container::XEnumeration> xEnum( xEnumAccess->createContentEnumeration( serviceName ) ); if (xEnum.is()) { while (xEnum->hasMoreElements()) { Reference<lang::XSingleComponentFactory> xFactory( xEnum->nextElement(), UNO_QUERY ); OSL_ASSERT( xFactory.is() ); if (xFactory.is()) { Reference<XInterface> xCanvas( use( xFactory, args, xContext ) ); if (xCanvas.is()) { ::osl::MutexGuard guard(m_mutex); // init for reuse: m_xFactory.set(xFactory); m_serviceName = serviceName; return xCanvas; } } } } return Reference<XInterface>(); } //______________________________________________________________________________ Reference<XInterface> CanvasFactory::createInstanceWithArgumentsAndContext( OUString const & preferredOne, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ) throw (Exception) { // preferred one overrides previously used one: if (preferredOne.getLength() > 0) { Reference<XInterface> xCanvas( lookupAndUse( preferredOne, args, xContext ) ); if (xCanvas.is()) return xCanvas; } { // try to reuse previously installed factory: ::osl::ClearableMutexGuard guard(m_mutex); if (m_xFactory.is()) { Reference<lang::XSingleComponentFactory> xFac(m_xFactory); guard.clear(); Reference<XInterface> xCanvas( use( xFac, args, xContext ) ); if (xCanvas.is()) return xCanvas; } } // try configured ones: OUString const * pservices = m_services.getConstArray(); sal_Int32 pos = 0, len = m_services.getLength(); for ( ; pos < len; ++pos ) { Reference<XInterface> xCanvas( lookupAndUse( pservices[pos], args, xContext ) ); if (xCanvas.is()) return xCanvas; } OSL_ENSURE( 0, "### no canvas available!?" ); return Reference<XInterface>(); } // XMultiServiceFactory //______________________________________________________________________________ Reference<XInterface> CanvasFactory::createInstance( OUString const & name ) throw (Exception) { return createInstanceWithArgumentsAndContext( name, Sequence<Any>(), m_xContext ); } //______________________________________________________________________________ Reference<XInterface> CanvasFactory::createInstanceWithArguments( OUString const & name, Sequence<Any> const & args ) throw (Exception) { return createInstanceWithArgumentsAndContext( name, args, m_xContext ); } const ::cppu::ImplementationEntry s_entries [] = { { create, getImplName, getSuppServices, ::cppu::createSingleComponentFactory, 0, 0 }, { 0, 0, 0, 0, 0, 0 } }; } // anon namespace extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } sal_Bool SAL_CALL component_writeInfo( lang::XMultiServiceFactory * pServiceManager, registry::XRegistryKey * pRegistryKey ) { return ::cppu::component_writeInfoHelper( pServiceManager, pRegistryKey, s_entries ); } void * SAL_CALL component_getFactory( sal_Char const * pImplName, lang::XMultiServiceFactory * pServiceManager, registry::XRegistryKey * pRegistryKey ) { return ::cppu::component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey, s_entries ); } } <commit_msg>INTEGRATION: CWS cairocanvas (1.5.14); FILE MERGED 2005/11/04 14:26:03 thb 1.5.14.3: RESYNC: (1.5-1.7); FILE MERGED 2005/07/08 10:41:18 thb 1.5.14.2: #i51657# Reverted getenv() to osl function 2005/07/07 07:58:08 radekdoulik 1.5.14.1: Issue number: 51657 Submitted by: radekdoulik Reviewed by: radekdoulik initial import of cairo canvas code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cf_service.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2006-02-28 10:40:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "osl/mutex.hxx" #include "osl/process.h" #include "cppuhelper/implementationentry.hxx" #include "cppuhelper/factory.hxx" #include "cppuhelper/implbase3.hxx" #include "vcl/configsettings.hxx" #include "com/sun/star/uno/XComponentContext.hpp" #include "com/sun/star/lang/XServiceInfo.hpp" #include "com/sun/star/lang/XSingleComponentFactory.hpp" #include "com/sun/star/container/XContentEnumerationAccess.hpp" #include "com/sun/star/container/XNameAccess.hpp" #include "com/sun/star/beans/PropertyValue.hpp" #include <vector> #include <algorithm> #define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) ) #define ARLEN(x) (sizeof (x) / sizeof *(x)) using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using ::rtl::OUString; namespace { OUString SAL_CALL getImplName() { return OUSTR("com.sun.star.comp.rendering.CanvasFactory"); } Sequence<OUString> SAL_CALL getSuppServices() { OUString name = OUSTR("com.sun.star.rendering.CanvasFactory"); return Sequence<OUString>(&name, 1); } //============================================================================== class CanvasFactory : public ::cppu::WeakImplHelper3< lang::XServiceInfo, lang::XMultiComponentFactory, lang::XMultiServiceFactory > { ::osl::Mutex m_mutex; Reference<XComponentContext> m_xContext; Sequence<OUString> m_services; OUString m_serviceName; Reference<lang::XSingleComponentFactory> m_xFactory; Reference<XInterface> use( Reference<lang::XSingleComponentFactory> const & xFactory, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ); Reference<XInterface> lookupAndUse( OUString const & serviceName, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ); public: virtual ~CanvasFactory(); CanvasFactory( Reference<XComponentContext> const & xContext ); // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw (RuntimeException); virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName ) throw (RuntimeException); virtual Sequence<OUString> SAL_CALL getSupportedServiceNames() throw (RuntimeException); // XMultiComponentFactory virtual Sequence<OUString> SAL_CALL getAvailableServiceNames() throw (RuntimeException); virtual Reference<XInterface> SAL_CALL createInstanceWithContext( OUString const & name, Reference<XComponentContext> const & xContext ) throw (Exception); virtual Reference<XInterface> SAL_CALL createInstanceWithArgumentsAndContext( OUString const & name, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ) throw (Exception); // XMultiServiceFactory virtual Reference<XInterface> SAL_CALL createInstance( OUString const & name ) throw (Exception); virtual Reference<XInterface> SAL_CALL createInstanceWithArguments( OUString const & name, Sequence<Any> const & args ) throw (Exception); // virtual Sequence<OUString> SAL_CALL getAvailableServiceNames() // throw (RuntimeException); }; CanvasFactory::CanvasFactory( Reference<XComponentContext> const & xContext ) : m_xContext(xContext) { ::rtl::OUString preferredServices; try { // read out configuration for preferred services: Reference<lang::XMultiServiceFactory> xConfigProvider( m_xContext->getServiceManager()->createInstanceWithContext( OUSTR("com.sun.star.configuration.ConfigurationProvider"), m_xContext ), UNO_QUERY_THROW ); Any propValue( makeAny( beans::PropertyValue( OUSTR("nodepath"), -1, makeAny( OUSTR("/org.openoffice.VCL/Settings/Canvas") ), beans::PropertyState_DIRECT_VALUE ) ) ); Reference<container::XNameAccess> xNameAccess( xConfigProvider->createInstanceWithArguments( OUSTR("com.sun.star.configuration.ConfigurationAccess"), Sequence<Any>( &propValue, 1 ) ), UNO_QUERY ); if (xNameAccess.is()) xNameAccess->getByName( OUSTR("PreferredServices") ) >>= preferredServices; } catch (RuntimeException &) { throw; } catch (Exception & exc) { (void) exc; } ::std::vector< ::rtl::OUString > services; sal_Int32 tokenPos = 0; do { ::rtl::OUString oneService = preferredServices.getToken( 0, ';', tokenPos ); if ( oneService.getLength() ) services.push_back( oneService ); } while ( tokenPos > 0 ); m_services.realloc( services.size() ); ::std::copy( services.begin(), services.end(), m_services.getArray() ); // append the usual preferred ones: sal_Int32 pos = m_services.getLength(); #if defined WNT m_services.realloc( pos + 5 ); m_services[ pos++ ] = OUSTR("com.sun.star.rendering.DXCanvas"); m_services[ pos++ ] = OUSTR("com.sun.star.rendering.GLCanvas"); #else m_services.realloc( pos + 4 ); m_services[ pos++ ] = OUSTR("com.sun.star.rendering.GLCanvas"); #endif m_services[ pos++ ] = OUSTR("com.sun.star.rendering.CairoCanvas"); m_services[ pos++ ] = OUSTR("com.sun.star.rendering.JavaCanvas"); m_services[ pos ] = OUSTR("com.sun.star.rendering.VCLCanvas"); } CanvasFactory::~CanvasFactory() { } //------------------------------------------------------------------------------ Reference<XInterface> create( Reference<XComponentContext> const & xContext ) { return static_cast< ::cppu::OWeakObject * >( new CanvasFactory( xContext ) ); } // XServiceInfo //______________________________________________________________________________ OUString CanvasFactory::getImplementationName() throw (RuntimeException) { return getImplName(); } //______________________________________________________________________________ sal_Bool CanvasFactory::supportsService( OUString const & serviceName ) throw (RuntimeException) { return serviceName.equals(getSuppServices()[0]); } //______________________________________________________________________________ Sequence<OUString> CanvasFactory::getSupportedServiceNames() throw (RuntimeException) { return getSuppServices(); } // XMultiComponentFactory //______________________________________________________________________________ Sequence<OUString> CanvasFactory::getAvailableServiceNames() throw (RuntimeException) { return m_services; } //______________________________________________________________________________ Reference<XInterface> CanvasFactory::createInstanceWithContext( OUString const & name, Reference<XComponentContext> const & xContext ) throw (Exception) { return createInstanceWithArgumentsAndContext( name, Sequence<Any>(), xContext ); } //______________________________________________________________________________ Reference<XInterface> CanvasFactory::use( Reference<lang::XSingleComponentFactory> const & xFactory, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ) { try { return xFactory->createInstanceWithArgumentsAndContext(args, xContext); } catch (RuntimeException &) { throw; } catch (Exception &) { return Reference<XInterface>(); } } //______________________________________________________________________________ Reference<XInterface> CanvasFactory::lookupAndUse( OUString const & serviceName, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ) { { // try to reuse: ::osl::ClearableMutexGuard guard(m_mutex); if (m_serviceName.equals(serviceName)) { Reference<lang::XSingleComponentFactory> xFac(m_xFactory); guard.clear(); Reference<XInterface> xCanvas( use( xFac, args, xContext ) ); if (xCanvas.is()) return xCanvas; } } Reference<container::XContentEnumerationAccess> xEnumAccess( // use service manager of factory: m_xContext->getServiceManager(), UNO_QUERY_THROW ); Reference<container::XEnumeration> xEnum( xEnumAccess->createContentEnumeration( serviceName ) ); if (xEnum.is()) { while (xEnum->hasMoreElements()) { Reference<lang::XSingleComponentFactory> xFactory( xEnum->nextElement(), UNO_QUERY ); OSL_ASSERT( xFactory.is() ); if (xFactory.is()) { Reference<XInterface> xCanvas( use( xFactory, args, xContext ) ); if (xCanvas.is()) { ::osl::MutexGuard guard(m_mutex); // init for reuse: m_xFactory.set(xFactory); m_serviceName = serviceName; return xCanvas; } } } } return Reference<XInterface>(); } //______________________________________________________________________________ Reference<XInterface> CanvasFactory::createInstanceWithArgumentsAndContext( OUString const & preferredOne, Sequence<Any> const & args, Reference<XComponentContext> const & xContext ) throw (Exception) { // preferred one overrides previously used one: if (preferredOne.getLength() > 0) { Reference<XInterface> xCanvas( lookupAndUse( preferredOne, args, xContext ) ); if (xCanvas.is()) return xCanvas; } { // try to reuse previously installed factory: ::osl::ClearableMutexGuard guard(m_mutex); if (m_xFactory.is()) { Reference<lang::XSingleComponentFactory> xFac(m_xFactory); guard.clear(); Reference<XInterface> xCanvas( use( xFac, args, xContext ) ); if (xCanvas.is()) return xCanvas; } } // try configured ones: OUString const * pservices = m_services.getConstArray(); sal_Int32 pos = 0, len = m_services.getLength(); for ( ; pos < len; ++pos ) { Reference<XInterface> xCanvas( lookupAndUse( pservices[pos], args, xContext ) ); if (xCanvas.is()) return xCanvas; } OSL_ENSURE( 0, "### no canvas available!?" ); return Reference<XInterface>(); } // XMultiServiceFactory //______________________________________________________________________________ Reference<XInterface> CanvasFactory::createInstance( OUString const & name ) throw (Exception) { return createInstanceWithArgumentsAndContext( name, Sequence<Any>(), m_xContext ); } //______________________________________________________________________________ Reference<XInterface> CanvasFactory::createInstanceWithArguments( OUString const & name, Sequence<Any> const & args ) throw (Exception) { return createInstanceWithArgumentsAndContext( name, args, m_xContext ); } const ::cppu::ImplementationEntry s_entries [] = { { create, getImplName, getSuppServices, ::cppu::createSingleComponentFactory, 0, 0 }, { 0, 0, 0, 0, 0, 0 } }; } // anon namespace extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } sal_Bool SAL_CALL component_writeInfo( lang::XMultiServiceFactory * pServiceManager, registry::XRegistryKey * pRegistryKey ) { return ::cppu::component_writeInfoHelper( pServiceManager, pRegistryKey, s_entries ); } void * SAL_CALL component_getFactory( sal_Char const * pImplName, lang::XMultiServiceFactory * pServiceManager, registry::XRegistryKey * pRegistryKey ) { return ::cppu::component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey, s_entries ); } } <|endoftext|>
<commit_before>#include <unordered_map> #include <string> #include <numeric> #include <algorithm> #include <Rcpp.h> using namespace Rcpp; using namespace std; // [[Rcpp::export]] SEXP cpp_stack(SEXP arlist) { auto array_list = as<List>(arlist); auto dimnames = vector<vector<string>>(); // dim: names along auto axmap = vector<unordered_map<string, int>>(); // dim: element name->index auto a2r = vector<vector<vector<int>>>(array_list.size()); // array > dim > element // create lookup tables for all present dimension names for (int a=0; a<Rf_xlength(array_list); a++) { // array in arlist auto va = as<NumericVector>(array_list[a]); auto dn = as<List>(va.attr("dimnames")); auto da = as<vector<int>>(va.attr("dim")); a2r[a] = vector<vector<int>>(da.size()); if (dimnames.size() < da.size()) { dimnames.resize(da.size()); axmap.resize(da.size()); } for (int d=0; d<da.size(); d++) { // dimension in array auto dni = as<vector<string>>(dn[d]); for (int e=0; e<da[d]; e++) { // element in dimension if (axmap[d].count(dni[e]) == 0) { cout << "array " << a << " dim " << d << ": " << dni[e] << " -> " << axmap[d].size() << "\n"; axmap[d].emplace(dni[e], axmap[d].size()); dimnames[d].push_back(dni[e]); } a2r[a][d].push_back(axmap[d][dni[e]]); } } } for (auto ai=0; ai<a2r.size(); ai++) for (auto di=0; di<a2r[ai].size(); di++) { cout << "*** array " << ai << " dim " << di << ": "; copy(a2r[ai][di].begin(), a2r[ai][di].end(), ostream_iterator<int>(cout, " ")); cout << "\n"; } // create result array with attributes auto rdim = IntegerVector(dimnames.size()); auto rdnames = List(dimnames.size()); for (int i=0; i<dimnames.size(); i++) { rdim[i] = dimnames[i].size(); rdnames[i] = CharacterVector(dimnames[i].begin(), dimnames[i].end()); } auto n = accumulate(rdim.begin(), rdim.end(), 1, multiplies<int>()); auto result = NumericVector(n); result.attr("dim") = rdim; result.attr("dimnames") = rdnames; // fill the result array auto maxdim = rdim.size() - 1; for (int ai=0; ai<Rf_xlength(array_list); ai++) { auto a = as<NumericVector>(array_list[ai]); auto it = vector<vector<int>::iterator>(a2r[ai].size()); // one for each result dim for (int rd=0; rd<it.size(); rd++) it[rd] = a2r[ai][rd].begin(); int aidx = 0; // consecutive elements in original array do { int ridx_flat = *it[0]; it[0]++; for (int d=0; d<maxdim; d++) { ridx_flat += rdim[d] * *it[d+1]; if (it[d] == a2r[ai][d].end()) { it[d] = a2r[ai][d].begin(); it[d+1]++; } } cout << "result[" << ridx_flat << "] = a[" << aidx << "++]\n"; result[ridx_flat] = a[aidx++]; } while(it[maxdim] != a2r[ai][maxdim].end()); } return result; } <commit_msg>calc offset only when dim jumping<commit_after>#include <unordered_map> #include <string> #include <numeric> #include <algorithm> #include <Rcpp.h> using namespace Rcpp; using namespace std; // [[Rcpp::export]] SEXP cpp_stack(SEXP arlist) { auto array_list = as<List>(arlist); auto dimnames = vector<vector<string>>(); // dim: names along auto axmap = vector<unordered_map<string, int>>(); // dim: element name->index auto a2r = vector<vector<vector<int>>>(array_list.size()); // array > dim > element // create lookup tables for all present dimension names for (int a=0; a<Rf_xlength(array_list); a++) { // array in arlist auto va = as<NumericVector>(array_list[a]); auto dn = as<List>(va.attr("dimnames")); auto da = as<vector<int>>(va.attr("dim")); a2r[a] = vector<vector<int>>(da.size()); if (dimnames.size() < da.size()) { dimnames.resize(da.size()); axmap.resize(da.size()); } for (int d=0; d<da.size(); d++) { // dimension in array auto dni = as<vector<string>>(dn[d]); for (int e=0; e<da[d]; e++) { // element in dimension if (axmap[d].count(dni[e]) == 0) { cout << "array " << a << " dim " << d << ": " << dni[e] << " -> " << axmap[d].size() << "\n"; axmap[d].emplace(dni[e], axmap[d].size()); dimnames[d].push_back(dni[e]); } a2r[a][d].push_back(axmap[d][dni[e]]); } } } for (auto ai=0; ai<a2r.size(); ai++) for (auto di=0; di<a2r[ai].size(); di++) { cout << "*** array " << ai << " dim " << di << ": "; copy(a2r[ai][di].begin(), a2r[ai][di].end(), ostream_iterator<int>(cout, " ")); cout << "\n"; } // create result array with attributes auto rdim = IntegerVector(dimnames.size()); auto rdnames = List(dimnames.size()); for (int i=0; i<dimnames.size(); i++) { rdim[i] = dimnames[i].size(); rdnames[i] = CharacterVector(dimnames[i].begin(), dimnames[i].end()); } auto n = accumulate(rdim.begin(), rdim.end(), 1, multiplies<int>()); auto result = NumericVector(n); result.attr("dim") = rdim; result.attr("dimnames") = rdnames; // fill the result array int maxdim = rdim.size() - 1; for (int ai=0; ai<Rf_xlength(array_list); ai++) { auto a = as<NumericVector>(array_list[ai]); int aidx = 0; // consecutive elements in original array auto it = vector<vector<int>::iterator>(a2r[ai].size()); // one for each result dim for (int d=0; d<it.size(); d++) it[d] = a2r[ai][d].begin(); int dim_offset = 0; for (int d=0; d<maxdim; d++) dim_offset += rdim[d] * *it[d+1]; do { int cur_offset = *it[0]; int dim_offset_new = 0; it[0]++; for (int d=0; d<maxdim; d++) { if (it[d] != a2r[ai][d].end()) // no dimension jump break; dim_offset_new += rdim[d]; // add only dimensions we jump it[d] = a2r[ai][d].begin(); it[d+1]++; } cout << "result[" << cur_offset + dim_offset << "] = a[" << ai << "][" << aidx << "]\n"; result[cur_offset + dim_offset] = a[aidx++]; dim_offset += dim_offset_new; } while(it[maxdim] != a2r[ai][maxdim].end()); } return result; } <|endoftext|>
<commit_before>#pragma once #include "../src/Geometry/Geometry.hpp" #include "../src/Geometry/convex.cpp" #include "../src/Geometry/distance.cpp" #include "../src/Geometry/intersect.cpp" #include "../src/Geometry/intersect_circle.cpp" #include "../src/Graph/Graph.hpp" #include "../src/Graph/bfs01.cpp" #include "../src/Graph/bipartite_matching.cpp" #include "../src/Graph/dijkstra.cpp" #include "../src/Graph/lca.cpp" #include "../src/Graph/max_flow.cpp" #include "../src/Graph/min_cost_flow.cpp" #include "../src/Graph/recession.cpp" #include "../src/Graph/spfa.cpp" #include "../src/Math/eratosthenes.cpp" #include "../src/Math/fft.cpp" #include "../src/Math/matrix.cpp" #include "../src/Math/mod.cpp" #include "../src/Math/vector.cpp" #include "../src/Others/cout.cpp" #include "../src/String/kmp.cpp" #include "../src/String/rolling_hash.cpp" #include "../src/Structure/fenwick_tree.cpp" #include "../src/Structure/rars.cpp" #include "../src/Structure/segment_tree.cpp" #include "../src/Structure/skew_heap.cpp" #include "../src/Structure/slide_min.cpp" #include "../src/Structure/starry_sky_tree.cpp" #include "../src/Structure/unionfind.cpp" using namespace std; class Timer { double start; public: Timer() : start(clock()) {} double stop() { return (clock() - start) / CLOCKS_PER_SEC; } }; void print(const char *name, double t, double x) { t = (t + 2 * x) * 1e9; printf("%s : %.3f ns\n", name, t); // printf("%s : %.3f ns (%.3f ns - %.3f ns)\n", name, t, t - 2 * x, t + 2 * x); } void check(double (*f)(), const char *name) { const int N = 5; vector<double> res(N); for (auto &i: res) i = f(); double ave = accumulate(begin(res), end(res), 0.0) / N; transform(begin(res), end(res), begin(res), [&](double x){ return pow(x - ave, 2); }); double sd = sqrt(accumulate(begin(res), end(res), 0.0) / N); print(name, ave, sd); } mt19937 mt(0); uniform_real_distribution<double> rnd(-100.0, 100.0); const int array_len = 200000; const int query_num = 1000000; // STL vector<int> random_array() { vector<int> res(array_len); for (auto &i: res) i = mt(); return res; } // Structure class Query { public: int type, pos, left, right, value; Query(int len) : type(mt() % 2), pos(mt() % len), left(mt() % len), right(mt() % len), value(mt() % 2000 - 1000) { if (left > right) swap(left, right); ++right; } }; vector<Query> random_query() { vector<Query> res(query_num, array_len); for (auto &i: res) i = Query(array_len); return res; } // Graph const int vertex_num = 50000; const int edge_num = 200000; CGraph<int> random_cgraph(int min_cost, int max_cost) { CGraph<int> g(vertex_num); for (int i = 0; i < edge_num; ++i) { int from = mt() % vertex_num; int to = mt() % vertex_num; int cost = mt() % (max_cost - min_cost) + min_cost; add_edge(g, from, to, cost); } return g; } FGraph<int> random_fgraph(int V, int E, int max_flow) { FGraph<int> g(V); for (int i = 0; i < E; ++i) { int from = mt() % V; int to = mt() % V; int flow = mt() % max_flow; add_edge(g, from, to, flow); } return g; } FCGraph<int, int> random_fcgraph(int V, int E, int max_flow, int max_cost) { FCGraph<int, int> g(V); for (int i = 0; i < E; ++i) { int from = mt() % V; int to = mt() % V; int flow = mt() % max_flow; int cost = mt() % max_cost; add_edge(g, from, to, flow, cost); } return g; } Graph random_tree(int V) { vector<pair<int,int>> edges; for (int i = 1; i < V; ++i) { int p = mt() % i; if (mt() % 2) edges.emplace_back(i, p); else edges.emplace_back(p, i); } shuffle(begin(edges), end(edges), mt); Graph g(V); for (auto e: edges) add_edge(g, e.first, e.second); return g; } // Geometry template<typename T, T (*f)()> vector<T> vectorize() { vector<T> res; for (int i = 0; i < query_num; ++i) res.push_back(f()); return res; } template<typename T> int zero(T x) { return max(0, min(int(abs(x)), 0)); } Point random_point() { return Point(rnd(mt), rnd(mt)); } Segment random_segment() { return Segment(random_point(), random_point()); } Line random_line() { return Line(random_segment()); } Circle random_circle() { return Circle(random_point(), rnd(mt)); } vector<Point> random_points() { return unique(vectorize<Point, random_point>()); } vector<Segment> random_segments() { return vectorize<Segment, random_segment>(); } vector<Line> random_lines() { return vectorize<Line, random_line>(); } vector<Circle> random_circles() { return vectorize<Circle, random_circle>(); } Polygon random_polygon() { Polygon res; const ld pi = acos(-1.0); for (int i = 0; i < query_num; ++i) res.push_back(polar(100.0L, 2 * pi / query_num)); return res; } <commit_msg>impl hash functions<commit_after>#pragma once #include "../src/Geometry/Geometry.hpp" #include "../src/Geometry/convex.cpp" #include "../src/Geometry/distance.cpp" #include "../src/Geometry/intersect.cpp" #include "../src/Geometry/intersect_circle.cpp" #include "../src/Graph/Graph.hpp" #include "../src/Graph/bfs01.cpp" #include "../src/Graph/bipartite_matching.cpp" #include "../src/Graph/dijkstra.cpp" #include "../src/Graph/lca.cpp" #include "../src/Graph/max_flow.cpp" #include "../src/Graph/min_cost_flow.cpp" #include "../src/Graph/recession.cpp" #include "../src/Graph/spfa.cpp" #include "../src/Math/eratosthenes.cpp" #include "../src/Math/fft.cpp" #include "../src/Math/matrix.cpp" #include "../src/Math/mod.cpp" #include "../src/Math/vector.cpp" #include "../src/Others/cout.cpp" #include "../src/String/kmp.cpp" #include "../src/String/rolling_hash.cpp" #include "../src/Structure/fenwick_tree.cpp" #include "../src/Structure/rars.cpp" #include "../src/Structure/segment_tree.cpp" #include "../src/Structure/skew_heap.cpp" #include "../src/Structure/slide_min.cpp" #include "../src/Structure/starry_sky_tree.cpp" #include "../src/Structure/unionfind.cpp" using namespace std; class Timer { double start; public: Timer() : start(clock()) {} double stop() { return (clock() - start) / CLOCKS_PER_SEC; } }; void print(const char *name, double t, double x) { t = (t + 2 * x) * 1e9; printf("%s : %.3f ns\n", name, t); // printf("%s : %.3f ns (%.3f ns - %.3f ns)\n", name, t, t - 2 * x, t + 2 * x); } void check(double (*f)(), const char *name) { const int N = 5; vector<double> res(N); for (auto &i: res) i = f(); double ave = accumulate(begin(res), end(res), 0.0) / N; transform(begin(res), end(res), begin(res), [&](double x){ return pow(x - ave, 2); }); double sd = sqrt(accumulate(begin(res), end(res), 0.0) / N); print(name, ave, sd); } mt19937 mt(0); uniform_real_distribution<double> rnd(-100.0, 100.0); const int array_len = 200000; const int query_num = 1000000; // Hash using ull = unsigned long long; ull my_hash(int n, mt19937 &mt) { return ull(n) * ull(mt()); } ull my_hash(long long n, mt19937 &mt) { return ull(n) * ull(mt()); } ull my_hash(long double n, mt19937 &mt) { return ull(n - 0.123456789) * ull(mt()); } template<typename T> ull my_hash(const complex<T> &n, mt19937 &mt) { return my_hash(real(n), mt) + my_hash(imag(n), mt); } template<typename U, typename T> ull my_hash(const pair<U, T> &n, mt19937 &mt) { return my_hash(n.first, mt) + my_hash(n.second, mt); } template<typename T> ull my_hash(const vector<T> &n, mt19937 &mt) { ull sum = 0; for (const T &i: n) sum += my_hash(i, mt); return sum; } template<typename T> ull my_hash(T n) { mt19937 mt(0); return my_hash(n, mt); } // STL vector<int> random_array() { vector<int> res(array_len); for (auto &i: res) i = mt(); return res; } // Structure class Query { public: int type, pos, left, right, value; Query(int len) : type(mt() % 2), pos(mt() % len), left(mt() % len), right(mt() % len), value(mt() % 2000 - 1000) { if (left > right) swap(left, right); ++right; } }; vector<Query> random_query() { vector<Query> res(query_num, array_len); for (auto &i: res) i = Query(array_len); return res; } // Graph const int vertex_num = 50000; const int edge_num = 200000; CGraph<int> random_cgraph(int min_cost, int max_cost) { CGraph<int> g(vertex_num); for (int i = 0; i < edge_num; ++i) { int from = mt() % vertex_num; int to = mt() % vertex_num; int cost = mt() % (max_cost - min_cost) + min_cost; add_edge(g, from, to, cost); } return g; } FGraph<int> random_fgraph(int V, int E, int max_flow) { FGraph<int> g(V); for (int i = 0; i < E; ++i) { int from = mt() % V; int to = mt() % V; int flow = mt() % max_flow; add_edge(g, from, to, flow); } return g; } FCGraph<int, int> random_fcgraph(int V, int E, int max_flow, int max_cost) { FCGraph<int, int> g(V); for (int i = 0; i < E; ++i) { int from = mt() % V; int to = mt() % V; int flow = mt() % max_flow; int cost = mt() % max_cost; add_edge(g, from, to, flow, cost); } return g; } Graph random_tree(int V) { vector<pair<int,int>> edges; for (int i = 1; i < V; ++i) { int p = mt() % i; if (mt() % 2) edges.emplace_back(i, p); else edges.emplace_back(p, i); } shuffle(begin(edges), end(edges), mt); Graph g(V); for (auto e: edges) add_edge(g, e.first, e.second); return g; } // Geometry template<typename T, T (*f)()> vector<T> vectorize() { vector<T> res; for (int i = 0; i < query_num; ++i) res.push_back(f()); return res; } template<typename T> int zero(T x) { return max(0, min(int(abs(x)), 0)); } Point random_point() { return Point(rnd(mt), rnd(mt)); } Segment random_segment() { return Segment(random_point(), random_point()); } Line random_line() { return Line(random_segment()); } Circle random_circle() { return Circle(random_point(), rnd(mt)); } vector<Point> random_points() { return unique(vectorize<Point, random_point>()); } vector<Segment> random_segments() { return vectorize<Segment, random_segment>(); } vector<Line> random_lines() { return vectorize<Line, random_line>(); } vector<Circle> random_circles() { return vectorize<Circle, random_circle>(); } Polygon random_polygon() { Polygon res; const ld pi = acos(-1.0); for (int i = 0; i < query_num; ++i) res.push_back(polar(100.0L, 2 * pi / query_num)); return res; } <|endoftext|>
<commit_before>#include "audio_nodes.h" #include "app_globals.h" #include <cinder/audio/Context.h> #include <cinder/audio/MonitorNode.h> #include <cinder/app/App.h> #include "resampler_node.h" namespace cieq { AudioNodes::AudioNodes(AppGlobals& globals) : mGlobals(globals) , mIsEnabled(false) {} void AudioNodes::setup(bool auto_enable /*= true*/) { mInputDeviceNode = mGlobals.getAudioContext().createInputDeviceNode(); auto monitorFormat = ci::audio::MonitorNode::Format().windowSize(1024); mMonitorNode = mGlobals.getAudioContext().makeNode(new ci::audio::MonitorNode(monitorFormat)); auto monitorSpectralFormat = ci::audio::MonitorSpectralNode::Format().fftSize(2048).windowSize(1024); mMonitorSpectralNode = mGlobals.getAudioContext().makeNode(new ci::audio::MonitorSpectralNode(monitorSpectralFormat)); auto resamplerFormat = cieq::audio::ResamplerNode::Format().windowSize(512).targetSampleRate(8000.0f); mResamplerNode = mGlobals.getAudioContext().makeNode(new audio::ResamplerNode(resamplerFormat)); mInputDeviceNode >> mMonitorNode; mInputDeviceNode >> mResamplerNode; mInputDeviceNode >> mMonitorSpectralNode; ci::app::getWindow()->setTitle(ci::app::getWindow()->getTitle() + " (" + mInputDeviceNode->getDevice()->getName() + ")"); if (auto_enable) { enableInput(); } } cinder::audio::InputDeviceNode* const AudioNodes::getInputDeviceNode() { return mInputDeviceNode.get(); } cinder::audio::MonitorNode* const AudioNodes::getMonitorNode() { return mMonitorNode.get(); } cinder::audio::MonitorSpectralNode* const AudioNodes::getMonitorSpectralNode() { return mMonitorSpectralNode.get(); } void AudioNodes::enableInput() { if (mIsEnabled) return; mGlobals.getAudioContext().enable(); mInputDeviceNode->enable(); mIsEnabled = true; } void AudioNodes::disableInput() { if (!mIsEnabled) return; mGlobals.getAudioContext().disable(); mInputDeviceNode->disable(); mIsEnabled = false; } void AudioNodes::toggleInput() { if (mIsEnabled) { disableInput(); } else { enableInput(); } } cieq::audio::ResamplerNode* const AudioNodes::getResamplerNode() { return mResamplerNode.get(); } } //!cieq<commit_msg>unplugging resampler node for now<commit_after>#include "audio_nodes.h" #include "app_globals.h" #include <cinder/audio/Context.h> #include <cinder/audio/MonitorNode.h> #include <cinder/app/App.h> #include "resampler_node.h" namespace cieq { AudioNodes::AudioNodes(AppGlobals& globals) : mGlobals(globals) , mIsEnabled(false) {} void AudioNodes::setup(bool auto_enable /*= true*/) { mInputDeviceNode = mGlobals.getAudioContext().createInputDeviceNode(); auto monitorFormat = ci::audio::MonitorNode::Format().windowSize(1024); mMonitorNode = mGlobals.getAudioContext().makeNode(new ci::audio::MonitorNode(monitorFormat)); auto monitorSpectralFormat = ci::audio::MonitorSpectralNode::Format().fftSize(2048).windowSize(1024); mMonitorSpectralNode = mGlobals.getAudioContext().makeNode(new ci::audio::MonitorSpectralNode(monitorSpectralFormat)); /*auto resamplerFormat = cieq::audio::ResamplerNode::Format().windowSize(512).targetSampleRate(8000.0f); mResamplerNode = mGlobals.getAudioContext().makeNode(new audio::ResamplerNode(resamplerFormat));*/ mInputDeviceNode >> mMonitorNode; //mInputDeviceNode >> mResamplerNode; mInputDeviceNode >> mMonitorSpectralNode; ci::app::getWindow()->setTitle(ci::app::getWindow()->getTitle() + " (" + mInputDeviceNode->getDevice()->getName() + ")"); if (auto_enable) { enableInput(); } } cinder::audio::InputDeviceNode* const AudioNodes::getInputDeviceNode() { return mInputDeviceNode.get(); } cinder::audio::MonitorNode* const AudioNodes::getMonitorNode() { return mMonitorNode.get(); } cinder::audio::MonitorSpectralNode* const AudioNodes::getMonitorSpectralNode() { return mMonitorSpectralNode.get(); } void AudioNodes::enableInput() { if (mIsEnabled) return; mGlobals.getAudioContext().enable(); mInputDeviceNode->enable(); mIsEnabled = true; } void AudioNodes::disableInput() { if (!mIsEnabled) return; mGlobals.getAudioContext().disable(); mInputDeviceNode->disable(); mIsEnabled = false; } void AudioNodes::toggleInput() { if (mIsEnabled) { disableInput(); } else { enableInput(); } } cieq::audio::ResamplerNode* const AudioNodes::getResamplerNode() { return mResamplerNode.get(); } } //!cieq<|endoftext|>
<commit_before>#include <catch.hpp> #include <cmap.hpp> using cmap::make_map; using cmap::map; SCENARIO("Helo") { constexpr auto lookup = make_map(map(1,2), map(2,3), map(5,7)); CHECK( lookup[1] == 2 ); CHECK( lookup[2] == 3 ); CHECK( lookup[5] == 7 ); } <commit_msg>Added more tests<commit_after>#include <catch.hpp> #include <cmap.hpp> using cmap::make_map; using cmap::map; SCENARIO("Compile time mapping") { GIVEN("a map of int -> int") { constexpr auto lookup = make_map( map(1,2), map(2,3), map(5,7) ); THEN("chek each mapping") { CHECK( lookup[1] == 2 ); CHECK( lookup[2] == 3 ); CHECK( lookup[5] == 7 ); } } GIVEN("a custom type") { struct MyType { constexpr bool operator==(const MyType& rhs) const { return value == rhs.value; } const int value; }; GIVEN("a map of int -> custom type") { constexpr auto lookup = make_map( map(42, MyType{12}), map(43, MyType{13}), map(44, MyType{14}) ); THEN("check each mapping") { CHECK( lookup[42] == MyType{12} ); CHECK( lookup[43] == MyType{13} ); CHECK( lookup[44] == MyType{14} ); } } GIVEN("a map of custom type -> int") { constexpr auto lookup = make_map( map(MyType{12}, 42), map(MyType{13}, 43), map(MyType{14}, 44) ); THEN("check each mapping") { CHECK( lookup[MyType{12}] == 42 ); CHECK( lookup[MyType{13}] == 43 ); CHECK( lookup[MyType{14}] == 44 ); } } } } <|endoftext|>
<commit_before>#include <cstdlib> #include <cstring> #include <cstdio> #include <iostream> #include <log4cpp/Category.hh> #include <log4cpp/OstreamAppender.hh> #include <log4cpp/FileAppender.hh> #include <log4cpp/BasicLayout.hh> #include <log4cpp/PatternLayout.hh> #include <log4cpp/TimeStamp.hh> #include "Clock.hh" // ----------------------------------------------------------------------------- int main(int argc, char* argv[]) { int count = argc > 1 ? std::atoi(argv[1]) : 100; size_t size = argc > 2 ? std::atoi(argv[2]) : 128; std::cout << " count: " << count << std::endl << " size: " << size << " bytes" << std::endl << std::endl; log4cpp::Category& root = log4cpp::Category::getRoot(); root.setPriority(log4cpp::Priority::ERROR); log4cpp::OstreamAppender ostreamAppender("cerr", &std::cerr); log4cpp::FileAppender fileAppender("stderr", fileno(stderr)); ostreamAppender.setLayout(new log4cpp::BasicLayout()); fileAppender.setLayout(new log4cpp::BasicLayout()); root.removeAllAppenders(); root.addAppender(ostreamAppender); log4cpp::Category& log = log4cpp::Category::getInstance("someCategory"); Clock clock; char* buffer = new char[size + 1]; std::memset(buffer, 'X', size + 1); buffer[size] = '\0'; std::cout << "BasicLayout:" << std::endl; { clock.start(); for (int i = 0; i < count; i++) log.error("%s", buffer); clock.stop(); std::cout << " buffer ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { const char* buffer2 = buffer; clock.start(); for (int i = 0; i < count; i++) log.error(std::string(buffer2)); clock.stop(); std::cout << " buffer ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); clock.start(); for (int i = 0; i < count; i++) log << log4cpp::Priority::ERROR << str; clock.stop(); std::cout << " stream ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); clock.start(); for (int i = 0; i < count; i++) log << log4cpp::Priority::ERROR << buffer; clock.stop(); std::cout << " stream2 ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); clock.start(); for (int i = 0; i < count; i++) log.error(str); clock.stop(); std::cout << " string ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); root.removeAllAppenders(); root.addAppender(fileAppender); clock.start(); for (int i = 0; i < count; i++) log.error(str); clock.stop(); std::cout << " string file: " << ((float)clock.elapsed()) / count << " us" << std::endl; } std::cout << "PatternLayout:" << std::endl; { log4cpp::PatternLayout* patternLayout = new log4cpp::PatternLayout(); patternLayout->setConversionPattern("%R %p %c %x: %m\n"); ostreamAppender.setLayout(patternLayout); } { log4cpp::PatternLayout* patternLayout = new log4cpp::PatternLayout(); patternLayout->setConversionPattern("%R %p %c %x: %m\n"); fileAppender.setLayout(patternLayout); } root.removeAllAppenders(); root.addAppender(ostreamAppender); { clock.start(); for (int i = 0; i < count; i++) log.error("%s", buffer); clock.stop(); std::cout << " buffer ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); clock.start(); for (int i = 0; i < count; i++) log.error(str); clock.stop(); std::cout << " string ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); root.removeAllAppenders(); root.addAppender(fileAppender); clock.start(); for (int i = 0; i < count; i++) log.error(str); clock.stop(); std::cout << " string file: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { clock.start(); for (int i = 0; i < count; i++) fprintf(stderr, "%d ERROR someCategory : %s\n", log4cpp::TimeStamp().getSeconds(), buffer); clock.stop(); std::cout << std::endl << " fprintf: " << ((float)clock.elapsed()) / count << " us" << std::endl; } log4cpp::Category::shutdown(); return 0; } <commit_msg>Added tests.<commit_after>#include <cstdlib> #include <cstring> #include <cstdio> #include <iostream> #include <log4cpp/Category.hh> #include <log4cpp/OstreamAppender.hh> #include <log4cpp/FileAppender.hh> #include <log4cpp/BasicLayout.hh> #include <log4cpp/PatternLayout.hh> #include <log4cpp/TimeStamp.hh> #include "Clock.hh" // ----------------------------------------------------------------------------- int main(int argc, char* argv[]) { int count = argc > 1 ? std::atoi(argv[1]) : 100; size_t size = argc > 2 ? std::atoi(argv[2]) : 128; std::cout << " count: " << count << std::endl << " size: " << size << " bytes" << std::endl << std::endl; log4cpp::Category& root = log4cpp::Category::getRoot(); root.setPriority(log4cpp::Priority::ERROR); log4cpp::OstreamAppender ostreamAppender("cerr", &std::cerr); log4cpp::FileAppender fileAppender("stderr", fileno(stderr)); ostreamAppender.setLayout(new log4cpp::BasicLayout()); fileAppender.setLayout(new log4cpp::BasicLayout()); root.removeAllAppenders(); root.addAppender(ostreamAppender); log4cpp::Category& log = log4cpp::Category::getInstance("someCategory"); Clock clock; char* buffer = new char[size + 1]; std::memset(buffer, 'X', size + 1); buffer[size] = '\0'; std::cout << "BasicLayout:" << std::endl; { clock.start(); for (int i = 0; i < count; i++) log.error("%s", buffer); clock.stop(); std::cout << " charbuf printf ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { const char* buffer2 = buffer; clock.start(); for (int i = 0; i < count; i++) log.error(std::string(buffer2)); clock.stop(); std::cout << " charbuf string ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); clock.start(); for (int i = 0; i < count; i++) log << log4cpp::Priority::ERROR << str; clock.stop(); std::cout << " string stream ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { clock.start(); for (int i = 0; i < count; i++) log << log4cpp::Priority::ERROR << buffer; clock.stop(); std::cout << " charbuf stream ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); clock.start(); log4cpp::CategoryStream s(log << log4cpp::Priority::ERROR); for (int i = 0; i < count; i++) s << str << log4cpp::CategoryStream::ENDLINE; clock.stop(); std::cout << " string stream2 ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { clock.start(); log4cpp::CategoryStream s(log << log4cpp::Priority::ERROR); for (int i = 0; i < count; i++) s << buffer << log4cpp::CategoryStream::ENDLINE; clock.stop(); std::cout << " charbuf stream2 ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); clock.start(); for (int i = 0; i < count; i++) log.error(str); clock.stop(); std::cout << " direct string ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); root.removeAllAppenders(); root.addAppender(fileAppender); clock.start(); for (int i = 0; i < count; i++) log.error(str); clock.stop(); std::cout << " direct string file: " << ((float)clock.elapsed()) / count << " us" << std::endl; } std::cout << "PatternLayout:" << std::endl; { log4cpp::PatternLayout* patternLayout = new log4cpp::PatternLayout(); patternLayout->setConversionPattern("%R %p %c %x: %m\n"); ostreamAppender.setLayout(patternLayout); } { log4cpp::PatternLayout* patternLayout = new log4cpp::PatternLayout(); patternLayout->setConversionPattern("%R %p %c %x: %m\n"); fileAppender.setLayout(patternLayout); } root.removeAllAppenders(); root.addAppender(ostreamAppender); { clock.start(); for (int i = 0; i < count; i++) log.error("%s", buffer); clock.stop(); std::cout << " charbuf printf ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); clock.start(); for (int i = 0; i < count; i++) log.error(str); clock.stop(); std::cout << " direct string ostream: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { std::string str(size, 'X'); root.removeAllAppenders(); root.addAppender(fileAppender); clock.start(); for (int i = 0; i < count; i++) log.error(str); clock.stop(); std::cout << " string file: " << ((float)clock.elapsed()) / count << " us" << std::endl; } { clock.start(); for (int i = 0; i < count; i++) fprintf(stderr, "%d ERROR someCategory : %s\n", log4cpp::TimeStamp().getSeconds(), buffer); clock.stop(); std::cout << std::endl << " fprintf: " << ((float)clock.elapsed()) / count << " us" << std::endl; } log4cpp::Category::shutdown(); return 0; } <|endoftext|>
<commit_before>#include "DxContext.hpp" #include "DxDevice.hpp" #include "DxRenderBuffer.hpp" #include "DxDepthStencilBuffer.hpp" #include "DxTexture.hpp" #include "DxSampler.hpp" #include "DxUniformBuffer.hpp" #include "DxVertexShader.hpp" #include "DxPixelShader.hpp" #include "DxVertexBuffer.hpp" #include "VertexLayout.hpp" #include "DxInternalInputLayout.hpp" #include "DxInternalInputLayoutCache.hpp" #include "DxIndexBuffer.hpp" #include "../File.hpp" #include "../Exception.hpp" DxContext::DxContext(ID3D11Device* device, ID3D11DeviceContext* deviceContext) : device(device), deviceContext(deviceContext) { // создать кэш входных разметок inputLayoutCache = NEW(DxInternalInputLayoutCache(this)); } ptr<DxInternalInputLayout> DxContext::CreateInternalInputLayout(VertexLayout* vertexLayout, DxVertexShader* vertexShader) { try { // получить элементы разметки const std::vector<VertexLayout::Element>& elements = vertexLayout->GetElements(); if(elements.empty()) THROW_PRIMARY_EXCEPTION("Vertex layout is empty"); // структуры описания // количество не указывается, так как матрицы требуют несколько элементов std::vector<D3D11_INPUT_ELEMENT_DESC> descs; // строки для имён семантик, их количество известно std::vector<String> semanticNames(elements.size()); // и заполнить их for(size_t i = 0; i < elements.size(); ++i) { const VertexLayout::Element& element = elements[i]; // получить количество необходимых описаний для элемента int needDescsCount; switch(element.type) { case VertexLayout::typeFloat4x4: needDescsCount = 4; break; default: needDescsCount = 1; break; } // выбрать формат элемента DXGI_FORMAT format; switch(element.type) { case VertexLayout::typeFloat: format = DXGI_FORMAT_R32_FLOAT; break; case VertexLayout::typeFloat2: format = DXGI_FORMAT_R32G32_FLOAT; break; case VertexLayout::typeFloat3: format = DXGI_FORMAT_R32G32B32_FLOAT; break; case VertexLayout::typeFloat4: format = DXGI_FORMAT_R32G32B32A32_FLOAT; break; case VertexLayout::typeFloat4x4: format = DXGI_FORMAT_R32G32B32A32_FLOAT; break; case VertexLayout::typeUInt: format = DXGI_FORMAT_R32_UINT; break; case VertexLayout::typeUInt2: format = DXGI_FORMAT_R32G32_UINT; break; case VertexLayout::typeUInt3: format = DXGI_FORMAT_R32G32B32_UINT; break; case VertexLayout::typeUInt4: format = DXGI_FORMAT_R32G32B32A32_UINT; break; default: THROW_PRIMARY_EXCEPTION("Unknown element type"); } // размер элемента - пока всегда один вектор (float4 или uint4), // так как он нужен только для матриц float4x4 const int elementSize = 16; // имя семантики получается переводом кода семантики в 26-ричную систему (буквы) String& semanticName = semanticNames[i]; semanticName.assign('A', 8); int semantic = element.semantic; for(int j = 0; semantic; ++j) { semanticName[j] = 'A' + semantic % 26; semantic /= 26; } // цикл по вот этим требуемым элементам for(int descIndex = 0; descIndex < needDescsCount; ++descIndex) { descs.push_back(D3D11_INPUT_ELEMENT_DESC()); D3D11_INPUT_ELEMENT_DESC& desc = descs.back(); // SemanticName в структуре будет заполнено позже, // потому что сейчас адреса в векторе ещё могут поменяться desc.SemanticName = semanticName.c_str(); desc.SemanticIndex = descIndex; desc.Format = format; desc.InputSlot = 0; desc.AlignedByteOffset = element.offset + descIndex * elementSize; desc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; desc.InstanceDataStepRate = 0; } } // получить код шейдера ptr<File> vertexShaderCode = vertexShader->GetCode(); // создать разметку ID3D11InputLayout* inputLayoutInterface; if(FAILED(device->CreateInputLayout(&*descs.begin(), (UINT)descs.size(), vertexShaderCode->GetData(), vertexShaderCode->GetSize(), &inputLayoutInterface))) THROW_PRIMARY_EXCEPTION("Can't create input layout"); return NEW(DxInternalInputLayout(inputLayoutInterface)); } catch(Exception* exception) { THROW_SECONDARY_EXCEPTION("Can't create DX internal input layout", exception); } } void DxContext::Update() { // рендертаргеты { // сейчас единственная оптимизация - количество обновляемых рендертаргетов int end; for(end = renderTargetSlotsCount - 1; end >= 0; --end) if(dirtyRenderBuffers[end]) break; ++end; if(end > 0 || dirtyDepthStencilBuffer) { ID3D11RenderTargetView* views[renderTargetSlotsCount]; for(int i = 0; i < end; ++i) { RenderBuffer* abstractRenderBuffer = boundRenderBuffers[i]; if(abstractRenderBuffer) { DxRenderBuffer* renderBuffer = fast_cast<DxRenderBuffer*>(abstractRenderBuffer); views[i] = renderBuffer->GetRenderTargetViewInterface(); } else views[i] = 0; } ID3D11DepthStencilView* depthStencilView; DepthStencilBuffer* abstractDepthStencilBuffer = boundDepthStencilBuffer; if(abstractDepthStencilBuffer) { DxDepthStencilBuffer* depthStencilBuffer = fast_cast<DxDepthStencilBuffer*>(abstractDepthStencilBuffer); depthStencilView = depthStencilBuffer->GetDepthStencilViewInterface(); } else depthStencilView = 0; // выполнить вызов deviceContext->OMSetRenderTargets(end, views, depthStencilView); // обновить флажки for(int i = 0; i < end; ++i) dirtyRenderBuffers[i] = false; dirtyDepthStencilBuffer = false; } } // текстуры { // сейчас единственная оптимизация - начало и конец в списке обновляемых текстур int end; for(end = textureSlotsCount - 1; end >= 0; --end) if(dirtyTextures[end]) break; ++end; int begin; for(begin = 0; begin < end; ++begin) if(dirtyTextures[begin]) break; if(begin < end) { ID3D11ShaderResourceView* views[textureSlotsCount]; for(int i = begin; i < end; ++i) { Texture* abstractTexture = boundTextures[i]; if(abstractTexture) { DxTexture* texture = fast_cast<DxTexture*>(abstractTexture); views[i] = texture->GetShaderResourceViewInterface(); } else views[i] = 0; } // установить текстуры deviceContext->VSSetShaderResources(begin, end - begin, views + begin); deviceContext->PSSetShaderResources(begin, end - begin, views + begin); // обновить флажки for(int i = begin; i < end; ++i) dirtyTextures[i] = false; } } // семплеры { // сейчас единственная оптимизация - начало и конец в списке обновляемых семплеров int end; for(end = textureSlotsCount - 1; end >= 0; --end) if(dirtySamplers[end]) break; ++end; int begin; for(begin = 0; begin < end; ++begin) if(dirtySamplers[begin]) break; if(begin < end) { ID3D11SamplerState* states[textureSlotsCount]; for(int i = begin; i < end; ++i) { Sampler* abstractSampler = boundSamplers[i]; if(abstractSampler) { DxSampler* sampler = fast_cast<DxSampler*>(abstractSampler); states[i] = sampler->GetSamplerStateInterface(); } else states[i] = 0; } // установить семплеры deviceContext->VSSetSamplers(begin, end - begin, states + begin); deviceContext->PSSetSamplers(begin, end - begin, states + begin); // обновить флажки for(int i = begin; i < end; ++i) dirtySamplers[i] = false; } } // константные буферы { // сейчас единственная оптимизация - начало и конец в списке обновляемых текстур int end; for(end = uniformBufferSlotsCount - 1; end >= 0; --end) if(dirtyUniformBuffers[end]) break; ++end; int begin; for(begin = 0; begin < end; ++begin) if(dirtyUniformBuffers[begin]) break; if(begin < end) { ID3D11Buffer* buffers[uniformBufferSlotsCount]; for(int i = begin; i < end; ++i) { UniformBuffer* abstractUniformBuffer = boundUniformBuffers[i]; if(abstractUniformBuffer) { DxUniformBuffer* uniformBuffer = fast_cast<DxUniformBuffer*>(abstractUniformBuffer); buffers[i] = uniformBuffer->GetBufferInterface(); } else buffers[i] = 0; } // установить буферы deviceContext->VSSetConstantBuffers(begin, end - begin, buffers + begin); deviceContext->PSSetConstantBuffers(begin, end - begin, buffers + begin); // обновить флажки for(int i = begin; i < end; ++i) dirtyUniformBuffers[i] = false; } } // входная разметка if(dirtyVertexBuffer || dirtyVertexShader) { ptr<DxInternalInputLayout> inputLayout = inputLayoutCache->GetInputLayout(boundVertexBuffer->GetVertexLayout(), fast_cast<DxVertexShader*>(&*boundVertexShader)); if(inputLayout != boundInputLayout) { deviceContext->IASetInputLayout(inputLayout->GetInputLayoutInterface()); boundInputLayout = inputLayout; } } // вершинный шейдер if(dirtyVertexShader) { ID3D11VertexShader* shader; if(boundVertexShader) shader = fast_cast<DxVertexShader*>(&*boundVertexShader)->GetVertexShaderInterface(); else shader = 0; deviceContext->VSSetShader(shader, NULL, 0); dirtyVertexShader = false; } // пиксельный шейдер if(dirtyPixelShader) { ID3D11PixelShader* shader; if(boundPixelShader) shader = fast_cast<DxPixelShader*>(&*boundPixelShader)->GetPixelShaderInterface(); else shader = 0; deviceContext->PSSetShader(shader, NULL, 0); dirtyPixelShader = false; } } void DxContext::SetUniformBufferData(UniformBuffer* abstractUniformBuffer, const void* data, size_t size) { // проверить, что размер не больше, чем нужно if(size > abstractUniformBuffer->GetSize()) THROW_PRIMARY_EXCEPTION("Data size to set into uniform buffer is too big"); DxUniformBuffer* uniformBuffer = fast_cast<DxUniformBuffer*>(abstractUniformBuffer); //спроецировать буфер D3D11_MAPPED_SUBRESOURCE bufferData; ID3D11Resource* resource = uniformBuffer->GetBufferInterface(); if(FAILED(deviceContext->Map(resource, 0, D3D11_MAP_WRITE_DISCARD, 0, &bufferData))) THROW_PRIMARY_EXCEPTION("Can't map graphics buffer"); //скопировать данные memcpy(bufferData.pData, data, size); //отключить проекцию буфера deviceContext->Unmap(resource, 0); } void DxContext::Draw() { Update(); if(boundIndexBuffer) deviceContext->DrawIndexed(boundIndexBuffer->GetIndicesCount(), 0, 0); else deviceContext->Draw(boundVertexBuffer->GetVerticesCount(), 0); } void DxContext::DrawInstanced(int instancesCount) { Update(); if(boundIndexBuffer) deviceContext->DrawIndexedInstanced(boundIndexBuffer->GetIndicesCount(), instancesCount, 0, 0, 0); else deviceContext->DrawInstanced(boundVertexBuffer->GetVerticesCount(), instancesCount, 0, 0); } <commit_msg>DxContext changed according to context refactoring<commit_after>#include "DxContext.hpp" #include "DxDevice.hpp" #include "DxRenderBuffer.hpp" #include "DxDepthStencilBuffer.hpp" #include "DxTexture.hpp" #include "DxSampler.hpp" #include "DxUniformBuffer.hpp" #include "DxVertexShader.hpp" #include "DxPixelShader.hpp" #include "DxVertexBuffer.hpp" #include "VertexLayout.hpp" #include "DxInternalInputLayout.hpp" #include "DxInternalInputLayoutCache.hpp" #include "DxIndexBuffer.hpp" #include "../File.hpp" #include "../Exception.hpp" DxContext::DxContext(ID3D11Device* device, ID3D11DeviceContext* deviceContext) : device(device), deviceContext(deviceContext) { // создать кэш входных разметок inputLayoutCache = NEW(DxInternalInputLayoutCache(this)); } ptr<DxInternalInputLayout> DxContext::CreateInternalInputLayout(VertexLayout* vertexLayout, DxVertexShader* vertexShader) { try { // получить элементы разметки const std::vector<VertexLayout::Element>& elements = vertexLayout->GetElements(); if(elements.empty()) THROW_PRIMARY_EXCEPTION("Vertex layout is empty"); // структуры описания // количество не указывается, так как матрицы требуют несколько элементов std::vector<D3D11_INPUT_ELEMENT_DESC> descs; // строки для имён семантик, их количество известно std::vector<String> semanticNames(elements.size()); // и заполнить их for(size_t i = 0; i < elements.size(); ++i) { const VertexLayout::Element& element = elements[i]; // получить количество необходимых описаний для элемента int needDescsCount; switch(element.type) { case VertexLayout::typeFloat4x4: needDescsCount = 4; break; default: needDescsCount = 1; break; } // выбрать формат элемента DXGI_FORMAT format; switch(element.type) { case VertexLayout::typeFloat: format = DXGI_FORMAT_R32_FLOAT; break; case VertexLayout::typeFloat2: format = DXGI_FORMAT_R32G32_FLOAT; break; case VertexLayout::typeFloat3: format = DXGI_FORMAT_R32G32B32_FLOAT; break; case VertexLayout::typeFloat4: format = DXGI_FORMAT_R32G32B32A32_FLOAT; break; case VertexLayout::typeFloat4x4: format = DXGI_FORMAT_R32G32B32A32_FLOAT; break; case VertexLayout::typeUInt: format = DXGI_FORMAT_R32_UINT; break; case VertexLayout::typeUInt2: format = DXGI_FORMAT_R32G32_UINT; break; case VertexLayout::typeUInt3: format = DXGI_FORMAT_R32G32B32_UINT; break; case VertexLayout::typeUInt4: format = DXGI_FORMAT_R32G32B32A32_UINT; break; default: THROW_PRIMARY_EXCEPTION("Unknown element type"); } // размер элемента - пока всегда один вектор (float4 или uint4), // так как он нужен только для матриц float4x4 const int elementSize = 16; // имя семантики получается переводом кода семантики в 26-ричную систему (буквы) String& semanticName = semanticNames[i]; semanticName.assign('A', 8); int semantic = element.semantic; for(int j = 0; semantic; ++j) { semanticName[j] = 'A' + semantic % 26; semantic /= 26; } // цикл по вот этим требуемым элементам for(int descIndex = 0; descIndex < needDescsCount; ++descIndex) { descs.push_back(D3D11_INPUT_ELEMENT_DESC()); D3D11_INPUT_ELEMENT_DESC& desc = descs.back(); // SemanticName в структуре будет заполнено позже, // потому что сейчас адреса в векторе ещё могут поменяться desc.SemanticName = semanticName.c_str(); desc.SemanticIndex = descIndex; desc.Format = format; desc.InputSlot = 0; desc.AlignedByteOffset = element.offset + descIndex * elementSize; desc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; desc.InstanceDataStepRate = 0; } } // получить код шейдера ptr<File> vertexShaderCode = vertexShader->GetCode(); // создать разметку ID3D11InputLayout* inputLayoutInterface; if(FAILED(device->CreateInputLayout(&*descs.begin(), (UINT)descs.size(), vertexShaderCode->GetData(), vertexShaderCode->GetSize(), &inputLayoutInterface))) THROW_PRIMARY_EXCEPTION("Can't create input layout"); return NEW(DxInternalInputLayout(inputLayoutInterface)); } catch(Exception* exception) { THROW_SECONDARY_EXCEPTION("Can't create DX internal input layout", exception); } } void DxContext::Update() { // рендертаргеты { // сейчас единственная оптимизация - количество обновляемых рендертаргетов int end; for(end = ContextState::renderTargetSlotsCount - 1; end >= 0; --end) if(targetState.renderBuffers[end] != boundState.renderBuffers[end]) break; ++end; if(end > 0 || targetState.depthStencilBuffer != boundState.depthStencilBuffer) { ID3D11RenderTargetView* views[ContextState::renderTargetSlotsCount]; for(int i = 0; i < end; ++i) { RenderBuffer* abstractRenderBuffer = targetState.renderBuffers[i]; if(abstractRenderBuffer) { DxRenderBuffer* renderBuffer = fast_cast<DxRenderBuffer*>(abstractRenderBuffer); views[i] = renderBuffer->GetRenderTargetViewInterface(); } else views[i] = 0; } ID3D11DepthStencilView* depthStencilView; DepthStencilBuffer* abstractDepthStencilBuffer = targetState.depthStencilBuffer; if(abstractDepthStencilBuffer) { DxDepthStencilBuffer* depthStencilBuffer = fast_cast<DxDepthStencilBuffer*>(abstractDepthStencilBuffer); depthStencilView = depthStencilBuffer->GetDepthStencilViewInterface(); } else depthStencilView = 0; // выполнить вызов deviceContext->OMSetRenderTargets(end, views, depthStencilView); // обновить актуальное состояние for(int i = 0; i < end; ++i) boundState.renderBuffers[i] = targetState.renderBuffers[i]; boundState.depthStencilBuffer = targetState.depthStencilBuffer; } } // текстуры { // сейчас единственная оптимизация - начало и конец в списке обновляемых текстур int end; for(end = ContextState::textureSlotsCount - 1; end >= 0; --end) if(targetState.textures[end] != boundState.textures[end]) break; ++end; int begin; for(begin = 0; begin < end; ++begin) if(targetState.textures[begin] != boundState.textures[begin]) break; if(begin < end) { ID3D11ShaderResourceView* views[ContextState::textureSlotsCount]; for(int i = begin; i < end; ++i) { Texture* abstractTexture = targetState.textures[i]; if(abstractTexture) { DxTexture* texture = fast_cast<DxTexture*>(abstractTexture); views[i] = texture->GetShaderResourceViewInterface(); } else views[i] = 0; } // установить текстуры deviceContext->VSSetShaderResources(begin, end - begin, views + begin); deviceContext->PSSetShaderResources(begin, end - begin, views + begin); // обновить актуальное состояние for(int i = begin; i < end; ++i) boundState.textures[i] = targetState.textures[i]; } } // семплеры { // сейчас единственная оптимизация - начало и конец в списке обновляемых семплеров int end; for(end = ContextState::textureSlotsCount - 1; end >= 0; --end) if(targetState.samplers[end] != boundState.samplers[end]) break; ++end; int begin; for(begin = 0; begin < end; ++begin) if(targetState.samplers[begin] != boundState.samplers[begin]) break; if(begin < end) { ID3D11SamplerState* states[ContextState::textureSlotsCount]; for(int i = begin; i < end; ++i) { Sampler* abstractSampler = targetState.samplers[i]; if(abstractSampler) { DxSampler* sampler = fast_cast<DxSampler*>(abstractSampler); states[i] = sampler->GetSamplerStateInterface(); } else states[i] = 0; } // установить семплеры deviceContext->VSSetSamplers(begin, end - begin, states + begin); deviceContext->PSSetSamplers(begin, end - begin, states + begin); // обновить актуальное состояние for(int i = begin; i < end; ++i) boundState.samplers[i] = targetState.samplers[i]; } } // константные буферы { // сейчас единственная оптимизация - начало и конец в списке обновляемых текстур int end; for(end = ContextState::uniformBufferSlotsCount - 1; end >= 0; --end) if(targetState.uniformBuffers[end] != boundState.uniformBuffers[end]) break; ++end; int begin; for(begin = 0; begin < end; ++begin) if(targetState.uniformBuffers[begin] != boundState.uniformBuffers[begin]) break; if(begin < end) { ID3D11Buffer* buffers[ContextState::uniformBufferSlotsCount]; for(int i = begin; i < end; ++i) { UniformBuffer* abstractUniformBuffer = targetState.uniformBuffers[i]; if(abstractUniformBuffer) { DxUniformBuffer* uniformBuffer = fast_cast<DxUniformBuffer*>(abstractUniformBuffer); buffers[i] = uniformBuffer->GetBufferInterface(); } else buffers[i] = 0; } // установить буферы deviceContext->VSSetConstantBuffers(begin, end - begin, buffers + begin); deviceContext->PSSetConstantBuffers(begin, end - begin, buffers + begin); // обновить актуальное состояние for(int i = begin; i < end; ++i) boundState.uniformBuffers[i] = targetState.uniformBuffers[i]; } } // входная разметка if(targetState.vertexBuffer != boundState.vertexBuffer || targetState.vertexShader != boundState.vertexShader) { ptr<DxInternalInputLayout> inputLayout = inputLayoutCache->GetInputLayout(targetState.vertexBuffer->GetVertexLayout(), fast_cast<DxVertexShader*>(&*targetState.vertexShader)); if(inputLayout != boundInputLayout) { deviceContext->IASetInputLayout(inputLayout->GetInputLayoutInterface()); boundInputLayout = inputLayout; } } // вершинный шейдер if(targetState.vertexShader != boundState.vertexShader) { ID3D11VertexShader* shader; if(targetState.vertexShader) shader = fast_cast<DxVertexShader*>(&*targetState.vertexShader)->GetVertexShaderInterface(); else shader = 0; deviceContext->VSSetShader(shader, NULL, 0); boundState.vertexShader = targetState.vertexShader; } // пиксельный шейдер if(targetState.pixelShader != boundState.pixelShader) { ID3D11PixelShader* shader; if(targetState.pixelShader) shader = fast_cast<DxPixelShader*>(&*targetState.pixelShader)->GetPixelShaderInterface(); else shader = 0; deviceContext->PSSetShader(shader, NULL, 0); boundState.pixelShader = targetState.pixelShader; } } void DxContext::SetUniformBufferData(UniformBuffer* abstractUniformBuffer, const void* data, size_t size) { // проверить, что размер не больше, чем нужно if(size > abstractUniformBuffer->GetSize()) THROW_PRIMARY_EXCEPTION("Data size to set into uniform buffer is too big"); DxUniformBuffer* uniformBuffer = fast_cast<DxUniformBuffer*>(abstractUniformBuffer); //спроецировать буфер D3D11_MAPPED_SUBRESOURCE bufferData; ID3D11Resource* resource = uniformBuffer->GetBufferInterface(); if(FAILED(deviceContext->Map(resource, 0, D3D11_MAP_WRITE_DISCARD, 0, &bufferData))) THROW_PRIMARY_EXCEPTION("Can't map graphics buffer"); //скопировать данные memcpy(bufferData.pData, data, size); //отключить проекцию буфера deviceContext->Unmap(resource, 0); } void DxContext::Draw() { Update(); if(boundState.indexBuffer) deviceContext->DrawIndexed(boundState.indexBuffer->GetIndicesCount(), 0, 0); else deviceContext->Draw(boundState.vertexBuffer->GetVerticesCount(), 0); } void DxContext::DrawInstanced(int instancesCount) { Update(); if(boundState.indexBuffer) deviceContext->DrawIndexedInstanced(boundState.indexBuffer->GetIndicesCount(), instancesCount, 0, 0, 0); else deviceContext->DrawInstanced(boundState.vertexBuffer->GetVerticesCount(), instancesCount, 0, 0); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkImagingFactory.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkObjectFactory.h" #include "vtkImagingFactory.h" #include "vtkToolkits.h" #ifdef VTK_USE_OGLR #include "vtkOpenGLImageMapper.h" #include "vtkOpenGLImager.h" #include "vtkOpenGLImageWindow.h" #include "vtkXOpenGLTextMapper.h" #include "vtkOpenGLPolyDataMapper2D.h" #endif #ifdef VTK_USE_MESA #include "vtkMesaImageMapper.h" #include "vtkMesaImager.h" #include "vtkMesaImageWindow.h" #include "vtkXMesaTextMapper.h" #include "vtkMesaPolyDataMapper2D.h" #endif #ifdef _WIN32 #include "vtkOpenGLImageMapper.h" #include "vtkOpenGLImager.h" #include "vtkWin32OpenGLImageWindow.h" #include "vtkWin32OpenGLTextMapper.h" #include "vtkOpenGLPolyDataMapper2D.h" #include "vtkWin32TextMapper.h" #include "vtkWin32ImageWindow.h" #include "vtkWin32ImageMapper.h" #include "vtkWin32PolyDataMapper2D.h" #else #include "vtkXTextMapper.h" #include "vtkXImageWindow.h" #include "vtkXImageMapper.h" #include "vtkXPolyDataMapper2D.h" #endif const char *vtkImagingFactoryGetRenderLibrary() { const char *temp; // first check the environment variable temp = getenv("VTK_RENDERER"); // Backward compatibility if ( temp ) { if (!strcmp("oglr",temp)) { temp = "OpenGL"; } else if (!strcmp("woglr",temp)) { temp = "Win32OpenGL"; } else if (strcmp("Mesa",temp) && strcmp("OpenGL",temp) && strcmp("Win32OpenGL",temp)) { vtkGenericWarningMacro(<<"VTK_RENDERER set to unsupported type:" << temp); temp = NULL; } } // if the environment variable is set to openGL and the user // does not have opengl but they do have mesa, then use it #ifndef VTK_USE_OGLR #ifdef VTK_USE_MESA if ( temp != NULL ) { if (!strcmp("OpenGL",temp)) { temp = "Mesa"; } } #endif #endif // if nothing is set then work down the list of possible renderers if ( !temp ) { #ifdef VTK_USE_MESA temp = "Mesa"; #endif #ifdef VTK_USE_OGLR temp = "OpenGL"; #endif #ifdef _WIN32 temp = "Win32OpenGL"; #endif } return temp; } vtkObject* vtkImagingFactory::CreateInstance(const char* vtkclassname ) { // first check the object factory vtkObject *ret = vtkObjectFactory::CreateInstance(vtkclassname); if (ret) { return ret; } const char *rl = vtkImagingFactoryGetRenderLibrary(); #ifdef VTK_USE_OGLR #ifdef VTK_USE_NATIVE_IMAGING if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkXTextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkXImageWindow::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkXImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkXPolyDataMapper2D::New(); } #else if (!strcmp("OpenGL",rl)) { if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkXOpenGLTextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkOpenGLImageWindow::New(); } if(strcmp(vtkclassname, "vtkImager") == 0) { return vtkOpenGLImager::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkOpenGLImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkOpenGLPolyDataMapper2D::New(); } } #endif #endif #ifdef _WIN32 #ifdef VTK_USE_NATIVE_IMAGING if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkWin32TextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkWin32ImageWindow::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkWin32ImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkWin32PolyDataMapper2D::New(); } #else if (!strcmp("Win32OpenGL",rl)) { if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkWin32OpenGLTextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkWin32OpenGLImageWindow::New(); } if(strcmp(vtkclassname, "vtkImager") == 0) { return vtkOpenGLImager::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkOpenGLImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkOpenGLPolyDataMapper2D::New(); } } #endif #endif #ifdef VTK_USE_MESA #ifdef VTK_USE_NATIVE_IMAGING if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkXTextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkXImageWindow::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkXImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkXPolyDataMapper2D::New(); } #else if (!strcmp("Mesa",rl)) { if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkXMesaTextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkMesaImageWindow::New(); } if(strcmp(vtkclassname, "vtkImager") == 0) { return vtkMesaImager::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkMesaImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkMesaPolyDataMapper2D::New(); } } #endif #endif vtkGenericWarningMacro("Attempting to create an OpenGL or Mesa based object with a VTK that is not linked/configured with Mesa/OpenGL."); abort(); return 0; } <commit_msg>ERR: Was failing if VTK_USE_NATIVE_IMAGING was set and vtkImager was created.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkImagingFactory.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkObjectFactory.h" #include "vtkImagingFactory.h" #include "vtkToolkits.h" #ifdef VTK_USE_OGLR #include "vtkOpenGLImageMapper.h" #include "vtkOpenGLImager.h" #include "vtkOpenGLImageWindow.h" #include "vtkXOpenGLTextMapper.h" #include "vtkOpenGLPolyDataMapper2D.h" #endif #ifdef VTK_USE_MESA #include "vtkMesaImageMapper.h" #include "vtkMesaImager.h" #include "vtkMesaImageWindow.h" #include "vtkXMesaTextMapper.h" #include "vtkMesaPolyDataMapper2D.h" #endif #ifdef _WIN32 #include "vtkOpenGLImageMapper.h" #include "vtkOpenGLImager.h" #include "vtkWin32OpenGLImageWindow.h" #include "vtkWin32OpenGLTextMapper.h" #include "vtkOpenGLPolyDataMapper2D.h" #include "vtkWin32TextMapper.h" #include "vtkWin32ImageWindow.h" #include "vtkWin32ImageMapper.h" #include "vtkWin32PolyDataMapper2D.h" #else #include "vtkXTextMapper.h" #include "vtkXImageWindow.h" #include "vtkXImageMapper.h" #include "vtkXPolyDataMapper2D.h" #endif const char *vtkImagingFactoryGetRenderLibrary() { const char *temp; // first check the environment variable temp = getenv("VTK_RENDERER"); // Backward compatibility if ( temp ) { if (!strcmp("oglr",temp)) { temp = "OpenGL"; } else if (!strcmp("woglr",temp)) { temp = "Win32OpenGL"; } else if (strcmp("Mesa",temp) && strcmp("OpenGL",temp) && strcmp("Win32OpenGL",temp)) { vtkGenericWarningMacro(<<"VTK_RENDERER set to unsupported type:" << temp); temp = NULL; } } // if the environment variable is set to openGL and the user // does not have opengl but they do have mesa, then use it #ifndef VTK_USE_OGLR #ifdef VTK_USE_MESA if ( temp != NULL ) { if (!strcmp("OpenGL",temp)) { temp = "Mesa"; } } #endif #endif // if nothing is set then work down the list of possible renderers if ( !temp ) { #ifdef VTK_USE_MESA temp = "Mesa"; #endif #ifdef VTK_USE_OGLR temp = "OpenGL"; #endif #ifdef _WIN32 temp = "Win32OpenGL"; #endif } return temp; } vtkObject* vtkImagingFactory::CreateInstance(const char* vtkclassname ) { // first check the object factory vtkObject *ret = vtkObjectFactory::CreateInstance(vtkclassname); if (ret) { return ret; } const char *rl = vtkImagingFactoryGetRenderLibrary(); #ifdef VTK_USE_OGLR #ifdef VTK_USE_NATIVE_IMAGING if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkXTextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkXImageWindow::New(); } if(strcmp(vtkclassname, "vtkImager") == 0) { return NULL; } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkXImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkXPolyDataMapper2D::New(); } #else if (!strcmp("OpenGL",rl)) { if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkXOpenGLTextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkOpenGLImageWindow::New(); } if(strcmp(vtkclassname, "vtkImager") == 0) { return vtkOpenGLImager::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkOpenGLImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkOpenGLPolyDataMapper2D::New(); } } #endif #endif #ifdef _WIN32 #ifdef VTK_USE_NATIVE_IMAGING if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkWin32TextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkWin32ImageWindow::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkWin32ImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkWin32PolyDataMapper2D::New(); } #else if (!strcmp("Win32OpenGL",rl)) { if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkWin32OpenGLTextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkWin32OpenGLImageWindow::New(); } if(strcmp(vtkclassname, "vtkImager") == 0) { return vtkOpenGLImager::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkOpenGLImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkOpenGLPolyDataMapper2D::New(); } } #endif #endif #ifdef VTK_USE_MESA #ifdef VTK_USE_NATIVE_IMAGING if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkXTextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkXImageWindow::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkXImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkXPolyDataMapper2D::New(); } #else if (!strcmp("Mesa",rl)) { if(strcmp(vtkclassname, "vtkTextMapper") == 0) { return vtkXMesaTextMapper::New(); } if(strcmp(vtkclassname, "vtkImageWindow") == 0) { return vtkMesaImageWindow::New(); } if(strcmp(vtkclassname, "vtkImager") == 0) { return vtkMesaImager::New(); } if(strcmp(vtkclassname, "vtkImageMapper") == 0) { return vtkMesaImageMapper::New(); } if(strcmp(vtkclassname, "vtkPolyDataMapper2D") == 0) { return vtkMesaPolyDataMapper2D::New(); } } #endif #endif vtkGenericWarningMacro("Attempting to create an OpenGL or Mesa based object with a VTK that is not linked/configured with Mesa/OpenGL."); abort(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include <iomanip> #include <iostream> #include <sys/time.h> using namespace benchmark; std::map<std::string, BenchFunction> BenchRunner::benchmarks; static double gettimedouble(void) { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_usec * 0.000001 + tv.tv_sec; } BenchRunner::BenchRunner(std::string name, BenchFunction func) { benchmarks.insert(std::make_pair(name, func)); } void BenchRunner::RunAll(double elapsedTimeForOne) { std::cout << "#Benchmark" << "," << "count" << "," << "min" << "," << "max" << "," << "average" << "\n"; for (std::map<std::string,BenchFunction>::iterator it = benchmarks.begin(); it != benchmarks.end(); ++it) { State state(it->first, elapsedTimeForOne); BenchFunction& func = it->second; func(state); } } bool State::KeepRunning() { if (count & countMask) { ++count; return true; } double now; if (count == 0) { beginTime = now = gettimedouble(); } else { now = gettimedouble(); double elapsed = now - lastTime; double elapsedOne = elapsed * countMaskInv; if (elapsedOne < minTime) minTime = elapsedOne; if (elapsedOne > maxTime) maxTime = elapsedOne; if (elapsed*128 < maxElapsed) { // If the execution was much too fast (1/128th of maxElapsed), increase the count mask by 8x and restart timing. // The restart avoids including the overhead of this code in the measurement. countMask = ((countMask<<3)|7) & ((1LL<<60)-1); countMaskInv = 1./(countMask+1); count = 0; minTime = std::numeric_limits<double>::max(); maxTime = std::numeric_limits<double>::min(); return true; } if (elapsed*16 < maxElapsed) { countMask = ((countMask<<1)|1) & ((1LL<<60)-1); countMaskInv = 1./(countMask+1); } } lastTime = now; ++count; if (now - beginTime < maxElapsed) return true; // Keep going --count; // Output results double average = (now-beginTime)/count; std::cout << std::fixed << std::setprecision(15) << name << "," << count << "," << minTime << "," << maxTime << "," << average << "\n"; return false; } <commit_msg>bench: Fix subtle counting issue when rescaling iteration count<commit_after>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include <iomanip> #include <iostream> #include <sys/time.h> using namespace benchmark; std::map<std::string, BenchFunction> BenchRunner::benchmarks; static double gettimedouble(void) { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_usec * 0.000001 + tv.tv_sec; } BenchRunner::BenchRunner(std::string name, BenchFunction func) { benchmarks.insert(std::make_pair(name, func)); } void BenchRunner::RunAll(double elapsedTimeForOne) { std::cout << "#Benchmark" << "," << "count" << "," << "min" << "," << "max" << "," << "average" << "\n"; for (std::map<std::string,BenchFunction>::iterator it = benchmarks.begin(); it != benchmarks.end(); ++it) { State state(it->first, elapsedTimeForOne); BenchFunction& func = it->second; func(state); } } bool State::KeepRunning() { if (count & countMask) { ++count; return true; } double now; if (count == 0) { beginTime = now = gettimedouble(); } else { now = gettimedouble(); double elapsed = now - lastTime; double elapsedOne = elapsed * countMaskInv; if (elapsedOne < minTime) minTime = elapsedOne; if (elapsedOne > maxTime) maxTime = elapsedOne; if (elapsed*128 < maxElapsed) { // If the execution was much too fast (1/128th of maxElapsed), increase the count mask by 8x and restart timing. // The restart avoids including the overhead of this code in the measurement. countMask = ((countMask<<3)|7) & ((1LL<<60)-1); countMaskInv = 1./(countMask+1); count = 0; minTime = std::numeric_limits<double>::max(); maxTime = std::numeric_limits<double>::min(); return true; } if (elapsed*16 < maxElapsed) { uint64_t newCountMask = ((countMask<<1)|1) & ((1LL<<60)-1); if ((count & newCountMask)==0) { countMask = newCountMask; countMaskInv = 1./(countMask+1); } } } lastTime = now; ++count; if (now - beginTime < maxElapsed) return true; // Keep going --count; // Output results double average = (now-beginTime)/count; std::cout << std::fixed << std::setprecision(15) << name << "," << count << "," << minTime << "," << maxTime << "," << average << "\n"; return false; } <|endoftext|>
<commit_before>/** * @file bigfixstats.cpp * @brief Converts BigFix deployment reports into Atlassian Confluence tables */ /* * The MIT License (MIT) * * Copyright (c) 2014 Michael Maraya * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <algorithm> #include <cmath> #include <fstream> // NOLINT #include <map> #include <string> #include <vector> #include "bigfix/bigfixstats.h" ComputerGroup::ComputerGroup() { } ComputerGroup::ComputerGroup(const std::string name) { name_ = name; } uint8_t ComputerGroup::widest() const { uint8_t top {0}; uint8_t name = name_.length(); uint8_t current = bf::format(current_).length(); uint8_t target = bf::format(target_).length(); uint8_t percent = bf::format(this->percent()).length() + 2; std::vector<uint8_t> vector = {name, current, target, percent}; for (auto it : vector) { if (it > top) { top = it; } } return top; } std::string ComputerGroup::name() const { return name_; } std::string ComputerGroup::formatted_name() const { std::string ret; if (name_ == "OS") { ret = name_ + "*" + std::string(this->widest() - name_.length() - 1, ' '); } else { ret = name_ + std::string(this->widest() - name_.length(), ' '); } return ret; } uint32_t ComputerGroup::current() const { return current_; } std::string ComputerGroup::formatted_current() const { std::string output = bf::format(current_); return output + std::string(this->widest() - output.length() + 1, ' '); } uint32_t ComputerGroup::target() const { return target_; } std::string ComputerGroup::formatted_target() const { std::string output = bf::format(target_); return output + std::string(this->widest() - output.length() + 1, ' '); } uint8_t ComputerGroup::percent() const { if (target_ != 0) { return round(static_cast<double>(current_) / target_ * 100); } else { return 0; } } std::string ComputerGroup::formatted_percent() const { std::string output = "*" + std::to_string(this->percent()) + "*"; return output + std::string(this->widest() - output.length() + 1, ' '); } void ComputerGroup::set_name(std::string name) { name_ = name; } void ComputerGroup::set_current(uint32_t current) { current_ = current; } void ComputerGroup::set_target(uint32_t target) { target_ = target; } /** * @details format the supplied number into comma-separated groupings since * there apparently is no portable way of doing this */ std::string bf::format(const uint32_t number) { std::string output = std::to_string(number); if (output.length() > 3) { for (int i = static_cast<int>(output.length() - 3); i > 0; i -= 3) { output.insert(i, ","); } } return output; } /** * @brief Converts BigFix deployment reports into text for updating Atlassian * Confluence tables * @param argc number of command-line arguments * @param argv array of command-line arguments * @retval int returns 0 upon successful program completion, non-zero otherwise */ int main(int argc, const char * argv[]) { // load arguments into vector<string> so we can use std::find std::vector<std::string> args; std::vector<std::string>::iterator it; for (int i = 1; i < argc; ++i) { args.push_back(argv[i]); } // display -h help it = std::find(args.begin(), args.end(), "-h"); if ((argc == 1) || (it != args.end())) { usage(); return 0; } // use -c current file std::string current_file {}; it = std::find(args.begin(), args.end(), "-c"); if (it != args.end()) { if (next(it) != args.end()) { current_file = *next(it); } else { printf("%s: option -c requires an argument\n", bf::kProgramName.c_str()); usage(); return 1; } } // use -t target file std::string target_file {}; it = std::find(args.begin(), args.end(), "-t"); if (it != args.end()) { if (next(it) != args.end()) { target_file = *next(it); } else { printf("%s: option -t requires an argument\n", bf::kProgramName.c_str()); usage(); return 1; } } std::map<std::string, uint32_t> raw; std::vector<ComputerGroup> final; loadTarget(target_file, &final); loadCurrent(current_file, &raw, &final); display(current_file, &raw, &final); } /** * @details Load computer groups and target deployment counts */ void loadTarget(std::string filename, std::vector<ComputerGroup>* final) { std::ifstream fs(filename); if (fs.is_open()) { std::string line {}; while (std::getline(fs, line)) { std::string group {}; uint16_t target {0}; std::size_t delim = line.find(bf::kDelim, 0); // read computer group and target group = line.substr(0, delim); target = std::stoi(line.substr(delim + 1, line.length())); // create new computer group ComputerGroup cg = ComputerGroup(group); cg.set_target(target); final->push_back(cg); } fs.close(); } else { printf("Error: Could not open file %s", filename.c_str()); } } /** * @details Load current deployment counts */ void loadCurrent(std::string filename, std::map<std::string, uint32_t>* raw, std::vector<ComputerGroup>* final) { std::ifstream fs(filename); if (fs.is_open()) { std::string line {}; while (std::getline(fs, line)) { if (line.compare(0, bf::kRecord.length(), bf::kRecord) == 0) { // read records std::size_t start = line.find(bf::kStart, 0), end {0}; while (start != std::string::npos) { std::string group {}; uint32_t count {0}; // read computer group end = line.find(bf::kEnd, start); if (end != std::string::npos) { start += bf::kStart.length(); group = line.substr(start, end - start); } // read computer count start = line.find(bf::kStart, start + bf::kStart.length()); end = line.find(bf::kEnd, start); if (end != std::string::npos) { start += bf::kStart.length(); count = std::stoi(line.substr(start, end - start)); } // populate collection raw->emplace(group, count); // read next computer group start = line.find(bf::kStart, start + bf::kStart.length()); } } } fs.close(); // update computer group collection std::map<std::string, uint32_t>::iterator it; for (auto &cg : *final) { it = raw->find(cg.name()); if (it != raw->end()) { cg.set_current(it->second); // add MBDA current deployment stats to OS if (cg.name() == "OS") { it = raw->find("MBDA"); cg.set_current(cg.current() + it->second); } } } } else { printf("Error: Could not open file %s", filename.c_str()); } } /** * @details Display computer group, current, target and percentage */ void display(std::string filename, std::map<std::string, uint32_t>* raw, std::vector<ComputerGroup>* final) { // extract date from filename size_t begin = filename.length() - bf::kExt.length() - bf::kDate.length(); std::string date = filename.substr(begin, bf::kDate.length()); // store raw results std::string raw_display[2] {"|| Date || ", "| " + date + " | "}; // compute raw totals uint32_t raw_total {0}; for (auto cg : *raw) { raw_total += cg.second; if (cg.first != "CBS" && cg.first != "HCHB") { raw_display[0] += cg.first + " || "; raw_display[1] += bf::format(cg.second) + " | "; } } raw_display[0] += "TOTAL ||"; raw_display[1] += bf::format(raw_total) + " |"; printf("%s\n%s\n\n", raw_display[0].c_str(), raw_display[1].c_str()); // compute final totals uint32_t current_total {0}, target_total {0}; for (auto cg : *final) { current_total += cg.current(); target_total += cg.target(); } ComputerGroup total = ComputerGroup("TOTAL"); total.set_current(current_total); total.set_target(target_total); final->push_back(total); // populate rows std::string header = "|| Nodes || "; std::string current = "| *Current* | "; std::string target = "| *Target* | "; std::string percent = "| *% Comp* | "; // display results for (auto cg : *final) { header += cg.formatted_name() + " || "; current += cg.formatted_current() + " | "; target += cg.formatted_target() + " | "; percent += cg.formatted_percent() + " | "; } printf("%s\n%s\n%s\n%s\n", header.c_str(), current.c_str(), target.c_str(), percent.c_str()); } /** * @details Display program name, version, and usage */ void usage() { printf("%s, version %u.%u\n\n", bf::kProgramName.c_str(), bf::kMajorVersion, bf::kMinorVersion); printf("usage: %s [-h] -t target -c current \n", bf::kProgramName.c_str()); printf("-h display usage\n"); printf("-t filename of the comma-separated computer group targets\n"); printf("-c filename of the current computer group deployment statistics\n\n"); } <commit_msg>tighten up the display output<commit_after>/** * @file bigfixstats.cpp * @brief Converts BigFix deployment reports into Atlassian Confluence tables */ /* * The MIT License (MIT) * * Copyright (c) 2014 Michael Maraya * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <algorithm> #include <cmath> #include <fstream> // NOLINT #include <map> #include <string> #include <vector> #include "bigfix/bigfixstats.h" ComputerGroup::ComputerGroup() { } ComputerGroup::ComputerGroup(const std::string name) { name_ = name; } uint8_t ComputerGroup::widest() const { uint8_t top {0}; uint8_t name = name_.length(); uint8_t current = bf::format(current_).length(); uint8_t target = bf::format(target_).length(); uint8_t percent = bf::format(this->percent()).length() + 2; std::vector<uint8_t> vector = {name, current, target, percent}; for (auto it : vector) { if (it > top) { top = it; } } return top; } std::string ComputerGroup::name() const { return name_; } std::string ComputerGroup::formatted_name() const { std::string ret; if (name_ == "OS") { ret = name_ + "*" + std::string(this->widest() - name_.length() - 1, ' '); } else { ret = name_ + std::string(this->widest() - name_.length(), ' '); } return ret; } uint32_t ComputerGroup::current() const { return current_; } std::string ComputerGroup::formatted_current() const { std::string output = bf::format(current_); return output + std::string(this->widest() - output.length() + 1, ' '); } uint32_t ComputerGroup::target() const { return target_; } std::string ComputerGroup::formatted_target() const { std::string output = bf::format(target_); return output + std::string(this->widest() - output.length() + 1, ' '); } uint8_t ComputerGroup::percent() const { if (target_ != 0) { return round(static_cast<double>(current_) / target_ * 100); } else { return 0; } } std::string ComputerGroup::formatted_percent() const { std::string output = "*" + std::to_string(this->percent()) + "*"; return output + std::string(this->widest() - output.length() + 1, ' '); } void ComputerGroup::set_name(std::string name) { name_ = name; } void ComputerGroup::set_current(uint32_t current) { current_ = current; } void ComputerGroup::set_target(uint32_t target) { target_ = target; } /** * @details format the supplied number into comma-separated groupings since * there apparently is no portable way of doing this */ std::string bf::format(const uint32_t number) { std::string output = std::to_string(number); if (output.length() > 3) { for (int i = static_cast<int>(output.length() - 3); i > 0; i -= 3) { output.insert(i, ","); } } return output; } /** * @brief Converts BigFix deployment reports into text for updating Atlassian * Confluence tables * @param argc number of command-line arguments * @param argv array of command-line arguments * @retval int returns 0 upon successful program completion, non-zero otherwise */ int main(int argc, const char * argv[]) { // load arguments into vector<string> so we can use std::find std::vector<std::string> args; std::vector<std::string>::iterator it; for (int i = 1; i < argc; ++i) { args.push_back(argv[i]); } // display -h help it = std::find(args.begin(), args.end(), "-h"); if ((argc == 1) || (it != args.end())) { usage(); return 0; } // use -c current file std::string current_file {}; it = std::find(args.begin(), args.end(), "-c"); if (it != args.end()) { if (next(it) != args.end()) { current_file = *next(it); } else { printf("%s: option -c requires an argument\n", bf::kProgramName.c_str()); usage(); return 1; } } // use -t target file std::string target_file {}; it = std::find(args.begin(), args.end(), "-t"); if (it != args.end()) { if (next(it) != args.end()) { target_file = *next(it); } else { printf("%s: option -t requires an argument\n", bf::kProgramName.c_str()); usage(); return 1; } } std::map<std::string, uint32_t> raw; std::vector<ComputerGroup> final; loadTarget(target_file, &final); loadCurrent(current_file, &raw, &final); display(current_file, &raw, &final); } /** * @details Load computer groups and target deployment counts */ void loadTarget(std::string filename, std::vector<ComputerGroup>* final) { std::ifstream fs(filename); if (fs.is_open()) { std::string line {}; while (std::getline(fs, line)) { std::string group {}; uint16_t target {0}; std::size_t delim = line.find(bf::kDelim, 0); // read computer group and target group = line.substr(0, delim); target = std::stoi(line.substr(delim + 1, line.length())); // create new computer group ComputerGroup cg = ComputerGroup(group); cg.set_target(target); final->push_back(cg); } fs.close(); } else { printf("Error: Could not open file %s", filename.c_str()); } } /** * @details Load current deployment counts */ void loadCurrent(std::string filename, std::map<std::string, uint32_t>* raw, std::vector<ComputerGroup>* final) { std::ifstream fs(filename); if (fs.is_open()) { std::string line {}; while (std::getline(fs, line)) { if (line.compare(0, bf::kRecord.length(), bf::kRecord) == 0) { // read records std::size_t start = line.find(bf::kStart, 0), end {0}; while (start != std::string::npos) { std::string group {}; uint32_t count {0}; // read computer group end = line.find(bf::kEnd, start); if (end != std::string::npos) { start += bf::kStart.length(); group = line.substr(start, end - start); } // read computer count start = line.find(bf::kStart, start + bf::kStart.length()); end = line.find(bf::kEnd, start); if (end != std::string::npos) { start += bf::kStart.length(); count = std::stoi(line.substr(start, end - start)); } // populate collection raw->emplace(group, count); // read next computer group start = line.find(bf::kStart, start + bf::kStart.length()); } } } fs.close(); // update computer group collection std::map<std::string, uint32_t>::iterator it; for (auto &cg : *final) { it = raw->find(cg.name()); if (it != raw->end()) { cg.set_current(it->second); // add MBDA current deployment stats to OS if (cg.name() == "OS") { it = raw->find("MBDA"); cg.set_current(cg.current() + it->second); } } } } else { printf("Error: Could not open file %s", filename.c_str()); } } /** * @details Display computer group, current, target and percentage */ void display(std::string filename, std::map<std::string, uint32_t>* raw, std::vector<ComputerGroup>* final) { // extract date from filename size_t begin = filename.length() - bf::kExt.length() - bf::kDate.length(); std::string date = filename.substr(begin, bf::kDate.length()); // store raw results std::string raw_display[2] {"|| Date || ", "| " + date + " | "}; // compute raw totals uint32_t raw_total {0}; for (auto cg : *raw) { raw_total += cg.second; if (cg.first != "CBS" && cg.first != "HCHB") { raw_display[0] += cg.first + " || "; raw_display[1] += bf::format(cg.second) + " | "; } } raw_display[0] += "TOTAL ||"; raw_display[1] += bf::format(raw_total) + " |"; printf("%s\n%s\n\n", raw_display[0].c_str(), raw_display[1].c_str()); // compute final totals uint32_t current_total {0}, target_total {0}; for (auto cg : *final) { current_total += cg.current(); target_total += cg.target(); } ComputerGroup total = ComputerGroup("TOTAL"); total.set_current(current_total); total.set_target(target_total); final->push_back(total); // populate rows std::string header = "|| Nodes || "; std::string current = "| *Current* | "; std::string target = "| *Target* | "; std::string percent = "| *%Comp* | "; // display results for (auto cg : *final) { header += cg.formatted_name() + " || "; current += cg.formatted_current() + " | "; target += cg.formatted_target() + " | "; percent += cg.formatted_percent() + " | "; } printf("%s\n%s\n%s\n%s\n", header.c_str(), current.c_str(), target.c_str(), percent.c_str()); } /** * @details Display program name, version, and usage */ void usage() { printf("%s, version %u.%u\n\n", bf::kProgramName.c_str(), bf::kMajorVersion, bf::kMinorVersion); printf("usage: %s [-h] -t target -c current \n", bf::kProgramName.c_str()); printf("-h display usage\n"); printf("-t filename of the comma-separated computer group targets\n"); printf("-c filename of the current computer group deployment statistics\n\n"); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2015-2016 The Bitcoin Unlimited developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparamsbase.h" #include "clientversion.h" #include "rpcclient.h" #include "rpcprotocol.h" #include "util.h" #include "utilstrencodings.h" #include <boost/filesystem/operations.hpp> #include <stdio.h> #include <event2/event.h> #include <event2/http.h> #include <event2/buffer.h> #include <event2/keyvalq_struct.h> #include <univalue.h> using namespace std; static const char DEFAULT_RPCCONNECT[] = "127.0.0.1"; static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900; std::string HelpMessageCli() { string strUsage; strUsage += HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME)); strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory")); AppendParamsHelpMessages(strUsage); strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT)); strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort())); strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start")); strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout during HTTP requests (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT)); return strUsage; } ////////////////////////////////////////////////////////////////////////////// // // Start // // // Exception thrown on connection error. This error is used to determine // when to wait if -rpcwait is given. // class CConnectionFailed : public std::runtime_error { public: explicit inline CConnectionFailed(const std::string& msg) : std::runtime_error(msg) {} }; static bool AppInitRPC(int argc, char* argv[]) { // // Parameters // ParseParameters(argc, argv); if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version")) { std::string strUsage = _("Bitcoin MVF-BU RPC client version") + " " + FormatFullVersion() + "\n"; // MVF-BU client name (MVHF-BU-DES-IDME-1) if (!mapArgs.count("-version")) { strUsage += "\n" + _("Usage:") + "\n" + " bitcoin-cli [options] <command> [params] " + _("Send command to Bitcoin") + "\n" + // BU remove branding " bitcoin-cli [options] help " + _("List commands") + "\n" + " bitcoin-cli [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessageCli(); } fprintf(stdout, "%s", strUsage.c_str()); return false; } if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause) try { SelectBaseParams(ChainNameFromCommandLine()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return false; } if (GetBoolArg("-rpcssl", false)) { fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n"); return false; } return true; } /** Reply structure for request_done to fill in */ struct HTTPReply { int status; std::string body; }; static void http_request_done(struct evhttp_request *req, void *ctx) { HTTPReply *reply = static_cast<HTTPReply*>(ctx); if (req == NULL) { /* If req is NULL, it means an error occurred while connecting, but * I'm not sure how to find out which one. We also don't really care. */ reply->status = 0; return; } reply->status = evhttp_request_get_response_code(req); struct evbuffer *buf = evhttp_request_get_input_buffer(req); if (buf) { size_t size = evbuffer_get_length(buf); const char *data = (const char*)evbuffer_pullup(buf, size); if (data) reply->body = std::string(data, size); evbuffer_drain(buf, size); } } UniValue CallRPC(const string& strMethod, const UniValue& params) { std::string host = GetArg("-rpcconnect", DEFAULT_RPCCONNECT); int port = GetArg("-rpcport", BaseParams().RPCPort()); // Create event base struct event_base *base = event_base_new(); // TODO RAII if (!base) throw runtime_error("cannot create event_base"); // Synchronously look up hostname struct evhttp_connection *evcon = evhttp_connection_base_new(base, NULL, host.c_str(), port); // TODO RAII if (evcon == NULL) throw runtime_error("create connection failed"); evhttp_connection_set_timeout(evcon, GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT)); HTTPReply response; struct evhttp_request *req = evhttp_request_new(http_request_done, (void*)&response); // TODO RAII if (req == NULL) throw runtime_error("create http request failed"); // Get credentials std::string strRPCUserColonPass; if (mapArgs["-rpcpassword"] == "") { // Try fall back to cookie-based authentication if no password is provided if (!GetAuthCookie(&strRPCUserColonPass)) { throw runtime_error(strprintf( _("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"), GetConfigFile().string().c_str())); } } else { strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; } struct evkeyvalq *output_headers = evhttp_request_get_output_headers(req); assert(output_headers); evhttp_add_header(output_headers, "Host", host.c_str()); evhttp_add_header(output_headers, "Connection", "close"); evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str()); // Attach request data std::string strRequest = JSONRPCRequest(strMethod, params, 1); struct evbuffer * output_buffer = evhttp_request_get_output_buffer(req); assert(output_buffer); evbuffer_add(output_buffer, strRequest.data(), strRequest.size()); int r = evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/"); if (r != 0) { evhttp_connection_free(evcon); event_base_free(base); throw CConnectionFailed("send http request failed"); } event_base_dispatch(base); evhttp_connection_free(evcon); event_base_free(base); if (response.status == 0) throw CConnectionFailed("couldn't connect to server"); else if (response.status == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", response.status)); else if (response.body.empty()) throw runtime_error("no response from server"); // Parse reply UniValue valReply(UniValue::VSTR); if (!valReply.read(response.body)) throw runtime_error("couldn't parse reply from server"); const UniValue& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); UniValue params = RPCConvertValues(strMethod, strParams); // Execute and handle connection failures with -rpcwait const bool fWait = GetBoolArg("-rpcwait", false); do { try { const UniValue reply = CallRPC(strMethod, params); // Parse reply const UniValue& result = find_value(reply, "result"); const UniValue& error = find_value(reply, "error"); if (!error.isNull()) { // Error int code = error["code"].get_int(); if (fWait && code == RPC_IN_WARMUP) throw CConnectionFailed("server in warmup"); strPrint = "error: " + error.write(); nRet = abs(code); if (error.isObject()) { UniValue errCode = find_value(error, "code"); UniValue errMsg = find_value(error, "message"); strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n"; if (errMsg.isStr()) strPrint += "error message:\n"+errMsg.get_str(); } } else { // Result if (result.isNull()) strPrint = ""; else if (result.isStr()) strPrint = result.get_str(); else strPrint = result.write(2); } // Connection succeeded, no need to retry. break; } catch (const CConnectionFailed&) { if (fWait) MilliSleep(1000); else throw; } } while (fWait); } catch (const boost::thread_interrupted&) { throw; } catch (const std::exception& e) { strPrint = string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); throw; } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } int main(int argc, char* argv[]) { SetupEnvironment(); if (!SetupNetworking()) { fprintf(stderr, "Error: Initializing networking failed\n"); exit(1); } try { if(!AppInitRPC(argc, argv)) return EXIT_FAILURE; } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInitRPC()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "AppInitRPC()"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; try { ret = CommandLineRPC(argc, argv); } catch (const std::exception& e) { PrintExceptionContinue(&e, "CommandLineRPC()"); } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); } return ret; } <commit_msg>add missing Copyright (c) 2016 The Bitcoin developers<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2015-2016 The Bitcoin Unlimited developers // Copyright (c) 2016 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparamsbase.h" #include "clientversion.h" #include "rpcclient.h" #include "rpcprotocol.h" #include "util.h" #include "utilstrencodings.h" #include <boost/filesystem/operations.hpp> #include <stdio.h> #include <event2/event.h> #include <event2/http.h> #include <event2/buffer.h> #include <event2/keyvalq_struct.h> #include <univalue.h> using namespace std; static const char DEFAULT_RPCCONNECT[] = "127.0.0.1"; static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900; std::string HelpMessageCli() { string strUsage; strUsage += HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME)); strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory")); AppendParamsHelpMessages(strUsage); strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT)); strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort())); strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start")); strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout during HTTP requests (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT)); return strUsage; } ////////////////////////////////////////////////////////////////////////////// // // Start // // // Exception thrown on connection error. This error is used to determine // when to wait if -rpcwait is given. // class CConnectionFailed : public std::runtime_error { public: explicit inline CConnectionFailed(const std::string& msg) : std::runtime_error(msg) {} }; static bool AppInitRPC(int argc, char* argv[]) { // // Parameters // ParseParameters(argc, argv); if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version")) { std::string strUsage = _("Bitcoin MVF-BU RPC client version") + " " + FormatFullVersion() + "\n"; // MVF-BU client name (MVHF-BU-DES-IDME-1) if (!mapArgs.count("-version")) { strUsage += "\n" + _("Usage:") + "\n" + " bitcoin-cli [options] <command> [params] " + _("Send command to Bitcoin") + "\n" + // BU remove branding " bitcoin-cli [options] help " + _("List commands") + "\n" + " bitcoin-cli [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessageCli(); } fprintf(stdout, "%s", strUsage.c_str()); return false; } if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause) try { SelectBaseParams(ChainNameFromCommandLine()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return false; } if (GetBoolArg("-rpcssl", false)) { fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n"); return false; } return true; } /** Reply structure for request_done to fill in */ struct HTTPReply { int status; std::string body; }; static void http_request_done(struct evhttp_request *req, void *ctx) { HTTPReply *reply = static_cast<HTTPReply*>(ctx); if (req == NULL) { /* If req is NULL, it means an error occurred while connecting, but * I'm not sure how to find out which one. We also don't really care. */ reply->status = 0; return; } reply->status = evhttp_request_get_response_code(req); struct evbuffer *buf = evhttp_request_get_input_buffer(req); if (buf) { size_t size = evbuffer_get_length(buf); const char *data = (const char*)evbuffer_pullup(buf, size); if (data) reply->body = std::string(data, size); evbuffer_drain(buf, size); } } UniValue CallRPC(const string& strMethod, const UniValue& params) { std::string host = GetArg("-rpcconnect", DEFAULT_RPCCONNECT); int port = GetArg("-rpcport", BaseParams().RPCPort()); // Create event base struct event_base *base = event_base_new(); // TODO RAII if (!base) throw runtime_error("cannot create event_base"); // Synchronously look up hostname struct evhttp_connection *evcon = evhttp_connection_base_new(base, NULL, host.c_str(), port); // TODO RAII if (evcon == NULL) throw runtime_error("create connection failed"); evhttp_connection_set_timeout(evcon, GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT)); HTTPReply response; struct evhttp_request *req = evhttp_request_new(http_request_done, (void*)&response); // TODO RAII if (req == NULL) throw runtime_error("create http request failed"); // Get credentials std::string strRPCUserColonPass; if (mapArgs["-rpcpassword"] == "") { // Try fall back to cookie-based authentication if no password is provided if (!GetAuthCookie(&strRPCUserColonPass)) { throw runtime_error(strprintf( _("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"), GetConfigFile().string().c_str())); } } else { strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; } struct evkeyvalq *output_headers = evhttp_request_get_output_headers(req); assert(output_headers); evhttp_add_header(output_headers, "Host", host.c_str()); evhttp_add_header(output_headers, "Connection", "close"); evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str()); // Attach request data std::string strRequest = JSONRPCRequest(strMethod, params, 1); struct evbuffer * output_buffer = evhttp_request_get_output_buffer(req); assert(output_buffer); evbuffer_add(output_buffer, strRequest.data(), strRequest.size()); int r = evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/"); if (r != 0) { evhttp_connection_free(evcon); event_base_free(base); throw CConnectionFailed("send http request failed"); } event_base_dispatch(base); evhttp_connection_free(evcon); event_base_free(base); if (response.status == 0) throw CConnectionFailed("couldn't connect to server"); else if (response.status == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", response.status)); else if (response.body.empty()) throw runtime_error("no response from server"); // Parse reply UniValue valReply(UniValue::VSTR); if (!valReply.read(response.body)) throw runtime_error("couldn't parse reply from server"); const UniValue& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); UniValue params = RPCConvertValues(strMethod, strParams); // Execute and handle connection failures with -rpcwait const bool fWait = GetBoolArg("-rpcwait", false); do { try { const UniValue reply = CallRPC(strMethod, params); // Parse reply const UniValue& result = find_value(reply, "result"); const UniValue& error = find_value(reply, "error"); if (!error.isNull()) { // Error int code = error["code"].get_int(); if (fWait && code == RPC_IN_WARMUP) throw CConnectionFailed("server in warmup"); strPrint = "error: " + error.write(); nRet = abs(code); if (error.isObject()) { UniValue errCode = find_value(error, "code"); UniValue errMsg = find_value(error, "message"); strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n"; if (errMsg.isStr()) strPrint += "error message:\n"+errMsg.get_str(); } } else { // Result if (result.isNull()) strPrint = ""; else if (result.isStr()) strPrint = result.get_str(); else strPrint = result.write(2); } // Connection succeeded, no need to retry. break; } catch (const CConnectionFailed&) { if (fWait) MilliSleep(1000); else throw; } } while (fWait); } catch (const boost::thread_interrupted&) { throw; } catch (const std::exception& e) { strPrint = string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); throw; } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } int main(int argc, char* argv[]) { SetupEnvironment(); if (!SetupNetworking()) { fprintf(stderr, "Error: Initializing networking failed\n"); exit(1); } try { if(!AppInitRPC(argc, argv)) return EXIT_FAILURE; } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInitRPC()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "AppInitRPC()"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; try { ret = CommandLineRPC(argc, argv); } catch (const std::exception& e) { PrintExceptionContinue(&e, "CommandLineRPC()"); } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); } return ret; } <|endoftext|>
<commit_before>/** * The MIT License * * Copyright (C) 2017 Kiyofumi Kondoh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "stdafx.h" #include "test_cef_offscreen.h" extern int main_win(HINSTANCE hInstance); extern int main_win_term(); #include "include/base/cef_lock.h" #define MAX_LOADSTRING 100 HWND s_hWnd = NULL; HDC s_memDC = NULL; HBITMAP s_memBitmap = NULL; void* s_memBitmapPixel = NULL; base::Lock s_memBitmapPixelLock; HBITMAP s_memBitmapPrev = NULL; HINSTANCE hInst; TCHAR szTitle[MAX_LOADSTRING]; TCHAR szWindowClass[MAX_LOADSTRING]; ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); { const int nRet = main_win(hInstance); if ( 0 <= nRet ) { return nRet; } } MSG msg; HACCEL hAccelTable; LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_TEST_CEF_OFFSCREEN, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TEST_CEF_OFFSCREEN)); while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } { main_win_term(); } return (int) msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TEST_CEF_OFFSCREEN)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_TEST_CEF_OFFSCREEN); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; DWORD dwStyle = WS_OVERLAPPEDWINDOW; dwStyle ^= WS_MINIMIZEBOX; dwStyle ^= WS_MAXIMIZEBOX; dwStyle ^= WS_THICKFRAME; DWORD dwExStyle = 0; int width = CW_USEDEFAULT; int height = CW_USEDEFAULT; { RECT rect; rect.left = 0; rect.top = 0; rect.bottom = 720; rect.right = 1280; ::AdjustWindowRectEx(&rect, dwStyle, TRUE, dwExStyle); width = rect.right - rect.left; height = rect.bottom - rect.top; } hWnd = CreateWindow(szWindowClass, szTitle, dwStyle, CW_USEDEFAULT, 0, width, height, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); s_hWnd = hWnd; return TRUE; } #include "../test_cef_app/cef_client.h" extern CefRefPtr<Client> s_client; #include <windowsx.h> LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_CREATE: { hdc = GetDC( hWnd ); s_memDC = CreateCompatibleDC( hdc ); { BITMAPINFO bi; ZeroMemory( &bi, sizeof(bi) ); bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biBitCount = 32; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = 1280; bi.bmiHeader.biHeight = -720; { base::AutoLock lock_scope(s_memBitmapPixelLock); s_memBitmap = CreateDIBSection( NULL, &bi, DIB_RGB_COLORS, &s_memBitmapPixel, NULL, 0 ); if ( NULL == s_memBitmap ) { ReleaseDC( hWnd, hdc ); return -1; } { DWORD* p = reinterpret_cast<DWORD*>(s_memBitmapPixel); for ( int x = 0; x < 1280; ++x ) { for ( int y = 0; y < 720; ++y ) { // A,R,G,B //p[y*1280 + x] = 0xffffffffUL; p[y*1280 + x] = 0x0000ff00UL; } } } } } s_memBitmapPrev = (HBITMAP)SelectObject( s_memDC, s_memBitmap ); ReleaseDC( hWnd, hdc ); } break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); BitBlt( hdc, 0, 0, 1280, 720, s_memDC, 0, 0, SRCCOPY ); EndPaint(hWnd, &ps); break; case WM_DESTROY: { if ( NULL != s_memDC ) { if ( NULL != s_memBitmap ) { base::AutoLock lock_scope(s_memBitmapPixelLock); SelectObject( s_memDC, s_memBitmapPrev ); s_memBitmapPrev = NULL; DeleteObject( s_memBitmap ); s_memBitmap = NULL; s_memBitmapPixel = NULL; } DeleteDC( s_memDC ); s_memDC = NULL; } } PostQuitMessage(0); break; case WM_LBUTTONDOWN: case WM_LBUTTONUP: { CefRefPtr<CefBrowser> browser = s_client->getBrowser(); if ( NULL != browser ) { CefRefPtr<CefBrowserHost> host = browser->GetHost(); if ( NULL != host ) { CefMouseEvent event; event.x = GET_X_LPARAM(lParam); event.y = GET_Y_LPARAM(lParam); event.modifiers = 0; const bool btnUp = (WM_LBUTTONUP == message)?(true):(false); host->SendMouseClickEvent( event, MBT_LEFT, btnUp, 1 ); } } } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } <commit_msg>add mouse move<commit_after>/** * The MIT License * * Copyright (C) 2017 Kiyofumi Kondoh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "stdafx.h" #include "test_cef_offscreen.h" extern int main_win(HINSTANCE hInstance); extern int main_win_term(); #include "include/base/cef_lock.h" #define MAX_LOADSTRING 100 HWND s_hWnd = NULL; HDC s_memDC = NULL; HBITMAP s_memBitmap = NULL; void* s_memBitmapPixel = NULL; base::Lock s_memBitmapPixelLock; HBITMAP s_memBitmapPrev = NULL; HINSTANCE hInst; TCHAR szTitle[MAX_LOADSTRING]; TCHAR szWindowClass[MAX_LOADSTRING]; ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); { const int nRet = main_win(hInstance); if ( 0 <= nRet ) { return nRet; } } MSG msg; HACCEL hAccelTable; LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_TEST_CEF_OFFSCREEN, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TEST_CEF_OFFSCREEN)); while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } { main_win_term(); } return (int) msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TEST_CEF_OFFSCREEN)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_TEST_CEF_OFFSCREEN); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; DWORD dwStyle = WS_OVERLAPPEDWINDOW; dwStyle ^= WS_MINIMIZEBOX; dwStyle ^= WS_MAXIMIZEBOX; dwStyle ^= WS_THICKFRAME; DWORD dwExStyle = 0; int width = CW_USEDEFAULT; int height = CW_USEDEFAULT; { RECT rect; rect.left = 0; rect.top = 0; rect.bottom = 720; rect.right = 1280; ::AdjustWindowRectEx(&rect, dwStyle, TRUE, dwExStyle); width = rect.right - rect.left; height = rect.bottom - rect.top; } hWnd = CreateWindow(szWindowClass, szTitle, dwStyle, CW_USEDEFAULT, 0, width, height, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); s_hWnd = hWnd; return TRUE; } #include "../test_cef_app/cef_client.h" extern CefRefPtr<Client> s_client; #include <windowsx.h> LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_CREATE: { hdc = GetDC( hWnd ); s_memDC = CreateCompatibleDC( hdc ); { BITMAPINFO bi; ZeroMemory( &bi, sizeof(bi) ); bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biBitCount = 32; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = 1280; bi.bmiHeader.biHeight = -720; { base::AutoLock lock_scope(s_memBitmapPixelLock); s_memBitmap = CreateDIBSection( NULL, &bi, DIB_RGB_COLORS, &s_memBitmapPixel, NULL, 0 ); if ( NULL == s_memBitmap ) { ReleaseDC( hWnd, hdc ); return -1; } { DWORD* p = reinterpret_cast<DWORD*>(s_memBitmapPixel); for ( int x = 0; x < 1280; ++x ) { for ( int y = 0; y < 720; ++y ) { // A,R,G,B //p[y*1280 + x] = 0xffffffffUL; p[y*1280 + x] = 0x0000ff00UL; } } } } } s_memBitmapPrev = (HBITMAP)SelectObject( s_memDC, s_memBitmap ); ReleaseDC( hWnd, hdc ); } break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); BitBlt( hdc, 0, 0, 1280, 720, s_memDC, 0, 0, SRCCOPY ); EndPaint(hWnd, &ps); break; case WM_DESTROY: { if ( NULL != s_memDC ) { if ( NULL != s_memBitmap ) { base::AutoLock lock_scope(s_memBitmapPixelLock); SelectObject( s_memDC, s_memBitmapPrev ); s_memBitmapPrev = NULL; DeleteObject( s_memBitmap ); s_memBitmap = NULL; s_memBitmapPixel = NULL; } DeleteDC( s_memDC ); s_memDC = NULL; } } PostQuitMessage(0); break; case WM_LBUTTONDOWN: case WM_LBUTTONUP: { CefRefPtr<CefBrowser> browser = s_client->getBrowser(); if ( NULL != browser ) { CefRefPtr<CefBrowserHost> host = browser->GetHost(); if ( NULL != host ) { CefMouseEvent event; event.x = GET_X_LPARAM(lParam); event.y = GET_Y_LPARAM(lParam); event.modifiers = 0; const bool btnUp = (WM_LBUTTONUP == message)?(true):(false); host->SendMouseClickEvent( event, MBT_LEFT, btnUp, 1 ); } } } break; case WM_MOUSEMOVE: { CefRefPtr<CefBrowser> browser = s_client->getBrowser(); if ( NULL != browser ) { CefRefPtr<CefBrowserHost> host = browser->GetHost(); if ( NULL != host ) { CefMouseEvent event; event.x = GET_X_LPARAM(lParam); event.y = GET_Y_LPARAM(lParam); event.modifiers = 0; const bool mouseLeave = false; host->SendMouseMoveEvent( event, mouseLeave ); } } } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } <|endoftext|>
<commit_before>// =============================== // PC-BSD SysAdm Bridge Server // Available under the 3-clause BSD License // Written by: Ken Moore <ken@pcbsd.org> May 2016 // ================================= #include "globals.h" #include <unistd.h> #include <sys/types.h> #include "BridgeServer.h" #define DEBUG 0 //Create any global classes/settings QSettings *CONFIG = new QSettings(SETTINGSFILE, QSettings::IniFormat); AuthorizationManager *AUTHSYSTEM = new AuthorizationManager(); //Set the defail values for the global config variables /*int BlackList_BlockMinutes = 60; int BlackList_AuthFailsToBlock = 5; int BlackList_AuthFailResetMinutes = 10;*/ //Create the default logfile /*QFile logfile; void MessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg){ QString txt; switch(type){ case QtDebugMsg: txt = msg; break; case QtWarningMsg: txt = QString("WARNING: %1").arg(msg); txt += "\n Context: "+QString(context.file)+" Line: "+QString(context.line)+" Function: "+QString(context.function); break; case QtCriticalMsg: txt = QString("CRITICAL: %1").arg(msg); txt += "\n Context: "+QString(context.file)+" Line: "+QString(context.line)+" Function: "+QString(context.function); break; case QtFatalMsg: txt = QString("FATAL: %1").arg(msg); txt += "\n Context: "+QString(context.file)+" Line: "+QString(context.line)+" Function: "+QString(context.function); break; } QTextStream out(&logfile); out << txt; if(!txt.endsWith("\n")){ out << "\n"; } } */ int main( int argc, char ** argv ) { //Evaluate input arguments quint16 port = 12149; //port number bool settingchange = false; for(int i=1; i<argc; i++){ if(settingchange){ QString info = QString(argv[i]); if(!info.contains("=")){ continue; } //invalid format QString var = info.section("=",0,0); QString val = info.section("=",1,-1); qDebug() << "Changing bridge setting:" << info; if(var=="blacklist/block_minutes"){ CONFIG->setValue("blacklist_settings/block_minutes",val.toInt()); } else if(var=="blacklist/fails_to_block"){ CONFIG->setValue("blacklist_settings/fails_to_block",val.toInt()); } //else if(var=="blacklist_settings/block_minutes"){ CONFIG->setValue("blacklist_settings/block_minutes",val.toInt()); } } else if( (QString(argv[i])=="-port" || QString(argv[i])=="-p") && (i+1<argc)){ i++; port = QString(argv[i]).toUInt(); } else if( QString(argv[i])=="-set" && i+1<argc){ settingchange = true; } } if(settingchange){ return 0; } QCoreApplication a(argc, argv); //Setup the log file /*logfile.setFileName("/var/log/sysadm-bridge.log"); if(DEBUG){ qDebug() << "Log File:" << logfile.fileName(); } if(QFile::exists(logfile.fileName()+".old")){ QFile::remove(logfile.fileName()+".old"); } if(logfile.exists()){ QFile::rename(logfile.fileName(), logfile.fileName()+".old"); } //Make sure the parent directory exists if(!QFile::exists("/var/log")){ QDir dir; dir.mkpath("/var/log"); } logfile.open(QIODevice::WriteOnly | QIODevice::Append); qInstallMessageHandler(MessageOutput); */ //Create the server qDebug() << "Starting the PC-BSD sysadm bridge...."; BridgeServer server; //Start the servers int ret = 1; //error return value if(!server.startServer(port)){ qDebug() << "Could not start bridge server on port:" << port; } else{ //Now start the main event loop qDebug() << "Bridge Started:" << QDateTime::currentDateTime().toString(Qt::ISODate); ret = a.exec(); qDebug() << "Bridge Stopped:" << QDateTime::currentDateTime().toString(Qt::ISODate); } //Cleanup any globals delete CONFIG; //logfile.close(); //Return return ret; } <commit_msg>Add a couple CLI options to the sysadm-bridge: 1) "-import_ssl_file <filepath>": This will import any .crt or .key file such that the designated public key may be used for authentication with this bridge. 2) "-import_ssl_pubkey <pubkey>": This will import the designated pubkey such that it may be used for authentication with this bridge.<commit_after>// =============================== // PC-BSD SysAdm Bridge Server // Available under the 3-clause BSD License // Written by: Ken Moore <ken@pcbsd.org> May 2016 // ================================= #include "globals.h" #include <unistd.h> #include <sys/types.h> #include "BridgeServer.h" #define DEBUG 0 #define USELOG 1 //turn this to "0" for dumping all output to the CLI (for debugging) //Create any global classes/settings QSettings *CONFIG = new QSettings(SETTINGSFILE, QSettings::IniFormat); AuthorizationManager *AUTHSYSTEM = new AuthorizationManager(); //Set the defail values for the global config variables /*int BlackList_BlockMinutes = 60; int BlackList_AuthFailsToBlock = 5; int BlackList_AuthFailResetMinutes = 10;*/ //Create the default logfile QFile logfile; void MessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg){ QString txt; switch(type){ case QtDebugMsg: txt = msg; break; case QtWarningMsg: txt = QString("WARNING: %1").arg(msg); txt += "\n Context: "+QString(context.file)+" Line: "+QString(context.line)+" Function: "+QString(context.function); break; case QtCriticalMsg: txt = QString("CRITICAL: %1").arg(msg); txt += "\n Context: "+QString(context.file)+" Line: "+QString(context.line)+" Function: "+QString(context.function); break; case QtFatalMsg: txt = QString("FATAL: %1").arg(msg); txt += "\n Context: "+QString(context.file)+" Line: "+QString(context.line)+" Function: "+QString(context.function); break; } QTextStream out(&logfile); out << txt; if(!txt.endsWith("\n")){ out << "\n"; } } int main( int argc, char ** argv ) { //Evaluate input arguments quint16 port = 12149; //port number bool settingchange = false; for(int i=1; i<argc; i++){ if(settingchange){ QString info = QString(argv[i]); if(!info.contains("=")){ continue; } //invalid format QString var = info.section("=",0,0); QString val = info.section("=",1,-1); qDebug() << "Changing bridge setting:" << info; if(var=="blacklist/block_minutes"){ CONFIG->setValue("blacklist_settings/block_minutes",val.toInt()); } else if(var=="blacklist/fails_to_block"){ CONFIG->setValue("blacklist_settings/fails_to_block",val.toInt()); } //else if(var=="blacklist_settings/block_minutes"){ CONFIG->setValue("blacklist_settings/block_minutes",val.toInt()); } } else if( (QString(argv[i])=="-port" || QString(argv[i])=="-p") && (i+1<argc)){ i++; port = QString(argv[i]).toUInt(); } else if( QString(argv[i])=="-set" && i+1<argc){ settingchange = true; } else if( QString(argv[i])=="-import_ssl_file" && i+1<argc){ i++; QFile file(argv[i]); if(!file.open(QIODevice::ReadOnly)){ qDebug() << "Could not open file:" << file.fileName(); } else{ QString enc_key; if(file.fileName().endsWith(".crt")){ QSslCertificate cert(&file); enc_key = QString(cert.publicKey().toPem().toBase64()); } else if(file.fileName().endsWith(".key")){ QSslKey key(&file); enc_key = QString(key.toPem().toBase64()); } if(enc_key.isEmpty()){ qDebug() << "Could not read key (need .crt or .key file)"; } else{ qDebug() << "Registered Key:" << enc_key << "(base64)"; CONFIG->setValue("RegisteredCerts/cli-import/"+enc_key, "Date Registered: "+QDateTime::currentDateTime().toString(Qt::ISODate) ); } } settingchange=true; }else if( QString(argv[i])=="-import_ssl_pubkey" && i+1<argc){ i++; QString enc_key = QByteArray(argv[i]).toBase64(); CONFIG->setValue("RegisteredCerts/cli-import/"+enc_key, "Date Registered: "+QDateTime::currentDateTime().toString(Qt::ISODate) ); qDebug() << "Registered Key:" << enc_key << "(base64)"; settingchange=true; } } //end loop over argc if(settingchange){ return 0; } QCoreApplication a(argc, argv); //Setup the log file if(USELOG){ logfile.setFileName("/var/log/sysadm-bridge.log"); if(DEBUG){ qDebug() << "Log File:" << logfile.fileName(); } if(QFile::exists(logfile.fileName()+".old")){ QFile::remove(logfile.fileName()+".old"); } if(logfile.exists()){ QFile::rename(logfile.fileName(), logfile.fileName()+".old"); } //Make sure the parent directory exists if(!QFile::exists("/var/log")){ QDir dir; dir.mkpath("/var/log"); } logfile.open(QIODevice::WriteOnly | QIODevice::Append); qInstallMessageHandler(MessageOutput); } //Create the server qDebug() << "Starting the PC-BSD sysadm bridge...."; BridgeServer server; //Start the servers int ret = 1; //error return value if(!server.startServer(port)){ qDebug() << "Could not start bridge server on port:" << port; } else{ //Now start the main event loop qDebug() << "Bridge Started:" << QDateTime::currentDateTime().toString(Qt::ISODate); ret = a.exec(); qDebug() << "Bridge Stopped:" << QDateTime::currentDateTime().toString(Qt::ISODate); } //Cleanup any globals delete CONFIG; if(USELOG){ logfile.close(); } //Return return ret; } <|endoftext|>
<commit_before>/* * jsonRpcWebsockets.cpp * * Created on: 9.6.2015 * Author: ondra */ #include "jsonRpcWebsockets.h" #include "../httpserver/abstractWebSockets.tcc" #include <lightspeed/base/interface.tcc> #include "lightspeed/base/actions/promise.tcc" #include "lightspeed/base/debug/dbglog.h" #include "lightspeed/base/exceptions/httpStatusException.h" #include "lightspeed/base/containers/map.tcc" namespace jsonsrv { class JsonRpcWebsocketsConnection::HttpRequestWrapper: public BredyHttpSrv::IHttpRequest { public: HttpRequestWrapper(BredyHttpSrv::IHttpRequest *r, JsonRpcWebsocketsConnection *owner):r(r),owner(owner) {} BredyHttpSrv::IHttpRequest * const r; JsonRpcWebsocketsConnection * const owner; protected: virtual ConstStrA getMethod() const {return "WS";} virtual ConstStrA getPath() const {return r->getPath();} virtual ConstStrA getProtocol() const {return r->getProtocol();} virtual HeaderValue getHeaderField(ConstStrA field) const {return r->getHeaderField(field);} virtual HeaderValue getHeaderField(HeaderField field) const {return r->getHeaderField(field);} virtual bool enumHeader(HdrEnumFn fn) const {return r->enumHeader(fn);} virtual void sendHeaders() {} virtual void header(ConstStrA , ConstStrA ) {} virtual void header(HeaderField , ConstStrA ) {} virtual void status(natural , ConstStrA = ConstStrA()) {} virtual void errorPage(natural , ConstStrA = ConstStrA(), ConstStrA = ConstStrA()) {} virtual void redirect(ConstStrA , int = 0) {} virtual ConstStrA getBaseUrl() const {return r->getBaseUrl();} virtual void useHTTP11(bool ) {} virtual bool isField(ConstStrA text, HeaderField fld) const {return r->isField(text,fld);} virtual natural read(void *, natural ) {return 0;} virtual natural write(const void *, natural ) {return 0;} virtual natural peek(void *, natural ) const {return 0;} virtual bool canRead() const {return false;} virtual bool canWrite() const {return false;} virtual void flush() {} virtual natural dataReady() const {return 0;} virtual void finish() {} virtual bool headersSent() const {return true;} virtual natural callHandler(ConstStrA , IHttpHandler ** = 0) {return 0;} virtual natural forwardRequest(ConstStrA, IHttpHandler ** = 0) { return 0; } virtual bool keepAlive() const {return true;} virtual PNetworkStream getConnection() {return nil;} virtual void setRequestContext(IHttpHandlerContext *context) { rctx = context; } virtual void setConnectionContext(IHttpHandlerContext *context) { owner->jsonrpc_context = context; } virtual IHttpHandlerContext *getRequestContext() const { return rctx; } virtual IHttpHandlerContext *getConnectionContext() const { return owner->jsonrpc_context; } virtual natural getPostBodySize() const { return 0; } virtual void beginIO() {r->beginIO();} virtual void endIO() {r->endIO();} virtual void setMaxPostSize(natural ) {} virtual void attachThread(natural ) {} virtual void closeOutput() {} virtual void setRequestName(ConstStrA ) {} virtual void recordRequestDuration(natural x) {r->recordRequestDuration(x);} virtual void *proxyInterface(IInterfaceRequest &p) { void *x = IInterface::proxyInterface(p); if (!x) x = r->proxyInterface(p); return x; } virtual const void *proxyInterface(const IInterfaceRequest &p) const { const void *x = IInterface::proxyInterface(p); if (!x) x = r->proxyInterface(p); return x; } virtual StringA getAbsoluteUrl() const { return r->getAbsoluteUrl(); } virtual StringA getAbsoluteUrl(ConstStrA relpath) const { return r->getAbsoluteUrl(relpath); } AllocPointer<IHttpHandlerContext> rctx; }; JsonRpcWebsocketsConnection::JsonRpcWebsocketsConnection(IHttpRequest &request, IJsonRpc& handler, StringA openMethod) :WebSocketConnection(request),handler(handler),nextPromiseId(0),http(request),openMethod(openMethod.getMT()) { logobject = handler.getIfcPtr<IJsonRpcLogObject>(); } void JsonRpcWebsocketsConnection::sendNotification(ConstStrA name, JSON::PNode arguments) { Synchronized<FastLock> _(lock); JSON::PNode req = json("method",name) ("params",arguments) ("id",nil); ConstStrA msg = json.factory->toString(*req); this->sendTextMessage(msg,true); } Future<JSON::PNode> JsonRpcWebsocketsConnection::callMethod(ConstStrA name, JSON::PNode arguments) { Synchronized<FastLock> _(lock); natural promiseId = nextPromiseId++; JSON::PNode req = json("method",name) ("params",arguments) ("id",promiseId); ConstStrA msg = json.factory->toString(*req); this->sendTextMessage(msg,true); Future<JSON::PNode> promise; waitingPromises.insert(promiseId,promise.getPromise()); return promise; } JsonRpcWebsocketsConnection* JsonRpcWebsocketsConnection::getConnection(IHttpRequest& request) { HttpRequestWrapper *rq = request.getIfcPtr<HttpRequestWrapper>(); if (rq == 0) return 0; return rq->owner; } void JsonRpcWebsocketsConnection::setContext(IHttpHandlerContext* context) { this->context = context; } IHttpHandlerContext* JsonRpcWebsocketsConnection::getContext() const { return context; } void JsonRpcWebsocketsConnection::onTextMessage(ConstStrA msg) { Synchronized<FastLock> _(lock); LS_LOGOBJ(lg); JSON::PNode req = json.factory->fromString(msg); if (req->getPtr("result")) { natural id = req["id"]->getUInt(); const Promise<JSON::PNode> *pres = waitingPromises.find(id); if (pres == 0) return; Promise<JSON::PNode> p = *pres; waitingPromises.erase(id); if (req["error"]->isNull()) p.resolve(req["result"]); else p.reject(RpcError(THISLOCATION,req["error"])); } else { TimeStamp beginTime = TimeStamp::now(); ConstStrA method = req["method"]->getStringUtf8(); JSON::PNode params = req["params"]; JSON::PNode id = req["id"]; JSON::PNode context = req->getPtr("context"); IJsonRpc::CallResult callRes; HttpRequestWrapper httpwrp(&http,this); try { SyncReleased<FastLock> _(lock); callRes = handler.callMethod(&httpwrp,method,params,context,id); if (logobject) logobject->logMethod(http,method,params,context,callRes.logOutput); } catch (std::exception &e) { callRes.error = json.factory->newValue(e.what()); callRes.id = id; callRes.logOutput = callRes.error; } if (!id->isNull()) { JSON::Builder::Object response = json("result",callRes.result) ("error",callRes.error) ("id", callRes.id); if (callRes.newContext != nil) { response("context",callRes.newContext); } ConstStrA msg = json.factory->toString(*response); sendTextMessage(msg,true); } TimeStamp endTime = TimeStamp::now(); natural ms = (endTime - beginTime).getMilis(); lg.progress("%1 - POST %2 WSRPC/1.0 (%3 ms)") << http.getIfc<IHttpPeerInfo>().getPeerRealAddr() << method << ms; http.recordRequestDuration(ms); } } JsonRpcWebsockets::JsonRpcWebsockets(IJsonRpc& handler,StringA openMethod):handler(handler),openMethod(openMethod.getMT()) { } WebSocketConnection* JsonRpcWebsockets::onNewConnection( IRuntimeAlloc& alloc, IHttpRequest& request, ConstStrA ) { IHttpRequest::HeaderValue origin = request.getHeaderField(IHttpRequest::fldOrigin); bool allow = true; if (origin.defined) { Optional<bool> allowed = handler.isAllowedOrigin(origin); if (allowed == null) { ConstStrA corig = origin; if (corig.head(7) == ConstStrA("http://")) corig = corig.offset(7); else if (corig.head(8) == ConstStrA("https://")) corig = corig.offset(8); ConstStrA host = request.getHeaderField(IHttpRequest::fldHost); if (host.tail(corig.length()) != corig) allow = false; } else { allow = allowed; } } if (allow) return new(alloc) JsonRpcWebsocketsConnection(request,handler,openMethod); else throw HttpStatusException(THISLOCATION,request.getAbsoluteUrl(),403,"Forbidden"); } void JsonRpcWebsocketsConnection::onCloseOutput(natural ) { Synchronized<FastLock> _(lock); context = nil; } JsonRpcWebsocketsConnection::~JsonRpcWebsocketsConnection() { Synchronized<FastLock> _(lock); context = nil; } void JsonRpcWebsocketsConnection::onConnect() { if (!openMethod.empty()) { IJsonRpc::CallResult callRes; { JSON::PNode nullNode = json.factory->newNullNode(); JSON::PNode emptyArr = json.array(); SyncReleased<FastLock> _(lock); callRes = handler.callMethod(&http,openMethod,emptyArr,nullNode,nullNode); if (logobject) logobject->logMethod(http,openMethod,emptyArr,nullNode,callRes.logOutput); if (callRes.error != nil && !callRes.error->isNull()) { this->closeConnection(closeAbnormal); } } } } void JsonRpcWebsocketsConnection::sendNotification(const PreparedNtf& ntf) { this->sendTextMessage(ntf,true); } JsonRpcWebsocketsConnection::PreparedNtf JsonRpcWebsocketsConnection::prepareNotification( LightSpeed::ConstStrA name, LightSpeed::JSON::PNode arguments) { Synchronized<FastLock> _(lock); JSON::PNode req = json("method",name) ("params",arguments) ("id",nil); return IRpcNotify::prepare(json.factory->toString(*req)); } IRpcNotify *IRpcNotify::fromRequest(RpcRequest *r) { JsonRpcWebsocketsConnection *conn = JsonRpcWebsocketsConnection::getConnection(*r->httpRequest); return conn; } } /* namespace jsonsrv */ <commit_msg>fix uncaught exception closes websocket connection<commit_after>/* * jsonRpcWebsockets.cpp * * Created on: 9.6.2015 * Author: ondra */ #include "jsonRpcWebsockets.h" #include "../httpserver/abstractWebSockets.tcc" #include <lightspeed/base/interface.tcc> #include "lightspeed/base/actions/promise.tcc" #include "lightspeed/base/debug/dbglog.h" #include "lightspeed/base/exceptions/httpStatusException.h" #include "lightspeed/base/containers/map.tcc" namespace jsonsrv { class JsonRpcWebsocketsConnection::HttpRequestWrapper: public BredyHttpSrv::IHttpRequest { public: HttpRequestWrapper(BredyHttpSrv::IHttpRequest *r, JsonRpcWebsocketsConnection *owner):r(r),owner(owner) {} BredyHttpSrv::IHttpRequest * const r; JsonRpcWebsocketsConnection * const owner; protected: virtual ConstStrA getMethod() const {return "WS";} virtual ConstStrA getPath() const {return r->getPath();} virtual ConstStrA getProtocol() const {return r->getProtocol();} virtual HeaderValue getHeaderField(ConstStrA field) const {return r->getHeaderField(field);} virtual HeaderValue getHeaderField(HeaderField field) const {return r->getHeaderField(field);} virtual bool enumHeader(HdrEnumFn fn) const {return r->enumHeader(fn);} virtual void sendHeaders() {} virtual void header(ConstStrA , ConstStrA ) {} virtual void header(HeaderField , ConstStrA ) {} virtual void status(natural , ConstStrA = ConstStrA()) {} virtual void errorPage(natural , ConstStrA = ConstStrA(), ConstStrA = ConstStrA()) {} virtual void redirect(ConstStrA , int = 0) {} virtual ConstStrA getBaseUrl() const {return r->getBaseUrl();} virtual void useHTTP11(bool ) {} virtual bool isField(ConstStrA text, HeaderField fld) const {return r->isField(text,fld);} virtual natural read(void *, natural ) {return 0;} virtual natural write(const void *, natural ) {return 0;} virtual natural peek(void *, natural ) const {return 0;} virtual bool canRead() const {return false;} virtual bool canWrite() const {return false;} virtual void flush() {} virtual natural dataReady() const {return 0;} virtual void finish() {} virtual bool headersSent() const {return true;} virtual natural callHandler(ConstStrA , IHttpHandler ** = 0) {return 0;} virtual natural forwardRequest(ConstStrA, IHttpHandler ** = 0) { return 0; } virtual bool keepAlive() const {return true;} virtual PNetworkStream getConnection() {return nil;} virtual void setRequestContext(IHttpHandlerContext *context) { rctx = context; } virtual void setConnectionContext(IHttpHandlerContext *context) { owner->jsonrpc_context = context; } virtual IHttpHandlerContext *getRequestContext() const { return rctx; } virtual IHttpHandlerContext *getConnectionContext() const { return owner->jsonrpc_context; } virtual natural getPostBodySize() const { return 0; } virtual void beginIO() {r->beginIO();} virtual void endIO() {r->endIO();} virtual void setMaxPostSize(natural ) {} virtual void attachThread(natural ) {} virtual void closeOutput() {} virtual void setRequestName(ConstStrA ) {} virtual void recordRequestDuration(natural x) {r->recordRequestDuration(x);} virtual void *proxyInterface(IInterfaceRequest &p) { void *x = IInterface::proxyInterface(p); if (!x) x = r->proxyInterface(p); return x; } virtual const void *proxyInterface(const IInterfaceRequest &p) const { const void *x = IInterface::proxyInterface(p); if (!x) x = r->proxyInterface(p); return x; } virtual StringA getAbsoluteUrl() const { return r->getAbsoluteUrl(); } virtual StringA getAbsoluteUrl(ConstStrA relpath) const { return r->getAbsoluteUrl(relpath); } AllocPointer<IHttpHandlerContext> rctx; }; JsonRpcWebsocketsConnection::JsonRpcWebsocketsConnection(IHttpRequest &request, IJsonRpc& handler, StringA openMethod) :WebSocketConnection(request),handler(handler),nextPromiseId(0),http(request),openMethod(openMethod.getMT()) { logobject = handler.getIfcPtr<IJsonRpcLogObject>(); } void JsonRpcWebsocketsConnection::sendNotification(ConstStrA name, JSON::PNode arguments) { Synchronized<FastLock> _(lock); JSON::PNode req = json("method",name) ("params",arguments) ("id",nil); ConstStrA msg = json.factory->toString(*req); this->sendTextMessage(msg,true); } Future<JSON::PNode> JsonRpcWebsocketsConnection::callMethod(ConstStrA name, JSON::PNode arguments) { Synchronized<FastLock> _(lock); natural promiseId = nextPromiseId++; JSON::PNode req = json("method",name) ("params",arguments) ("id",promiseId); ConstStrA msg = json.factory->toString(*req); this->sendTextMessage(msg,true); Future<JSON::PNode> promise; waitingPromises.insert(promiseId,promise.getPromise()); return promise; } JsonRpcWebsocketsConnection* JsonRpcWebsocketsConnection::getConnection(IHttpRequest& request) { HttpRequestWrapper *rq = request.getIfcPtr<HttpRequestWrapper>(); if (rq == 0) return 0; return rq->owner; } void JsonRpcWebsocketsConnection::setContext(IHttpHandlerContext* context) { this->context = context; } IHttpHandlerContext* JsonRpcWebsocketsConnection::getContext() const { return context; } void JsonRpcWebsocketsConnection::onTextMessage(ConstStrA msg) { Synchronized<FastLock> _(lock); LS_LOGOBJ(lg); JSON::PNode req = json.factory->fromString(msg); if (req->getPtr("result")) { natural id = req["id"]->getUInt(); const Promise<JSON::PNode> *pres = waitingPromises.find(id); if (pres == 0) return; Promise<JSON::PNode> p = *pres; waitingPromises.erase(id); if (req["error"]->isNull()) p.resolve(req["result"]); else p.reject(RpcError(THISLOCATION,req["error"])); } else { TimeStamp beginTime = TimeStamp::now(); ConstStrA method = req["method"]->getStringUtf8(); JSON::PNode params = req["params"]; JSON::PNode id = req["id"]; JSON::PNode context = req->getPtr("context"); IJsonRpc::CallResult callRes; HttpRequestWrapper httpwrp(&http,this); try { SyncReleased<FastLock> _(lock); callRes = handler.callMethod(&httpwrp,method,params,context,id); if (logobject) logobject->logMethod(http,method,params,context,callRes.logOutput); } catch (std::exception &e) { callRes.result= json.factory->newValue(null); callRes.error = json.factory->newValue(e.what()); callRes.id = id; callRes.logOutput = callRes.error; } if (!id->isNull()) { JSON::Builder::Object response = json("result",callRes.result) ("error",callRes.error) ("id", callRes.id); if (callRes.newContext != nil) { response("context",callRes.newContext); } ConstStrA msg = json.factory->toString(*response); sendTextMessage(msg,true); } TimeStamp endTime = TimeStamp::now(); natural ms = (endTime - beginTime).getMilis(); lg.progress("%1 - POST %2 WSRPC/1.0 (%3 ms)") << http.getIfc<IHttpPeerInfo>().getPeerRealAddr() << method << ms; http.recordRequestDuration(ms); } } JsonRpcWebsockets::JsonRpcWebsockets(IJsonRpc& handler,StringA openMethod):handler(handler),openMethod(openMethod.getMT()) { } WebSocketConnection* JsonRpcWebsockets::onNewConnection( IRuntimeAlloc& alloc, IHttpRequest& request, ConstStrA ) { IHttpRequest::HeaderValue origin = request.getHeaderField(IHttpRequest::fldOrigin); bool allow = true; if (origin.defined) { Optional<bool> allowed = handler.isAllowedOrigin(origin); if (allowed == null) { ConstStrA corig = origin; if (corig.head(7) == ConstStrA("http://")) corig = corig.offset(7); else if (corig.head(8) == ConstStrA("https://")) corig = corig.offset(8); ConstStrA host = request.getHeaderField(IHttpRequest::fldHost); if (host.tail(corig.length()) != corig) allow = false; } else { allow = allowed; } } if (allow) return new(alloc) JsonRpcWebsocketsConnection(request,handler,openMethod); else throw HttpStatusException(THISLOCATION,request.getAbsoluteUrl(),403,"Forbidden"); } void JsonRpcWebsocketsConnection::onCloseOutput(natural ) { Synchronized<FastLock> _(lock); context = nil; } JsonRpcWebsocketsConnection::~JsonRpcWebsocketsConnection() { Synchronized<FastLock> _(lock); context = nil; } void JsonRpcWebsocketsConnection::onConnect() { if (!openMethod.empty()) { IJsonRpc::CallResult callRes; { JSON::PNode nullNode = json.factory->newNullNode(); JSON::PNode emptyArr = json.array(); SyncReleased<FastLock> _(lock); callRes = handler.callMethod(&http,openMethod,emptyArr,nullNode,nullNode); if (logobject) logobject->logMethod(http,openMethod,emptyArr,nullNode,callRes.logOutput); if (callRes.error != nil && !callRes.error->isNull()) { this->closeConnection(closeAbnormal); } } } } void JsonRpcWebsocketsConnection::sendNotification(const PreparedNtf& ntf) { this->sendTextMessage(ntf,true); } JsonRpcWebsocketsConnection::PreparedNtf JsonRpcWebsocketsConnection::prepareNotification( LightSpeed::ConstStrA name, LightSpeed::JSON::PNode arguments) { Synchronized<FastLock> _(lock); JSON::PNode req = json("method",name) ("params",arguments) ("id",nil); return IRpcNotify::prepare(json.factory->toString(*req)); } IRpcNotify *IRpcNotify::fromRequest(RpcRequest *r) { JsonRpcWebsocketsConnection *conn = JsonRpcWebsocketsConnection::getConnection(*r->httpRequest); return conn; } } /* namespace jsonsrv */ <|endoftext|>
<commit_before>/* * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <system_error> #include <cerrno> #include <array> #include <experimental/filesystem> #include "utils.hpp" #include "python.hpp" #include "components/script_butler.hpp" namespace fs = std::experimental::filesystem; namespace butler { script_butler::script_butler(const bookwyrm::item &&wanted) : wanted_(wanted) {} vector<pybind11::module> script_butler::load_sources() { #ifdef DEBUG /* Bookwyrm must be run from build/ in DEBUG mode. */ const auto source_path = fs::canonical(fs::path("../src/sources")); #else const std::array<fs::path, 2> paths = {"/etc/bookwyrm/sources", "~/.config/bookwyrm/sources"}; // TODO: follow <https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html> #endif /* * Append source_path to Python's sys.path, * allowing them to be imported. */ auto sys_path = py::reinterpret_borrow<py::list>(py::module::import("sys").attr("path")); sys_path.append(source_path.c_str()); /* * Find all Python modules and populate the * list of sources by loading them. * * The first occurance of a module will be imported, * the latter ones will be ignored by Python. So we * either need to prepend the paths to sys.path, or * make sure that we don't clash with the many module * names in Python. */ vector<py::module> sources; for (const fs::path &p : fs::directory_iterator(source_path)) { if (p.extension() != ".py") continue; if (!utils::readable_file(p)) { logger_->warn("can't load module '{}': not a regular file or unreadable" "; ignoring...", p.string()); continue; } try { string module = p.stem(); logger_->debug("loading module '{}'...", module); sources.emplace_back(py::module::import(module.c_str())); } catch (const py::error_already_set &err) { logger_->warn("{}; ignoring...", err.what()); } } if (sources.empty()) throw program_error("couldn't find any valid source modules, terminating..."); return sources; } script_butler::~script_butler() { /* * Current behaviour is that the program cannot terminate unless * all source threads has joined. We'll of course want do to this. * * It's not possible to end a std::thread in a smooth matter. We could * instead have a control variable that the source scripts check every * once in a while. When this is set upon quitting the curses UI, we'll * have to let each script handle its own termination. * * Not joining the threads here doesn't make the OS very happy. */ py::gil_scoped_release nogil; for (auto &t : threads_) t.join(); } void script_butler::async_search(vector<py::module> &sources) { for (const auto &m : sources) { try { threads_.emplace_back([&m, wanted = wanted_, bw_instance = this]() { /* Required whenever we need to run anything Python. */ py::gil_scoped_acquire gil; m.attr("find")(wanted, bw_instance); }); } catch (const py::error_already_set &err) { logger_->error("module '{}' did something wrong ({}); ignoring...", m.attr("__name__").cast<string>(), err.what()); continue; } } } void script_butler::add_item(std::tuple<bookwyrm::nonexacts_t, bookwyrm::exacts_t> item_comps) { bookwyrm::item item(item_comps); std::lock_guard<std::mutex> guard(items_mutex_); /* if (!item.matches(wanted_)) */ /* return; */ items_.push_back(item); screen_butler_->update_screens(); } /* ns butler */ } <commit_msg>butler/script: import scripts in releasg (XDG)<commit_after>/* * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <system_error> #include <cerrno> #include <cstdlib> #include <array> #include <experimental/filesystem> #include "utils.hpp" #include "python.hpp" #include "components/script_butler.hpp" namespace fs = std::experimental::filesystem; namespace butler { script_butler::script_butler(const bookwyrm::item &&wanted) : wanted_(wanted) {} vector<pybind11::module> script_butler::load_sources() { vector<fs::path> source_paths; #ifdef DEBUG /* Bookwyrm must be run from build/ in DEBUG mode. */ source_paths = { fs::canonical(fs::path("../src/sources")) }; #else if (fs::path conf = std::getenv("XDG_CONFIG_HOME"); !conf.empty()) source_paths.push_back(conf / "bookwyrm/sources"); else if (fs::path home = std::getenv("HOME"); !home.empty()) source_paths.push_back(home / ".config/bookwyrm/sources"); else logger_->error("couldn't find any source script directories."); #endif /* * Append the source paths to Python's sys.path, * allowing them to be imported. */ auto sys_path = py::reinterpret_borrow<py::list>(py::module::import("sys").attr("path")); for (auto &p : source_paths) sys_path.append(p.string().c_str()); /* * Find all Python modules and populate the * list of sources by loading them. * * The first occurance of a module will be imported, * the latter ones will be ignored by Python. So we * either need to prepend the paths to sys.path, or * make sure that we don't clash with the many module * names in Python. */ vector<py::module> sources; for (const auto &source_path : source_paths) { for (const fs::path &p : fs::directory_iterator(source_path)) { if (p.extension() != ".py") continue; if (!utils::readable_file(p)) { logger_->warn("can't load module '{}': not a regular file or unreadable" "; ignoring...", p.string()); continue; } try { string module = p.stem(); logger_->debug("loading module '{}'...", module); sources.emplace_back(py::module::import(module.c_str())); } catch (const py::error_already_set &err) { logger_->warn("{}; ignoring...", err.what()); } } } if (sources.empty()) throw program_error("couldn't find any valid source scripts, terminating..."); return sources; } script_butler::~script_butler() { /* * Current behaviour is that the program cannot terminate unless * all source threads has joined. We'll of course want do to this. * * It's not possible to end a std::thread in a smooth matter. We could * instead have a control variable that the source scripts check every * once in a while. When this is set upon quitting the curses UI, we'll * have to let each script handle its own termination. * * Not joining the threads here doesn't make the OS very happy. */ py::gil_scoped_release nogil; for (auto &t : threads_) t.join(); } void script_butler::async_search(vector<py::module> &sources) { for (const auto &m : sources) { try { threads_.emplace_back([&m, wanted = wanted_, bw_instance = this]() { /* Required whenever we need to run anything Python. */ py::gil_scoped_acquire gil; m.attr("find")(wanted, bw_instance); }); } catch (const py::error_already_set &err) { logger_->error("module '{}' did something wrong ({}); ignoring...", m.attr("__name__").cast<string>(), err.what()); continue; } } } void script_butler::add_item(std::tuple<bookwyrm::nonexacts_t, bookwyrm::exacts_t> item_comps) { bookwyrm::item item(item_comps); std::lock_guard<std::mutex> guard(items_mutex_); /* if (!item.matches(wanted_)) */ /* return; */ items_.push_back(item); screen_butler_->update_screens(); } /* ns butler */ } <|endoftext|>
<commit_before>#include "UnixSocketHandler.hpp" #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <unistd.h> namespace et { UnixSocketHandler::UnixSocketHandler() {} bool UnixSocketHandler::hasData(int fd) { lock_guard<std::recursive_mutex> guard(mutex); fd_set input; FD_ZERO(&input); FD_SET(fd, &input); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; int n = select(fd + 1, &input, NULL, NULL, &timeout); if (n == -1) { // Select timed out or failed. return false; } else if (n == 0) return false; if (!FD_ISSET(fd, &input)) { LOG(FATAL) << "FD_ISSET is false but we should have data by now."; } return true; } ssize_t UnixSocketHandler::read(int fd, void *buf, size_t count) { lock_guard<std::recursive_mutex> guard(mutex); if (fd <= 0) { LOG(FATAL) << "Tried to read from an invalid socket: " << fd; } if (activeSockets.find(fd) == activeSockets.end()) { LOG(INFO) << "Tried to read from a socket that has been closed: " << fd; return 0; } ssize_t readBytes = ::read(fd, buf, count); if (readBytes == 0) { throw runtime_error("Remote host closed connection"); } if (readBytes < 0) { LOG(ERROR) << "Error reading: " << errno << " " << strerror(errno) << endl; } return readBytes; } ssize_t UnixSocketHandler::write(int fd, const void *buf, size_t count) { lock_guard<std::recursive_mutex> guard(mutex); if (fd <= 0) { LOG(FATAL) << "Tried to write to an invalid socket: " << fd; } #ifdef MSG_NOSIGNAL return ::send(fd, buf, count, MSG_NOSIGNAL); #else return ::write(fd, buf, count); #endif } int UnixSocketHandler::connect(const std::string &hostname, int port) { lock_guard<std::recursive_mutex> guard(mutex); int sockfd = -1; addrinfo *results; addrinfo *p; addrinfo hints; memset(&hints, 0, sizeof(addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_CANONNAME; std::string portname = std::to_string(port); int rc = getaddrinfo(hostname.c_str(), portname.c_str(), &hints, &results); if (rc != 0) { LOG(ERROR) << "Error getting address info for " << hostname << ":" << portname << ": " << rc << " (" << gai_strerror(rc) << ")"; return -1; } // loop through all the results and connect to the first we can for (p = results; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { LOG(INFO) << "Error creating socket: " << errno << " " << strerror(errno); continue; } initSocket(sockfd); // Set nonblocking just for the connect phase { int opts; opts = fcntl(sockfd, F_GETFL); FATAL_FAIL(opts); opts |= O_NONBLOCK; FATAL_FAIL(fcntl(sockfd, F_SETFL, opts)); } if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1 && errno != EINPROGRESS) { LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << errno << " " << strerror(errno); ::close(sockfd); sockfd = -1; continue; } fd_set fdset; FD_ZERO(&fdset); FD_SET(sockfd, &fdset); timeval tv; tv.tv_sec = 3; /* 3 second timeout */ tv.tv_usec = 0; if (::select(sockfd + 1, NULL, &fdset, NULL, &tv) == 1) { int so_error; socklen_t len = sizeof so_error; FATAL_FAIL(::getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &so_error, &len)); if (so_error == 0) { LOG(INFO) << "Connected to server: " << p->ai_canonname << " using fd " << sockfd; // Make sure that socket becomes blocking once it's attached to a // server. { int opts; opts = fcntl(sockfd, F_GETFL); FATAL_FAIL(opts); opts &= (~O_NONBLOCK); FATAL_FAIL(fcntl(sockfd, F_SETFL, opts)); } break; // if we get here, we must have connected successfully } else { if (p->ai_canonname) { LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << so_error << " " << strerror(so_error); } else { LOG(INFO) << "Error connecting to " << hostname << ": " << so_error << " " << strerror(so_error); } ::close(sockfd); sockfd = -1; continue; } } else { LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << errno << " " << strerror(errno); ::close(sockfd); sockfd = -1; continue; } } if (sockfd == -1) { LOG(ERROR) << "ERROR, no host found"; } else { if (activeSockets.find(sockfd) != activeSockets.end()) { LOG(FATAL) << "Tried to insert an fd that already exists: " << sockfd; } activeSockets.insert(sockfd); } freeaddrinfo(results); return sockfd; } int UnixSocketHandler::listen(int port) { lock_guard<std::recursive_mutex> guard(mutex); if (serverSockets.empty()) { addrinfo hints, *servinfo, *p; int rc; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP address std::string portname = std::to_string(port); if ((rc = getaddrinfo(NULL, portname.c_str(), &hints, &servinfo)) != 0) { LOG(ERROR) << "Error getting address info for " << port << ": " << rc << " (" << gai_strerror(rc) << ")"; exit(1); } // loop through all the results and bind to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { int sockfd; if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { LOG(INFO) << "Error creating socket " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno); continue; } initSocket(sockfd); // Also set the accept socket as non-blocking { int opts; opts = fcntl(sockfd, F_GETFL); FATAL_FAIL(opts); opts |= O_NONBLOCK; FATAL_FAIL(fcntl(sockfd, F_SETFL, opts)); } // Also set the accept socket as reusable { int flag = 1; FATAL_FAIL(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(int))); } if (p->ai_family == AF_INET6) { // Also ensure that IPV6 sockets only listen on IPV6 // interfaces. We will create another socket object for IPV4 // if it doesn't already exist. int flag = 1; FATAL_FAIL(setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&flag, sizeof(int))); } if (::bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { // This most often happens because the port is in use. LOG(ERROR) << "Error binding " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno); cerr << "Error binding " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno) << flush; exit(1); // close(sockfd); // continue; } // Listen FATAL_FAIL(::listen(sockfd, 32)); LOG(INFO) << "Listening on " << inet_ntoa(((sockaddr_in*)p->ai_addr)->sin_addr) << ":" << port << "/" << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol; // if we get here, we must have connected successfully serverSockets.push_back(sockfd); activeSockets.insert(sockfd); } if (serverSockets.empty()) { LOG(FATAL) << "Could not bind to any interface!"; } } for (int sockfd : serverSockets) { sockaddr_in client; socklen_t c = sizeof(sockaddr_in); int client_sock = ::accept(sockfd, (sockaddr *)&client, &c); if (client_sock >= 0) { initSocket(client_sock); activeSockets.insert(client_sock); // Make sure that socket becomes blocking once it's attached to a client. { int opts; opts = fcntl(client_sock, F_GETFL); FATAL_FAIL(opts); opts &= (~O_NONBLOCK); FATAL_FAIL(fcntl(client_sock, F_SETFL, opts)); } return client_sock; } else if (errno != EAGAIN && errno != EWOULDBLOCK) { FATAL_FAIL(-1); // LOG(FATAL) with the error } } return -1; } void UnixSocketHandler::stopListening() { lock_guard<std::recursive_mutex> guard(mutex); for (int sockfd : serverSockets) { close(sockfd); } } void UnixSocketHandler::close(int fd) { lock_guard<std::recursive_mutex> guard(mutex); if (fd == -1) { return; } if (activeSockets.find(fd) == activeSockets.end()) { // Connection was already killed. LOG(ERROR) << "Tried to close a connection that doesn't exist: " << fd; return; } activeSockets.erase(activeSockets.find(fd)); #if 0 VLOG(1) << "Shutting down connection: " << fd << endl; int rc = ::shutdown(fd, SHUT_RDWR); if (rc == -1) { if (errno == ENOTCONN || errno == EADDRNOTAVAIL) { // Shutdown is failing on OS/X with errno (49): Can't assign requested address // Possibly an OS bug but I don't think it's necessary anyways. // ENOTCONN is harmless } else { FATAL_FAIL(rc); } } #endif VLOG(1) << "Closing connection: " << fd << endl; FATAL_FAIL(::close(fd)); } void UnixSocketHandler::initSocket(int fd) { int flag = 1; FATAL_FAIL(setsockopt(fd, /* socket affected */ IPPROTO_TCP, /* set option at TCP level */ TCP_NODELAY, /* name of option */ (char *)&flag, /* the cast is historical cruft */ sizeof(int))); /* length of option value */ timeval tv; tv.tv_sec = 5; tv.tv_usec = 0; FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv))); FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv))); #ifndef MSG_NOSIGNAL // If we don't have MSG_NOSIGNAL, use SO_NOSIGPIPE int val = 1; FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&val, sizeof(val))); #endif } } <commit_msg>Bail early if trying to write to an unknown socket<commit_after>#include "UnixSocketHandler.hpp" #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <unistd.h> namespace et { UnixSocketHandler::UnixSocketHandler() {} bool UnixSocketHandler::hasData(int fd) { lock_guard<std::recursive_mutex> guard(mutex); fd_set input; FD_ZERO(&input); FD_SET(fd, &input); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; int n = select(fd + 1, &input, NULL, NULL, &timeout); if (n == -1) { // Select timed out or failed. return false; } else if (n == 0) return false; if (!FD_ISSET(fd, &input)) { LOG(FATAL) << "FD_ISSET is false but we should have data by now."; } return true; } ssize_t UnixSocketHandler::read(int fd, void *buf, size_t count) { lock_guard<std::recursive_mutex> guard(mutex); if (fd <= 0) { LOG(FATAL) << "Tried to read from an invalid socket: " << fd; } if (activeSockets.find(fd) == activeSockets.end()) { LOG(INFO) << "Tried to read from a socket that has been closed: " << fd; return 0; } ssize_t readBytes = ::read(fd, buf, count); if (readBytes == 0) { throw runtime_error("Remote host closed connection"); } if (readBytes < 0) { LOG(ERROR) << "Error reading: " << errno << " " << strerror(errno) << endl; } return readBytes; } ssize_t UnixSocketHandler::write(int fd, const void *buf, size_t count) { lock_guard<std::recursive_mutex> guard(mutex); if (fd <= 0) { LOG(FATAL) << "Tried to write to an invalid socket: " << fd; } if (activeSockets.find(fd) == activeSockets.end()) { LOG(INFO) << "Tried to write to a socket that has been closed: " << fd; return 0; } #ifdef MSG_NOSIGNAL return ::send(fd, buf, count, MSG_NOSIGNAL); #else return ::write(fd, buf, count); #endif } int UnixSocketHandler::connect(const std::string &hostname, int port) { lock_guard<std::recursive_mutex> guard(mutex); int sockfd = -1; addrinfo *results; addrinfo *p; addrinfo hints; memset(&hints, 0, sizeof(addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_CANONNAME; std::string portname = std::to_string(port); int rc = getaddrinfo(hostname.c_str(), portname.c_str(), &hints, &results); if (rc != 0) { LOG(ERROR) << "Error getting address info for " << hostname << ":" << portname << ": " << rc << " (" << gai_strerror(rc) << ")"; return -1; } // loop through all the results and connect to the first we can for (p = results; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { LOG(INFO) << "Error creating socket: " << errno << " " << strerror(errno); continue; } initSocket(sockfd); // Set nonblocking just for the connect phase { int opts; opts = fcntl(sockfd, F_GETFL); FATAL_FAIL(opts); opts |= O_NONBLOCK; FATAL_FAIL(fcntl(sockfd, F_SETFL, opts)); } if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1 && errno != EINPROGRESS) { LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << errno << " " << strerror(errno); ::close(sockfd); sockfd = -1; continue; } fd_set fdset; FD_ZERO(&fdset); FD_SET(sockfd, &fdset); timeval tv; tv.tv_sec = 3; /* 3 second timeout */ tv.tv_usec = 0; if (::select(sockfd + 1, NULL, &fdset, NULL, &tv) == 1) { int so_error; socklen_t len = sizeof so_error; FATAL_FAIL(::getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &so_error, &len)); if (so_error == 0) { LOG(INFO) << "Connected to server: " << p->ai_canonname << " using fd " << sockfd; // Make sure that socket becomes blocking once it's attached to a // server. { int opts; opts = fcntl(sockfd, F_GETFL); FATAL_FAIL(opts); opts &= (~O_NONBLOCK); FATAL_FAIL(fcntl(sockfd, F_SETFL, opts)); } break; // if we get here, we must have connected successfully } else { if (p->ai_canonname) { LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << so_error << " " << strerror(so_error); } else { LOG(INFO) << "Error connecting to " << hostname << ": " << so_error << " " << strerror(so_error); } ::close(sockfd); sockfd = -1; continue; } } else { LOG(INFO) << "Error connecting with " << p->ai_canonname << ": " << errno << " " << strerror(errno); ::close(sockfd); sockfd = -1; continue; } } if (sockfd == -1) { LOG(ERROR) << "ERROR, no host found"; } else { if (activeSockets.find(sockfd) != activeSockets.end()) { LOG(FATAL) << "Tried to insert an fd that already exists: " << sockfd; } activeSockets.insert(sockfd); } freeaddrinfo(results); return sockfd; } int UnixSocketHandler::listen(int port) { lock_guard<std::recursive_mutex> guard(mutex); if (serverSockets.empty()) { addrinfo hints, *servinfo, *p; int rc; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP address std::string portname = std::to_string(port); if ((rc = getaddrinfo(NULL, portname.c_str(), &hints, &servinfo)) != 0) { LOG(ERROR) << "Error getting address info for " << port << ": " << rc << " (" << gai_strerror(rc) << ")"; exit(1); } // loop through all the results and bind to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { int sockfd; if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { LOG(INFO) << "Error creating socket " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno); continue; } initSocket(sockfd); // Also set the accept socket as non-blocking { int opts; opts = fcntl(sockfd, F_GETFL); FATAL_FAIL(opts); opts |= O_NONBLOCK; FATAL_FAIL(fcntl(sockfd, F_SETFL, opts)); } // Also set the accept socket as reusable { int flag = 1; FATAL_FAIL(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(int))); } if (p->ai_family == AF_INET6) { // Also ensure that IPV6 sockets only listen on IPV6 // interfaces. We will create another socket object for IPV4 // if it doesn't already exist. int flag = 1; FATAL_FAIL(setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&flag, sizeof(int))); } if (::bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { // This most often happens because the port is in use. LOG(ERROR) << "Error binding " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno); cerr << "Error binding " << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol << ": " << errno << " " << strerror(errno) << flush; exit(1); // close(sockfd); // continue; } // Listen FATAL_FAIL(::listen(sockfd, 32)); LOG(INFO) << "Listening on " << inet_ntoa(((sockaddr_in*)p->ai_addr)->sin_addr) << ":" << port << "/" << p->ai_family << "/" << p->ai_socktype << "/" << p->ai_protocol; // if we get here, we must have connected successfully serverSockets.push_back(sockfd); activeSockets.insert(sockfd); } if (serverSockets.empty()) { LOG(FATAL) << "Could not bind to any interface!"; } } for (int sockfd : serverSockets) { sockaddr_in client; socklen_t c = sizeof(sockaddr_in); int client_sock = ::accept(sockfd, (sockaddr *)&client, &c); if (client_sock >= 0) { initSocket(client_sock); activeSockets.insert(client_sock); // Make sure that socket becomes blocking once it's attached to a client. { int opts; opts = fcntl(client_sock, F_GETFL); FATAL_FAIL(opts); opts &= (~O_NONBLOCK); FATAL_FAIL(fcntl(client_sock, F_SETFL, opts)); } return client_sock; } else if (errno != EAGAIN && errno != EWOULDBLOCK) { FATAL_FAIL(-1); // LOG(FATAL) with the error } } return -1; } void UnixSocketHandler::stopListening() { lock_guard<std::recursive_mutex> guard(mutex); for (int sockfd : serverSockets) { close(sockfd); } } void UnixSocketHandler::close(int fd) { lock_guard<std::recursive_mutex> guard(mutex); if (fd == -1) { return; } if (activeSockets.find(fd) == activeSockets.end()) { // Connection was already killed. LOG(ERROR) << "Tried to close a connection that doesn't exist: " << fd; return; } activeSockets.erase(activeSockets.find(fd)); #if 0 VLOG(1) << "Shutting down connection: " << fd << endl; int rc = ::shutdown(fd, SHUT_RDWR); if (rc == -1) { if (errno == ENOTCONN || errno == EADDRNOTAVAIL) { // Shutdown is failing on OS/X with errno (49): Can't assign requested address // Possibly an OS bug but I don't think it's necessary anyways. // ENOTCONN is harmless } else { FATAL_FAIL(rc); } } #endif VLOG(1) << "Closing connection: " << fd << endl; FATAL_FAIL(::close(fd)); } void UnixSocketHandler::initSocket(int fd) { int flag = 1; FATAL_FAIL(setsockopt(fd, /* socket affected */ IPPROTO_TCP, /* set option at TCP level */ TCP_NODELAY, /* name of option */ (char *)&flag, /* the cast is historical cruft */ sizeof(int))); /* length of option value */ timeval tv; tv.tv_sec = 5; tv.tv_usec = 0; FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv))); FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv))); #ifndef MSG_NOSIGNAL // If we don't have MSG_NOSIGNAL, use SO_NOSIGPIPE int val = 1; FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&val, sizeof(val))); #endif } } <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <boost/config.hpp> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> // for exit() #include "setup_transfer.hpp" // for tests_failure int test_main(); #include "libtorrent/assert.hpp" #include "libtorrent/file.hpp" #include <signal.h> void sig_handler(int sig) { char stack_text[10000]; #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS print_backtrace(stack_text, sizeof(stack_text), 30); #elif defined __FUNCTION__ strcat(stack_text, __FUNCTION__); #else stack_text[0] = 0; #endif char const* sig_name = 0; switch (sig) { #define SIG(x) case x: sig_name = #x; break SIG(SIGSEGV); #ifdef SIGBUS SIG(SIGBUS); #endif SIG(SIGILL); SIG(SIGABRT); SIG(SIGFPE); #ifdef SIGSYS SIG(SIGSYS); #endif #undef SIG }; fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text); exit(138); } using namespace libtorrent; int main() { #ifdef O_NONBLOCK // on darwin, stdout is set to non-blocking mode by default // which sometimes causes tests to fail with EAGAIN just // by printing logs int flags = fcntl(fileno(stdout), F_GETFL, 0); fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK); flags = fcntl(fileno(stderr), F_GETFL, 0); fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK); #endif signal(SIGSEGV, &sig_handler); #ifdef SIGBUS signal(SIGBUS, &sig_handler); #endif signal(SIGILL, &sig_handler); signal(SIGABRT, &sig_handler); signal(SIGFPE, &sig_handler); #ifdef SIGSYS signal(SIGSYS, &sig_handler); #endif char dir[40]; snprintf(dir, sizeof(dir), "test_tmp_%u", rand()); std::string test_dir = complete(dir); error_code ec; create_directory(test_dir, ec); if (ec) { fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str()); return 1; } #ifdef TORRENT_WINDOWS SetCurrentDirectoryA(dir); #else chdir(dir); #endif #ifndef BOOST_NO_EXCEPTIONS try { #endif test_main(); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; tests_failure = true; } catch (...) { std::cerr << "Terminated with unknown exception\n"; tests_failure = true; } #endif fflush(stdout); fflush(stderr); remove_all(test_dir, ec); if (ec) fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str()); return tests_failure ? 1 : 0; } <commit_msg>initialize random number generator for tests<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <boost/config.hpp> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> // for exit() #include "setup_transfer.hpp" // for tests_failure int test_main(); #include "libtorrent/assert.hpp" #include "libtorrent/file.hpp" #include <signal.h> void sig_handler(int sig) { char stack_text[10000]; #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS print_backtrace(stack_text, sizeof(stack_text), 30); #elif defined __FUNCTION__ strcat(stack_text, __FUNCTION__); #else stack_text[0] = 0; #endif char const* sig_name = 0; switch (sig) { #define SIG(x) case x: sig_name = #x; break SIG(SIGSEGV); #ifdef SIGBUS SIG(SIGBUS); #endif SIG(SIGILL); SIG(SIGABRT); SIG(SIGFPE); #ifdef SIGSYS SIG(SIGSYS); #endif #undef SIG }; fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text); exit(138); } using namespace libtorrent; int main() { srand(total_microseconds(time_now_hires() - min_time())); #ifdef O_NONBLOCK // on darwin, stdout is set to non-blocking mode by default // which sometimes causes tests to fail with EAGAIN just // by printing logs int flags = fcntl(fileno(stdout), F_GETFL, 0); fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK); flags = fcntl(fileno(stderr), F_GETFL, 0); fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK); #endif signal(SIGSEGV, &sig_handler); #ifdef SIGBUS signal(SIGBUS, &sig_handler); #endif signal(SIGILL, &sig_handler); signal(SIGABRT, &sig_handler); signal(SIGFPE, &sig_handler); #ifdef SIGSYS signal(SIGSYS, &sig_handler); #endif char dir[40]; snprintf(dir, sizeof(dir), "test_tmp_%u", rand()); std::string test_dir = complete(dir); error_code ec; create_directory(test_dir, ec); if (ec) { fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str()); return 1; } #ifdef TORRENT_WINDOWS SetCurrentDirectoryA(dir); #else chdir(dir); #endif #ifndef BOOST_NO_EXCEPTIONS try { #endif test_main(); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; tests_failure = true; } catch (...) { std::cerr << "Terminated with unknown exception\n"; tests_failure = true; } #endif fflush(stdout); fflush(stderr); remove_all(test_dir, ec); if (ec) fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str()); return tests_failure ? 1 : 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <boost/config.hpp> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> // for exit() #include "setup_transfer.hpp" // for tests_failure #include "dht_server.hpp" // for stop_dht #include "peer_server.hpp" // for stop_peer int test_main(); #include "libtorrent/assert.hpp" #include "libtorrent/file.hpp" #include <signal.h> void sig_handler(int sig) { char stack_text[10000]; #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS print_backtrace(stack_text, sizeof(stack_text), 30); #elif defined __FUNCTION__ strcat(stack_text, __FUNCTION__); #else stack_text[0] = 0; #endif char const* sig_name = 0; switch (sig) { #define SIG(x) case x: sig_name = #x; break SIG(SIGSEGV); #ifdef SIGBUS SIG(SIGBUS); #endif SIG(SIGILL); SIG(SIGABRT); SIG(SIGFPE); #ifdef SIGSYS SIG(SIGSYS); #endif #undef SIG }; fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text); exit(138); } using namespace libtorrent; int main() { srand(total_microseconds(time_now_hires() - min_time())); #ifdef O_NONBLOCK // on darwin, stdout is set to non-blocking mode by default // which sometimes causes tests to fail with EAGAIN just // by printing logs int flags = fcntl(fileno(stdout), F_GETFL, 0); fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK); flags = fcntl(fileno(stderr), F_GETFL, 0); fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK); #endif signal(SIGSEGV, &sig_handler); #ifdef SIGBUS signal(SIGBUS, &sig_handler); #endif signal(SIGILL, &sig_handler); signal(SIGABRT, &sig_handler); signal(SIGFPE, &sig_handler); #ifdef SIGSYS signal(SIGSYS, &sig_handler); #endif char dir[40]; snprintf(dir, sizeof(dir), "test_tmp_%u", rand()); std::string test_dir = complete(dir); error_code ec; create_directory(test_dir, ec); if (ec) { fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str()); return 1; } #ifdef TORRENT_WINDOWS SetCurrentDirectoryA(dir); #else chdir(dir); #endif #ifndef BOOST_NO_EXCEPTIONS try { #endif test_main(); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; tests_failure = true; } catch (...) { std::cerr << "Terminated with unknown exception\n"; tests_failure = true; } #endif // just in case of premature exits // make sure we try to clean up some stop_tracker(); stop_all_proxies(); stop_web_server(); stop_peer(); stop_dht(); fflush(stdout); fflush(stderr); remove_all(test_dir, ec); if (ec) fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str()); return tests_failure ? 1 : 0; } <commit_msg>SetErrorMode at the start of unit tests (on windows)<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <boost/config.hpp> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> // for exit() #include "setup_transfer.hpp" // for tests_failure #include "dht_server.hpp" // for stop_dht #include "peer_server.hpp" // for stop_peer int test_main(); #include "libtorrent/assert.hpp" #include "libtorrent/file.hpp" #include <signal.h> #ifdef WIN32 #include <windows.h> // fot SetErrorMode #endif void sig_handler(int sig) { char stack_text[10000]; #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS print_backtrace(stack_text, sizeof(stack_text), 30); #elif defined __FUNCTION__ strcat(stack_text, __FUNCTION__); #else stack_text[0] = 0; #endif char const* sig_name = 0; switch (sig) { #define SIG(x) case x: sig_name = #x; break SIG(SIGSEGV); #ifdef SIGBUS SIG(SIGBUS); #endif SIG(SIGILL); SIG(SIGABRT); SIG(SIGFPE); #ifdef SIGSYS SIG(SIGSYS); #endif #undef SIG }; fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text); exit(138); } using namespace libtorrent; int main() { #ifdef WIN32 // try to suppress hanging the process by windows displaying // modal dialogs. SetErrorMode(SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); #endif srand(total_microseconds(time_now_hires() - min_time())); #ifdef O_NONBLOCK // on darwin, stdout is set to non-blocking mode by default // which sometimes causes tests to fail with EAGAIN just // by printing logs int flags = fcntl(fileno(stdout), F_GETFL, 0); fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK); flags = fcntl(fileno(stderr), F_GETFL, 0); fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK); #endif signal(SIGSEGV, &sig_handler); #ifdef SIGBUS signal(SIGBUS, &sig_handler); #endif signal(SIGILL, &sig_handler); signal(SIGABRT, &sig_handler); signal(SIGFPE, &sig_handler); #ifdef SIGSYS signal(SIGSYS, &sig_handler); #endif char dir[40]; snprintf(dir, sizeof(dir), "test_tmp_%u", rand()); std::string test_dir = complete(dir); error_code ec; create_directory(test_dir, ec); if (ec) { fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str()); return 1; } #ifdef TORRENT_WINDOWS SetCurrentDirectoryA(dir); #else chdir(dir); #endif #ifndef BOOST_NO_EXCEPTIONS try { #endif test_main(); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; tests_failure = true; } catch (...) { std::cerr << "Terminated with unknown exception\n"; tests_failure = true; } #endif // just in case of premature exits // make sure we try to clean up some stop_tracker(); stop_all_proxies(); stop_web_server(); stop_peer(); stop_dht(); fflush(stdout); fflush(stderr); remove_all(test_dir, ec); if (ec) fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str()); return tests_failure ? 1 : 0; } <|endoftext|>
<commit_before>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <memory> #include <grpc++/channel.h> #include <grpc++/create_channel.h> #include <grpc++/impl/grpc_library.h> #include <grpc++/support/channel_arguments.h> #include "src/cpp/client/create_channel_internal.h" namespace grpc { class ChannelArguments; std::shared_ptr<Channel> CreateChannel( const grpc::string& target, const std::shared_ptr<ChannelCredentials>& creds) { return CreateCustomChannel(target, creds, ChannelArguments()); } std::shared_ptr<Channel> CreateCustomChannel( const grpc::string& target, const std::shared_ptr<ChannelCredentials>& creds, const ChannelArguments& args) { GrpcLibraryCodegen init_lib; // We need to call init in case of a bad creds. return creds ? creds->CreateChannel(target, args) : CreateChannelInternal("", grpc_lame_client_channel_create( NULL, GRPC_STATUS_INVALID_ARGUMENT, "Invalid credentials.")); } } // namespace grpc <commit_msg>Update create_channel.cc<commit_after>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <memory> #include <grpc++/channel.h> #include <grpc++/create_channel.h> #include <grpc++/impl/grpc_library.h> #include <grpc++/support/channel_arguments.h> #include "src/cpp/client/create_channel_internal.h" namespace grpc { class ChannelArguments; std::shared_ptr<Channel> CreateChannel( const grpc::string& target, const std::shared_ptr<ChannelCredentials>& creds) { return CreateCustomChannel(target, creds, ChannelArguments()); } std::shared_ptr<Channel> CreateCustomChannel( const grpc::string& target, const std::shared_ptr<ChannelCredentials>& creds, const ChannelArguments& args) { GrpcLibraryCodegen init_lib; // We need to call init in case of a bad creds. return creds ? creds->CreateChannel(target, args) : CreateChannelInternal("", grpc_lame_client_channel_create( NULL, GRPC_STATUS_INVALID_ARGUMENT, "Invalid credentials.")); } } // namespace grpc <|endoftext|>
<commit_before>/* tinyxml2ex - a set of add-on classes and helper functions bringing C++11/14 features, such as iterators, strings and exceptions, to tinyxml2 Copyright (c) 2016 Stan Thomas Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. tinyxml2 is the work of Lee Thomason (www.grinninglizard.com) and others. It can be found here: https://github.com/leethomason/tinyxml2 and has it's own licensing terms. */ #include <string> #include <iostream> #include <algorithm> #include <conio.h> // include the header for tinyxml2ex which includes tinyxml2, remember to put them on your include path #include <tixml2ex.h> using namespace std; using namespace std::literals::string_literals; int main() { // a simple XML document string testXml {R"-( <?xml version="1.0" encoding="UTF-8"?> <A> <B id="one"> <C code="1234"> A-B(one)-C.1234 </C> <C code="5678"> <![CDATA[A-B(one)-C.5678]]> </C> <C code="9ABC"> A-B{one)-C.9ABC</C> <D code="9ABC" id="dd" /> </B> <B id="two"> <D id="dd" /> </B> <B id="three" org="{extern}"> <C code="1234"> A-B(three)-C.1234 </C> <C code="9ABC">A-B(three)-C.9ABC</C> <D description="A-B(three)-D.9ABC" /> </B> <B id="four"> one {B4} two {B4} </B> </A> )-"s}; // these three blocks are equivalent and demonstrate different ways to iterate over // all <C> element children of <B> element children of the document element <A> // we only want to inspect the elements and attributes, so treat the XMLElements as const // 1) native TinyXML2 { printf ("\n1) <C> element children of <B> element children of the document element <A>\nnative TinyXML2\n"); tinyxml2::XMLDocument doc; if (doc .Parse (testXml .c_str()) == 0/*XML_NO_ERORR*/) { const tinyxml2::XMLElement * eA = doc .FirstChildElement(); if (eA) { const tinyxml2::XMLElement * eB = eA -> FirstChildElement("B"); while (eB) { const tinyxml2::XMLElement * eC = eB -> FirstChildElement ("C"); while (eC) { printf ("%s = %s\n", eC -> Name(), eC -> GetText()); eC = eC -> NextSiblingElement ("C"); } eB = eB -> NextSiblingElement ("B"); } } else printf ("unable to load XML document\n"); } } cout << "----" << endl << endl; // 2) tixml2ex XPath selector cout << "2) <C> element children of <B> element children of the document element <A>" << endl << "tixml2ex XPath selector" << endl; try { auto doc = tinyxml2::load_document (testXml); for (auto eC : tinyxml2::selection (static_cast <const tinyxml2::XMLDocument &> (*doc), "A/B/C")) cout << eC -> Name() << " = " << text (eC) << endl; } catch (tinyxml2::XmlException & e) { cout << "XmlException caught" << e .what() << endl; } cout << "----" << endl << endl; // 3) simple tixml2ex element iterator cout << endl << "3) <C> element children of <B> element children of the document element <A>" << endl << "simple tixml2ex element iterator" << endl; try { auto doc = tinyxml2::load_document (testXml); auto eA = doc -> FirstChildElement(); if (eA) for (auto eB : eA) { // just for fun, use standard algorithm for_each to iterate over the children of <B> for_each (cbegin (eB), cend (eB), [](auto e) { // simple iterators are just that, they iterate over all children // therefore we must test element name (type) to examine only <C> elements if (strcmp (e -> Name(), "C") == 0) cout << e -> Name() << " = " << text (e) << endl; }); } } catch (tinyxml2::XmlException & e) { cout << "XmlException caught" << e .what() << endl; } cout << "=================================================" << endl << endl; // additional element selection and iteration using XPath syntax // illustrating helper functions try { auto doc = tinyxml2::load_document (testXml); // find first matching an element in the document cout << "find an element by attribute value" << endl; auto bThree = find_element (static_cast<const tinyxml2::XMLDocument &>(*doc), "A/B[@id='three']"s); cout << attribute_value (bThree, "id"s) << " - " << attribute_value (bThree, "org"s) << endl; cout << "=================================================" << endl << endl; // find the first instance of a child element of the selected type cout << "get description attribute of <D> element" << endl; if (auto ch1 = find_element (bThree, "D"s)) cout << attribute_value (ch1, "description"s) << text (ch1) << endl << endl; cout << "=================================================" << endl << endl; // iterate over all <C> children of selected <B> cout << "iterate over all <C> children of selected <B>" << endl; for (auto cc : tinyxml2::selection (bThree, "C"s)) { cout << cc -> Parent() -> ToElement() -> Name() << "[" << attribute_value (cc -> Parent() -> ToElement(), "id") << "] / " << cc -> Name() << "[@code='"; if (!attribute_value (cc, "code") .empty()) cout << attribute_value (cc, "code"); else cout << "**element has no attribute - code**"; cout << "']" << endl; } cout << "=================================================" << endl << endl; // iterate over all elements in the document along the selected path by starting with '/' // note that because path starts from the document, bThree is used only as an element in the document not the root of the search cout << "iterate over all <C> children : /A/B[@id='three']/C" << endl; int nC = 0; for (auto cc : tinyxml2::selection (bThree, "/A/B[@id='three']/C"s)) { ++nC; cout << cc -> Parent() -> ToElement() -> Name() << "[" << attribute_value (cc -> Parent() -> ToElement(), "id") << "] / " << cc -> Name() << "[@code='"; if (!attribute_value (cc, "code") .empty()) cout << attribute_value (cc, "code"); else cout << "**element has no attribute - code**"; cout << "']" << endl; } cout << nC << " Cs in B[@id='three']" << endl << endl; cout << "=================================================" << endl << endl; // iterate over all children, any name (type), with code attribute value cout << "iterate over all children of any name (type) : /A/B/[@code='9ABC']" << endl; for (auto cc : tinyxml2::selection (bThree, "/A/B/[@code='9ABC']"s)) { cout << cc -> Parent() -> ToElement() -> Name() << "[" << attribute_value (cc -> Parent() -> ToElement(), "id") << "] / " << cc -> Name() << "[@code='"; if (!attribute_value (cc, "code") .empty()) cout << attribute_value (cc, "code"); else cout << "**element has no attribute - code**"; cout << "']" << endl; } cout << "=================================================" << endl << endl; // find the first instance of a child element of the selected type with a matching attribute value cout << "find C[@code='9ABC'] within B[@id='three']" << endl; if (auto cc = find_element (bThree, "C[@code='9ABC']"s)) cout << text (cc) << " , " << attribute_value (cc, "description") << endl << endl; else cout << "could not find C[@code='9ABC'] in B" << endl; cout << "=================================================" << endl << endl; // find the same element within document cout << "find B[@id='three']/C[@code='9ABC']" << endl; if (auto cc = find_element (*doc, "/A/B[@id='three']/C[@code='9ABC']"s)) cout << text (cc) << " , " << attribute_value (cc, "description") << endl << endl; else cout << "could not find A/B[@id='three']/C[@code='9ABC'] in document" << endl; cout << "=================================================" << endl << endl; } catch (tinyxml2::XmlException & e) { cout << e .what() << endl; } /////////////////////// modify the document try { auto doc = tinyxml2::load_document (testXml); // create new CZ element in branch below selected <C> element with new CX and new CY auto ne = append_element (find_element (*doc, "/A/B[@id='three']/C[@code='9ABC']"s), "CX/CY[@id='099']/CZ", {{"id"s, "0998"s}, {"code"s, "ASDF"s}}, "magnum"s); // now use the inserted element to insert another after it auto czId {"1233"s}; auto czCode {"ZXCV"s}; auto czData {"corneto"s}; insert_next_element (ne, "CZ", {{"id"s, czId}, {"code"s, czCode}}, czData); // todo: // what do we want find_element to do when path is empty? // . find the first child element (which is what it does now) ? // . or simply return the parent element passed in ? tinyxml2::XMLPrinter printer; doc -> Print (&printer); cout << printer .CStr() << endl; } catch (tinyxml2::XmlException & e) { cout << e .what() << endl; } /////////////////////// copy try { auto source = tinyxml2::load_document (testXml); auto dest = std::make_unique <tinyxml2::XMLDocument>(); auto e = dest -> NewElement ("mycopy"); dest -> InsertEndChild (e); xcopy (source -> FirstChildElement(), e, {{"extern", "internal"}, {"B4", "Bee Four"}}); tinyxml2::XMLPrinter printer; dest -> Print (&printer); cout << printer .CStr() << endl; } catch (tinyxml2::XmlException & e) { cout << e .what() << endl; } // hold console window open so we can see the output std::cout << "hit any key to close" << std::endl; auto c = _getch(); return 0; } <commit_msg>Update test example to include tixml2cx.h<commit_after>/* tinyxml2ex - a set of add-on classes and helper functions bringing C++11/14 features, such as iterators, strings and exceptions, to tinyxml2 Copyright (c) 2016 Stan Thomas Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. tinyxml2 is the work of Lee Thomason (www.grinninglizard.com) and others. It can be found here: https://github.com/leethomason/tinyxml2 and has it's own licensing terms. */ #include <string> #include <iostream> #include <algorithm> #include <conio.h> // include the header for tinyxml2ex which includes tinyxml2, remember to put them on your include path #include <tixml2cx.h> using namespace std; using namespace std::literals::string_literals; int main() { // a simple XML document string testXml {R"-( <?xml version="1.0" encoding="UTF-8"?> <A> <B id="one"> <C code="1234"> A-B(one)-C.1234 </C> <C code="5678"> <![CDATA[A-B(one)-C.5678]]> </C> <C code="9ABC"> A-B{one)-C.9ABC</C> <D code="9ABC" id="d1" /> </B> <B id="two"> <D id="d2" /> </B> <B id="three" org="{extern}"> <C code="1234"> A-B(three)-C.1234 </C> <C code="9ABC">A-B(three)-C.9ABC</C> <D id="d3" description="A-B(three)-D.9ABC" /> </B> <B id="four"> one {B4} two {B4} </B> </A> )-"s}; // these three blocks are equivalent and demonstrate different ways to iterate over // all <C> element children of <B> element children of the document element <A> // we only want to inspect the elements and attributes, so treat the XMLElements as const // 1) native TinyXML2 : 21 lines of code { printf ("\n1) <C> element children of <B> element children of the document element <A>\nnative TinyXML2\n"); tinyxml2::XMLDocument doc; if (doc .Parse (testXml .c_str()) == 0/*XML_NO_ERORR*/) { const tinyxml2::XMLElement * eA = doc .FirstChildElement(); if (eA) { const tinyxml2::XMLElement * eB = eA -> FirstChildElement("B"); while (eB) { const tinyxml2::XMLElement * eC = eB -> FirstChildElement ("C"); while (eC) { printf ("%s = %s\n", eC -> Name(), eC -> GetText()); eC = eC -> NextSiblingElement ("C"); } eB = eB -> NextSiblingElement ("B"); } } else printf ("unable to load XML document\n"); } } cout << "----" << endl << endl; // 2) tixml2ex XPath selector : 10 lines of code cout << "2) <C> element children of <B> element children of the document element <A>" << endl << "tixml2ex XPath selector" << endl; try { auto doc = tinyxml2::load_document (testXml); // n.b. the static_cast makes the XMLDocument const and hence all XMLElements returned are also const for (auto eC : tinyxml2::selection (static_cast <const tinyxml2::XMLDocument &> (*doc), "A/B/C")) cout << eC -> Name() << " = " << text (eC) << endl; } catch (tinyxml2::XmlException & e) { cout << "XmlException caught" << e .what() << endl; } cout << "----" << endl << endl; // 3) simple tixml2ex element iterator : 18 lines of code cout << endl << "3) <C> element children of <B> element children of the document element <A>" << endl << "simple tixml2ex element iterator" << endl; try { auto doc = tinyxml2::load_document (testXml); auto eA = doc -> FirstChildElement(); if (eA) for (auto eB : eA) { // just for fun, use standard algorithm for_each to iterate over the children of <B> for_each (cbegin (eB), cend (eB), [](auto e) { // simple iterators are just that, they iterate over all children // therefore we must test element name (type) to examine only <C> elements if (strcmp (e -> Name(), "C") == 0) cout << e -> Name() << " = " << text (e) << endl; }); } } catch (tinyxml2::XmlException & e) { cout << "XmlException caught" << e .what() << endl; } cout << "=================================================" << endl << endl; // additional element selection and iteration using XPath syntax // illustrating helper functions try { auto doc = tinyxml2::load_document (testXml); // find first matching an element in the document cout << "find an element by attribute value" << endl; auto bThree = find_element (static_cast<const tinyxml2::XMLDocument &>(*doc), "A/B[@id='three']"s); cout << attribute_value (bThree, "id"s) << " - " << attribute_value (bThree, "org"s) << endl; cout << "=================================================" << endl << endl; // find the first instance of a child element of the selected type cout << "get description attribute of <D> element" << endl; if (auto ch1 = find_element (bThree, "D"s)) cout << attribute_value (ch1, "description"s) << text (ch1) << endl << endl; cout << "=================================================" << endl << endl; // iterate over all <C> children of selected <B> cout << "iterate over all <C> children of selected <B>" << endl; for (auto cc : tinyxml2::selection (bThree, "C"s)) { cout << cc -> Parent() -> ToElement() -> Name() << "[" << attribute_value (cc -> Parent() -> ToElement(), "id") << "] / " << cc -> Name() << "[@code='"; if (!attribute_value (cc, "code") .empty()) cout << attribute_value (cc, "code"); else cout << "**element has no attribute - code**"; cout << "']" << endl; } cout << "=================================================" << endl << endl; // iterate over all elements in the document along the selected path by starting with '/' // note that because path starts from the document, bThree is used only as an element in the document not the root of the search cout << "iterate over all <C> children : /A/B[@id='three']/C" << endl; int nC = 0; for (auto cc : tinyxml2::selection (bThree, "/A/B[@id='three']/C"s)) { ++nC; cout << cc -> Parent() -> ToElement() -> Name() << "[" << attribute_value (cc -> Parent() -> ToElement(), "id") << "] / " << cc -> Name() << "[@code='"; if (!attribute_value (cc, "code") .empty()) cout << attribute_value (cc, "code"); else cout << "**element has no attribute - code**"; cout << "']" << endl; } cout << nC << " Cs in B[@id='three']" << endl << endl; cout << "=================================================" << endl << endl; // iterate over all children, any name (type), with code attribute value cout << "iterate over all children of any name (type) : /A/B/[@code='9ABC']" << endl; for (auto cc : tinyxml2::selection (bThree, "/A/B/[@code='9ABC']"s)) { cout << cc -> Parent() -> ToElement() -> Name() << "[" << attribute_value (cc -> Parent() -> ToElement(), "id") << "] / " << cc -> Name() << "[@code='"; if (!attribute_value (cc, "code") .empty()) cout << attribute_value (cc, "code"); else cout << "**element has no attribute - code**"; cout << "']" << endl; } cout << "=================================================" << endl << endl; // find the first instance of a child element of the selected type with a matching attribute value cout << "find C[@code='9ABC'] within B[@id='three']" << endl; if (auto cc = find_element (bThree, "C[@code='9ABC']"s)) cout << text (cc) << " , " << attribute_value (cc, "description") << endl << endl; else cout << "could not find C[@code='9ABC'] in B" << endl; cout << "=================================================" << endl << endl; // find the same element within document cout << "find B[@id='three']/C[@code='9ABC']" << endl; if (auto cc = find_element (*doc, "/A/B[@id='three']/C[@code='9ABC']"s)) cout << text (cc) << " , " << attribute_value (cc, "description") << endl << endl; else cout << "could not find A/B[@id='three']/C[@code='9ABC'] in document" << endl; cout << "=================================================" << endl << endl; // iterate over all children, any name (type), of <B> elements which are children of the document element cout << "iterate over all children, any name (type), of <B> elements which are children of the document element" << endl; auto eA = doc -> FirstChildElement(); for (auto cd : tinyxml2::selection (eA, "B/")) cout << cd -> Name() << " = " << text (cd) << " id=" << attribute_value (cd, "id") << endl; cout << "=================================================" << endl << endl; } catch (tinyxml2::XmlException & e) { cout << e .what() << endl; } /////////////////////// modify the document try { auto doc = tinyxml2::load_document (testXml); // create new CZ element in branch below selected <C> element with new CX and new CY auto ne = append_element (find_element (*doc, "/A/B[@id='three']/C[@code='9ABC']"s), "CX/CY[@id='099']/CZ", {{"id"s, "0998"s}, {"code"s, "ASDF"s}}, "magnum"s); // now use the inserted element to insert another after it auto czId {"1233"s}; auto czCode {"ZXCV"s}; auto czData {"corneto"s}; insert_next_element (ne, "CZ", {{"id"s, czId}, {"code"s, czCode}}, czData); // todo: // what do we want find_element to do when path is empty? // . find the first child element (which is what it does now) ? // . or simply return the parent element passed in ? tinyxml2::XMLPrinter printer; doc -> Print (&printer); cout << printer .CStr() << endl; } catch (tinyxml2::XmlException & e) { cout << e .what() << endl; } /////////////////////// copy try { auto source = tinyxml2::load_document (testXml); auto dest = std::make_unique <tinyxml2::XMLDocument>(); auto e = dest -> NewElement ("mycopy"); dest -> InsertEndChild (e); xcopy (source -> FirstChildElement(), e, {{"extern", "internal"}, {"B4", "Bee Four"}}); tinyxml2::XMLPrinter printer; dest -> Print (&printer); cout << printer .CStr() << endl; } catch (tinyxml2::XmlException & e) { cout << e .what() << endl; } // hold console window open so we can see the output std::cout << "hit any key to close" << std::endl; auto c = _getch(); return 0; } <|endoftext|>
<commit_before>#include <network/Client.h> #include <network/Protocol.h> #include <network/Server.h> #include <iostream> #include <string> class TestProtocol : public network::Protocol { public: class Listener { public: virtual ~Listener() {} virtual void onPongRecv() = 0; }; TestProtocol(network::MessageIO& messageIO, Listener* l) : network::Protocol(messageIO), mListener(l) { } virtual ~TestProtocol() {} void sendPing() { sendMessage(PING,"Ping",-1); } void sendPong() { sendMessage(PONG,"Pong",-1); } private: enum MessageType { PING = 0, PONG }; virtual void message(const network::Message& message) override { switch (message.type()) { case MessageType::PING: std::cout << "Ping received" << std::endl; sendPong(); break; case MessageType::PONG: std::cout << "Pong received" << std::endl; if (mListener != nullptr) { mListener->onPongRecv(); } break; } } Listener* mListener; }; class TestProtocolListener : public TestProtocol::Listener { public: virtual ~TestProtocolListener() {} virtual void onPongRecv() override { network::IOServiceManager::get().stop(); } }; class TestSession : public network::Session { public: TestSession() : mProtocol(*this, nullptr) { } private: TestProtocol mProtocol; }; void usage() { std::cout << "Usage: network-test server <port> | client <ip>" << " <port>" << std::endl; } int main(int argc, char* argv[]) { // validate input if (argc < 2) { usage(); return -1; } std::string action(argv[1]); if (action == "server" && argc != 3) { usage(); return -1; } if (action == "client" && argc != 4) { usage(); return -1; } if (action == "server") { auto port = atoi(argv[2]); network::Server<TestSession> server(port); network::IOServiceManager::get().run(); } else if (action == "client") { std::string ip(argv[2]); std::string port(argv[3]); network::Client client(ip, port); TestProtocolListener listener; TestProtocol protocol{client, &listener}; protocol.sendPing(); network::IOServiceManager::get().run(); } else { usage(); return -1; } return 0; } <commit_msg>Increase example to 100 pings<commit_after>#include <network/Client.h> #include <network/Protocol.h> #include <network/Server.h> #include <iostream> #include <string> const auto PING_COUNT = 100; class TestProtocol : public network::Protocol { public: class Listener { public: virtual ~Listener() {} virtual void onPongRecv() = 0; }; TestProtocol(network::MessageIO& messageIO, Listener* l) : network::Protocol(messageIO), mListener(l) { } virtual ~TestProtocol() {} void sendPing() { sendMessage(PING,"Ping",-1); } void sendPong() { sendMessage(PONG,"Pong",-1); } private: enum MessageType { PING = 0, PONG }; virtual void message(network::Message&& message) override { switch (message.type()) { case MessageType::PING: std::cout << "Ping received" << std::endl; sendPong(); break; case MessageType::PONG: std::cout << "Pong received" << std::endl; if (mListener != nullptr) { mListener->onPongRecv(); } break; } } Listener* mListener; }; class TestProtocolListener : public TestProtocol::Listener { public: virtual ~TestProtocolListener() {} virtual void onPongRecv() override { mRecCount++; if (mRecCount == PING_COUNT) { network::IOServiceManager::get().stop(); } } private: int mRecCount = 0; }; class TestSession : public network::Session { public: TestSession() : mProtocol(*this, nullptr) { } private: TestProtocol mProtocol; }; void usage() { std::cout << "Usage: network-test server <port> | client <ip>" << " <port>" << std::endl; } void iothread() { network::IOServiceManager::get().run(); } int main(int argc, char* argv[]) { // validate input if (argc < 2) { usage(); return -1; } std::string action(argv[1]); if (action == "server" && argc != 3) { usage(); return -1; } if (action == "client" && argc != 4) { usage(); return -1; } if (action == "server") { auto port = atoi(argv[2]); network::Server<TestSession> server(port); std::thread t(iothread); if (t.joinable()) { t.join(); } } else if (action == "client") { std::string ip(argv[2]); std::string port(argv[3]); network::Client client(ip, port); TestProtocolListener listener; TestProtocol protocol{client, &listener}; std::thread t(iothread); for (auto i = 0; i < PING_COUNT; i++) { protocol.sendPing(); } if (t.joinable()) { t.join(); } } else { usage(); return -1; } return 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006-2012, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <Context.h> #include <RX.h> #include <cmake.h> #include <test.h> Context context; int main (int argc, char** argv) { UnitTest ut (23); std::string text = "This is a test."; RX r1 ("i. ", true); ut.ok (r1.match (text), text + " =~ /i. /"); std::vector <std::string> matches; ut.ok (r1.match (matches, text), text + " =~ /i. /"); ut.ok (matches.size () == 2, "2 match"); ut.is (matches[0], "is ", "$1 == is\\s"); ut.is (matches[1], "is ", "$1 == is\\s"); text = "abcdefghijklmnopqrstuvwxyz"; RX r3 ("t..", true); ut.ok (r3.match (text), "t.."); RX r4 ("T..", false); ut.ok (r4.match (text), "T.."); RX r5 ("T..", true); ut.ok (!r5.match (text), "! T.."); text = "this is a test of the regex engine."; // |...:....|....:....|....:....|....: RX r6 ("^this"); ut.ok (r6.match (text), "^this matches"); RX r7 ("engine\\.$"); ut.ok (r7.match (text), "engine\\.$ matches"); std::vector <std::string> results; std::vector <int> start; std::vector <int> end; RX r8 ("e..", true); ut.ok (r8.match (results, text), "e.. there are matches"); ut.ok (r8.match (start, end, text), "e.. there are matches"); ut.is (results.size (), (size_t) 4, "e.. == 4 matches"); ut.is (results[0], "est", "e..[0] == 'est'"); ut.is (start[0], 11, "e..[0] == 11->"); ut.is (end[0], 14, "e..[0] == ->14"); results.clear (); RX r9 ("e", true); ut.ok (r9.match (results, text), "e there are matches"); ut.is (results.size (), (size_t) 6, "e == 6 matches"); start.clear (); end.clear (); ut.ok (r9.match (start, end, text), "e there are matches"); ut.is (start.size (), (size_t) 6, "e == 6 matches"); #ifdef DARWIN text = "this is the end."; ut.pass (text + " =~ /\\bthe/"); ut.pass (text + " =~ /the\\b/"); ut.pass (text + " =~ /\\bthe\\b/"); #else #ifdef SOLARIS RX r10 ("\\<the"); text = "this is the end."; ut.ok (r10.match (text), text + " =~ /\\<the/"); RX r11 ("the\\>"); ut.ok (r11.match (text), text + " =~ /the\\>/"); RX r12 ("\\<the\\>"); ut.ok (r12.match (text), text + " =~ /\\<the\\>/"); #else RX r10 ("\\bthe"); text = "this is the end."; ut.ok (r10.match (text), text + " =~ /\\bthe/"); RX r11 ("the\\b"); ut.ok (r11.match (text), text + " =~ /the\\b/"); RX r12 ("\\bthe\\b"); ut.ok (r12.match (text), text + " =~ /\\bthe\\b/"); #endif #endif return 0; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Unit Tests<commit_after>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006-2012, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <Context.h> #include <RX.h> #include <cmake.h> #include <test.h> Context context; int main (int argc, char** argv) { UnitTest ut (23); std::string text = "This is a test."; RX r1 ("i. ", true); ut.ok (r1.match (text), text + " =~ /i. /"); std::vector <std::string> matches; ut.ok (r1.match (matches, text), text + " =~ /i. /"); ut.ok (matches.size () == 2, "2 match"); ut.is (matches[0], "is ", "$1 == is\\s"); ut.is (matches[1], "is ", "$1 == is\\s"); text = "abcdefghijklmnopqrstuvwxyz"; RX r3 ("t..", true); ut.ok (r3.match (text), "t.."); RX r4 ("T..", false); ut.ok (r4.match (text), "T.."); RX r5 ("T..", true); ut.ok (!r5.match (text), "! T.."); text = "this is a test of the regex engine."; // |...:....|....:....|....:....|....: RX r6 ("^this"); ut.ok (r6.match (text), "^this matches"); RX r7 ("engine\\.$"); ut.ok (r7.match (text), "engine\\.$ matches"); std::vector <std::string> results; std::vector <int> start; std::vector <int> end; RX r8 ("e..", true); ut.ok (r8.match (results, text), "e.. there are matches"); ut.ok (r8.match (start, end, text), "e.. there are matches"); ut.is (results.size (), (size_t) 4, "e.. == 4 matches"); ut.is (results[0], "est", "e..[0] == 'est'"); ut.is (start[0], 11, "e..[0] == 11->"); ut.is (end[0], 14, "e..[0] == ->14"); results.clear (); RX r9 ("e", true); ut.ok (r9.match (results, text), "e there are matches"); ut.is (results.size (), (size_t) 6, "e == 6 matches"); start.clear (); end.clear (); ut.ok (r9.match (start, end, text), "e there are matches"); ut.is (start.size (), (size_t) 6, "e == 6 matches"); #if defined(DARWIN) || defined(CYGWIN) || defined(FREEBSD) text = "this is the end."; ut.pass (text + " =~ /\\bthe/"); ut.pass (text + " =~ /the\\b/"); ut.pass (text + " =~ /\\bthe\\b/"); #else #ifdef SOLARIS RX r10 ("\\<the"); text = "this is the end."; ut.ok (r10.match (text), text + " =~ /\\<the/"); RX r11 ("the\\>"); ut.ok (r11.match (text), text + " =~ /the\\>/"); RX r12 ("\\<the\\>"); ut.ok (r12.match (text), text + " =~ /\\<the\\>/"); #else RX r10 ("\\bthe"); text = "this is the end."; ut.ok (r10.match (text), text + " =~ /\\bthe/"); RX r11 ("the\\b"); ut.ok (r11.match (text), text + " =~ /the\\b/"); RX r12 ("\\bthe\\b"); ut.ok (r12.match (text), text + " =~ /\\bthe\\b/"); #endif #endif return 0; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before><commit_msg>Added some comments and fixed formatting<commit_after><|endoftext|>
<commit_before>/** * Copyright © 2016 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../manager.hpp" #include "../config.h" #include <cassert> #include <iostream> #include <algorithm> #include <thread> constexpr auto SERVICE = "phosphor.inventory.test"; constexpr auto INTERFACE = IFACE; constexpr auto ROOT = "/testing/inventory"; /** @class SignalQueue * @brief Store DBus signals in a queue. */ class SignalQueue { public: ~SignalQueue() = default; SignalQueue() = delete; SignalQueue(const SignalQueue&) = delete; SignalQueue(SignalQueue&&) = default; SignalQueue& operator=(const SignalQueue&) = delete; SignalQueue& operator=(SignalQueue&&) = default; explicit SignalQueue(const std::string& match) : _bus(sdbusplus::bus::new_default()), _match(_bus, match.c_str(), &callback, this), _next(nullptr) { } auto&& pop(unsigned timeout = 1000000) { while (timeout > 0 && !_next) { _bus.process_discard(); _bus.wait(50000); timeout -= 50000; } return std::move(_next); } private: static int callback(sd_bus_message* m, void* context, sd_bus_error*) { auto* me = static_cast<SignalQueue*>(context); sd_bus_message_ref(m); sdbusplus::message::message msg{m}; me->_next = std::move(msg); return 0; } sdbusplus::bus::bus _bus; sdbusplus::server::match::match _match; sdbusplus::message::message _next; }; template <typename ...T> using Object = std::map < std::string, std::map < std::string, sdbusplus::message::variant<T... >>>; /**@brief Find a subset of interfaces and properties in an object. */ template <typename ...T> auto hasProperties(const Object<T...>& l, const Object<T...>& r) { Object<T...> result; std::set_difference( r.cbegin(), r.cend(), l.cbegin(), l.cend(), std::inserter(result, result.end())); return result.empty(); } /**@brief Check an object for one or more interfaces. */ template <typename ...T> auto hasInterfaces(const std::vector<std::string>& l, const Object<T...>& r) { std::vector<std::string> stripped, interfaces; std::transform( r.cbegin(), r.cend(), std::back_inserter(stripped), [](auto & p) { return p.first; }); std::set_difference( stripped.cbegin(), stripped.cend(), l.cbegin(), l.cend(), std::back_inserter(interfaces)); return interfaces.empty(); } void runTests(phosphor::inventory::manager::Manager& mgr) { const std::string root{ROOT}; auto b = sdbusplus::bus::new_default(); auto notify = [&]() { return b.new_method_call( SERVICE, ROOT, INTERFACE, "Notify"); }; auto set = [&](const std::string & path) { return b.new_method_call( SERVICE, path.c_str(), "org.freedesktop.DBus.Properties", "Set"); }; Object<std::string> obj { { "xyz.openbmc_project.Example.Iface1", {{"ExampleProperty1", "test1"}} }, { "xyz.openbmc_project.Example.Iface2", {{"ExampleProperty2", "test2"}} }, }; // Make sure the notify method works. { sdbusplus::message::object_path relPath{"/foo"}; std::string path(root + relPath.str); SignalQueue queue( "path='" + root + "',member='InterfacesAdded'"); auto m = notify(); m.append(relPath); m.append(obj); b.call(m); auto sig{queue.pop()}; assert(sig); sdbusplus::message::object_path signalPath; Object<std::string> signalObject; sig.read(signalPath); assert(path == signalPath); sig.read(signalObject); assert(hasProperties(signalObject, obj)); auto moreSignals{queue.pop()}; assert(!moreSignals); } // Make sure DBus signals are handled. { sdbusplus::message::object_path relDeleteMeOne{"/deleteme1"}; sdbusplus::message::object_path relDeleteMeTwo{"/deleteme2"}; sdbusplus::message::object_path relTriggerOne{"/trigger1"}; std::string deleteMeOne{root + relDeleteMeOne.str}; std::string deleteMeTwo{root + relDeleteMeTwo.str}; std::string triggerOne{root + relTriggerOne.str}; // Create some objects to be deleted by an action. { auto m = notify(); m.append(relDeleteMeOne); m.append(obj); b.call(m); } { auto m = notify(); m.append(relDeleteMeTwo); m.append(obj); b.call(m); } // Create the triggering object. { auto m = notify(); m.append(relTriggerOne); m.append(obj); b.call(m); } // Set a property that should not trigger due to a filter. { SignalQueue queue( "path='" + root + "',member='InterfacesRemoved'"); auto m = set(triggerOne); m.append("xyz.openbmc_project.Example.Iface2"); m.append("ExampleProperty2"); m.append(sdbusplus::message::variant<std::string>("abc123")); b.call(m); auto sig{queue.pop()}; assert(!sig); } // Set a property that should trigger. { SignalQueue queue( "path='" + root + "',member='InterfacesRemoved'"); auto m = set(triggerOne); m.append("xyz.openbmc_project.Example.Iface2"); m.append("ExampleProperty2"); m.append(sdbusplus::message::variant<std::string>("xxxyyy")); b.call(m); sdbusplus::message::object_path sigpath; std::vector<std::string> interfaces; { std::vector<std::string> interfaces; auto sig{queue.pop()}; assert(sig); sig.read(sigpath); assert(sigpath == deleteMeOne); sig.read(interfaces); std::sort(interfaces.begin(), interfaces.end()); assert(hasInterfaces(interfaces, obj)); } { std::vector<std::string> interfaces; auto sig{queue.pop()}; assert(sig); sig.read(sigpath); assert(sigpath == deleteMeTwo); sig.read(interfaces); std::sort(interfaces.begin(), interfaces.end()); assert(hasInterfaces(interfaces, obj)); } { // Make sure there were only two signals. auto sig{queue.pop()}; assert(!sig); } } } // Validate the set property action. { sdbusplus::message::object_path relChangeMe{"/changeme"}; sdbusplus::message::object_path relTriggerTwo{"/trigger2"}; std::string changeMe{root + relChangeMe.str}; std::string triggerTwo{root + relTriggerTwo.str}; // Create an object to be updated by the set property action. { auto m = notify(); m.append(relChangeMe); m.append(obj); b.call(m); } // Create the triggering object. { auto m = notify(); m.append(relTriggerTwo); m.append(obj); b.call(m); } // Trigger and validate the change. { SignalQueue queue( "path='" + changeMe + "',member='PropertiesChanged'"); auto m = set(triggerTwo); m.append("xyz.openbmc_project.Example.Iface2"); m.append("ExampleProperty2"); m.append(sdbusplus::message::variant<std::string>("yyyxxx")); b.call(m); std::string sigInterface; std::map < std::string, sdbusplus::message::variant<std::string >> sigProperties; { std::vector<std::string> interfaces; auto sig{queue.pop()}; sig.read(sigInterface); assert(sigInterface == "xyz.openbmc_project.Example.Iface1"); sig.read(sigProperties); assert(sigProperties["ExampleProperty1"] == "changed"); } } } mgr.shutdown(); std::cout << "Success!" << std::endl; } int main() { phosphor::inventory::manager::Manager mgr( sdbusplus::bus::new_default(), SERVICE, ROOT, INTERFACE); auto f = [](auto mgr) { mgr->run(); }; auto t = std::thread(f, &mgr); runTests(mgr); // Wait for server thread to exit. t.join(); return 0; } // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 <commit_msg>Fix build failure<commit_after>/** * Copyright © 2016 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../manager.hpp" #include "../config.h" #include <cassert> #include <iostream> #include <algorithm> #include <thread> constexpr auto SERVICE = "phosphor.inventory.test"; constexpr auto INTERFACE = IFACE; constexpr auto ROOT = "/testing/inventory"; /** @class SignalQueue * @brief Store DBus signals in a queue. */ class SignalQueue { public: ~SignalQueue() = default; SignalQueue() = delete; SignalQueue(const SignalQueue&) = delete; SignalQueue(SignalQueue&&) = default; SignalQueue& operator=(const SignalQueue&) = delete; SignalQueue& operator=(SignalQueue&&) = default; explicit SignalQueue(const std::string& match) : _bus(sdbusplus::bus::new_default()), _match(_bus, match.c_str(), &callback, this), _next(nullptr) { } auto&& pop(unsigned timeout = 1000000) { while (timeout > 0 && !_next) { _bus.process_discard(); _bus.wait(50000); timeout -= 50000; } return std::move(_next); } private: static int callback(sd_bus_message* m, void* context, sd_bus_error*) { auto* me = static_cast<SignalQueue*>(context); sd_bus_message_ref(m); sdbusplus::message::message msg{m}; me->_next = std::move(msg); return 0; } sdbusplus::bus::bus _bus; sdbusplus::server::match::match _match; sdbusplus::message::message _next; }; template <typename ...T> using Object = std::map < std::string, std::map < std::string, sdbusplus::message::variant<T... >>>; /**@brief Find a subset of interfaces and properties in an object. */ template <typename ...T> auto hasProperties(const Object<T...>& l, const Object<T...>& r) { Object<T...> result; std::set_difference( r.cbegin(), r.cend(), l.cbegin(), l.cend(), std::inserter(result, result.end())); return result.empty(); } /**@brief Check an object for one or more interfaces. */ template <typename ...T> auto hasInterfaces(const std::vector<std::string>& l, const Object<T...>& r) { std::vector<std::string> stripped, interfaces; std::transform( r.cbegin(), r.cend(), std::back_inserter(stripped), [](auto & p) { return p.first; }); std::set_difference( stripped.cbegin(), stripped.cend(), l.cbegin(), l.cend(), std::back_inserter(interfaces)); return interfaces.empty(); } void runTests(phosphor::inventory::manager::Manager& mgr) { const std::string root{ROOT}; auto b = sdbusplus::bus::new_default(); auto notify = [&]() { return b.new_method_call( SERVICE, ROOT, INTERFACE, "Notify"); }; auto set = [&](const std::string & path) { return b.new_method_call( SERVICE, path.c_str(), "org.freedesktop.DBus.Properties", "Set"); }; Object<std::string> obj { { "xyz.openbmc_project.Example.Iface1", {{"ExampleProperty1", "test1"}} }, { "xyz.openbmc_project.Example.Iface2", {{"ExampleProperty2", "test2"}} }, }; // Make sure the notify method works. { sdbusplus::message::object_path relPath{"/foo"}; std::string path(root + relPath.str); SignalQueue queue( "path='" + root + "',member='InterfacesAdded'"); auto m = notify(); m.append(relPath); m.append(obj); b.call(m); auto sig{queue.pop()}; assert(sig); sdbusplus::message::object_path signalPath; Object<std::string> signalObject; sig.read(signalPath); assert(path == signalPath.str); sig.read(signalObject); assert(hasProperties(signalObject, obj)); auto moreSignals{queue.pop()}; assert(!moreSignals); } // Make sure DBus signals are handled. { sdbusplus::message::object_path relDeleteMeOne{"/deleteme1"}; sdbusplus::message::object_path relDeleteMeTwo{"/deleteme2"}; sdbusplus::message::object_path relTriggerOne{"/trigger1"}; std::string deleteMeOne{root + relDeleteMeOne.str}; std::string deleteMeTwo{root + relDeleteMeTwo.str}; std::string triggerOne{root + relTriggerOne.str}; // Create some objects to be deleted by an action. { auto m = notify(); m.append(relDeleteMeOne); m.append(obj); b.call(m); } { auto m = notify(); m.append(relDeleteMeTwo); m.append(obj); b.call(m); } // Create the triggering object. { auto m = notify(); m.append(relTriggerOne); m.append(obj); b.call(m); } // Set a property that should not trigger due to a filter. { SignalQueue queue( "path='" + root + "',member='InterfacesRemoved'"); auto m = set(triggerOne); m.append("xyz.openbmc_project.Example.Iface2"); m.append("ExampleProperty2"); m.append(sdbusplus::message::variant<std::string>("abc123")); b.call(m); auto sig{queue.pop()}; assert(!sig); } // Set a property that should trigger. { SignalQueue queue( "path='" + root + "',member='InterfacesRemoved'"); auto m = set(triggerOne); m.append("xyz.openbmc_project.Example.Iface2"); m.append("ExampleProperty2"); m.append(sdbusplus::message::variant<std::string>("xxxyyy")); b.call(m); sdbusplus::message::object_path sigpath; std::vector<std::string> interfaces; { std::vector<std::string> interfaces; auto sig{queue.pop()}; assert(sig); sig.read(sigpath); assert(sigpath == deleteMeOne); sig.read(interfaces); std::sort(interfaces.begin(), interfaces.end()); assert(hasInterfaces(interfaces, obj)); } { std::vector<std::string> interfaces; auto sig{queue.pop()}; assert(sig); sig.read(sigpath); assert(sigpath == deleteMeTwo); sig.read(interfaces); std::sort(interfaces.begin(), interfaces.end()); assert(hasInterfaces(interfaces, obj)); } { // Make sure there were only two signals. auto sig{queue.pop()}; assert(!sig); } } } // Validate the set property action. { sdbusplus::message::object_path relChangeMe{"/changeme"}; sdbusplus::message::object_path relTriggerTwo{"/trigger2"}; std::string changeMe{root + relChangeMe.str}; std::string triggerTwo{root + relTriggerTwo.str}; // Create an object to be updated by the set property action. { auto m = notify(); m.append(relChangeMe); m.append(obj); b.call(m); } // Create the triggering object. { auto m = notify(); m.append(relTriggerTwo); m.append(obj); b.call(m); } // Trigger and validate the change. { SignalQueue queue( "path='" + changeMe + "',member='PropertiesChanged'"); auto m = set(triggerTwo); m.append("xyz.openbmc_project.Example.Iface2"); m.append("ExampleProperty2"); m.append(sdbusplus::message::variant<std::string>("yyyxxx")); b.call(m); std::string sigInterface; std::map < std::string, sdbusplus::message::variant<std::string >> sigProperties; { std::vector<std::string> interfaces; auto sig{queue.pop()}; sig.read(sigInterface); assert(sigInterface == "xyz.openbmc_project.Example.Iface1"); sig.read(sigProperties); assert(sigProperties["ExampleProperty1"] == "changed"); } } } mgr.shutdown(); std::cout << "Success!" << std::endl; } int main() { phosphor::inventory::manager::Manager mgr( sdbusplus::bus::new_default(), SERVICE, ROOT, INTERFACE); auto f = [](auto mgr) { mgr->run(); }; auto t = std::thread(f, &mgr); runTests(mgr); // Wait for server thread to exit. t.join(); return 0; } // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 <|endoftext|>
<commit_before>#define gtf_HEADER_ONLY #include "../iutest/include/iutest.hpp" #include "../src/system/task.h" #include <vector> using namespace gtf; IUTEST_MAKE_PEEP(weak_ptr<TaskBase> (TaskManager::*)(unsigned int) const, TaskManager, FindTask); IUTEST_MAKE_PEEP(weak_ptr<BackgroundTaskBase> (TaskManager::*)(unsigned int) const, TaskManager, FindBGTask); static std::vector<int> veve; template<typename T, class B> class CTekitou : public B { public: CTekitou(T init) : hogehoge(init) { } ~CTekitou() {} T hogehoge; unsigned int GetID() const override { return hogehoge; } int GetDrawPriority() const override { return 1; } void Draw() override { veve.push_back(hogehoge); } }; template<typename T, class B, typename... Arg> class CTekitou2 : public B { public: CTekitou2(T init, Arg&&... args) : B(forward<Arg>(args)...), hogehoge(init) { } ~CTekitou2() {} T hogehoge; bool Execute(double /* e */) override{ veve.push_back(hogehoge); return true; } unsigned int GetID()const override{ return hogehoge; } }; template<typename T, typename... Arg> class CExTaskSelfDestruct : public ExclusiveTaskBase { public: CExTaskSelfDestruct(T init, Arg&&... args) : ExclusiveTaskBase(forward<Arg>(args)...), hogehoge(init) { } ~CExTaskSelfDestruct() {} T hogehoge; bool Execute(double /* e */) override{ veve.push_back(hogehoge); return false; } unsigned int GetID()const override{ return hogehoge; } }; IUTEST(gtfTest, TestMethod1) { TaskManager task; auto ptr = task.AddNewTask< CTekitou<int, TaskBase> >(1); IUTEST_ASSERT_EQ((void*)IUTEST_PEEP_GET(task, TaskManager, FindTask)(ptr->GetID()).lock().get(), (void*)ptr.get()); IUTEST_ASSERT_EQ((void*)task.FindTask<TaskBase>(ptr->GetID()).get(), (void*)ptr.get()); } IUTEST(gtfTest, TestMethod2) { TaskManager task; auto ptr = task.AddNewTask< CTekitou2<int, BackgroundTaskBase> >(1); IUTEST_ASSERT_EQ((void*)(task.FindTask<BackgroundTaskBase>(ptr->GetID())).get(), (void*)ptr.get()); } IUTEST(gtfTest, TestMethod3) { TaskManager task; auto ptr = task.AddNewTask< CTekitou2<int, ExclusiveTaskBase> >(1); IUTEST_ASSERT_NE((void*)IUTEST_PEEP_GET(task, TaskManager, FindTask)(ptr->GetID()).lock().get(), (void*)ptr.get()); } IUTEST(gtfTest, RunOrder1) { TaskManager task; veve.clear(); auto ptr = task.AddNewTask< CTekitou2<int, ExclusiveTaskBase> >(1); auto ptr2 = task.AddNewTask< CTekitou2<int, TaskBase> >(2); //modify veve task.Execute(0); task.Execute(1); IUTEST_ASSERT_EQ(1, veve[0]); IUTEST_ASSERT_EQ(1, veve[1]); } IUTEST(gtfTest, RunOrder2) { static TaskManager task; class ct : public CTekitou2 < int, ExclusiveTaskBase > { public: ct(int init) : CTekitou2 < int, ExclusiveTaskBase >(init) {} void Initialize() { task.AddNewTask< CTekitou2<int, TaskBase> >(2); } }; veve.clear(); auto ptr = task.AddNewTask<ct>(1); task.Execute(0); task.Execute(1); IUTEST_ASSERT_EQ(1, veve[0]); IUTEST_ASSERT_EQ(2, veve[1]); } IUTEST(gtfTest, Draw1) { static TaskManager task; class ct2 : public CTekitou2 < int, ExclusiveTaskBase > { public: ct2(int init) : CTekitou2 < int, ExclusiveTaskBase >(init) { } void Initialize() { task.AddNewTask< CTekitou<int, TaskBase> >(hogehoge + 1); } }; for (int i = 1; i < 257; i++) { task.AddNewTask<ct2>(i * 2); task.Execute(0); } veve.clear(); task.RemoveTaskByID(1); for (int i = 0; i < 4; i++) task.Draw(); IUTEST_ASSERT_EQ(513, veve[0]); } IUTEST(gtfTest, Draw2) { static TaskManager task; class ct2 : public CTekitou2 < int, ExclusiveTaskBase > { public: ct2(int init) : CTekitou2 < int, ExclusiveTaskBase >(init) { } void Initialize() { task.AddNewTask< CTekitou<int, BackgroundTaskBase> >(hogehoge + 1); } }; for (int i = 1; i < 5; i++) { task.AddNewTask<ct2>(i * 2); task.Execute(0); } veve.clear(); task.RemoveTaskByID(1); for (int i = 0; i < 4; i++) task.Draw(); IUTEST_ASSERT_EQ(3, veve[0]); } IUTEST(gtfTest, DrawFallthrough) { static TaskManager task; class ct2 : public CTekitou2 < int, ExclusiveTaskBase, bool > { public: ct2(int init) : CTekitou2 < int, ExclusiveTaskBase, bool >(init, true) { } void Initialize() { task.AddNewTask< CTekitou<int, TaskBase> >(hogehoge + 1); } }; for (int i = 1; i < 5; i++) { task.AddNewTask<ct2>(i * 2); task.Execute(0); } veve.clear(); task.RemoveTaskByID(1); for (int i = 0; i < 4; i++) task.Draw(); IUTEST_ASSERT_EQ(3, veve[0]); } IUTEST(gtfTest, TaskDependency) { static TaskManager task; class ct : public CTekitou2 < int, ExclusiveTaskBase > { public: ct(int init) : CTekitou2 < int, ExclusiveTaskBase >(init) { } void Initialize() { task.AddNewTask< CTekitou2<int, TaskBase> >(hogehoge + 20); } virtual bool Inactivate(unsigned int /* nextTaskID */){ return true; }//!< 他の排他タスクが開始したときに呼ばれる }; veve.clear(); auto ptr = task.AddNewTask<ct>(1); task.Execute(0); auto ptr2 = task.AddNewTask<ct>(3); task.Execute(1); IUTEST_ASSERT_EQ(1, veve[0]); IUTEST_ASSERT_EQ(1 + 20, veve[1]); IUTEST_ASSERT_EQ(3, veve[2]); IUTEST_ASSERT_EQ(3 + 20, veve[3]); task.RevertExclusiveTaskByID(1); task.Execute(3); IUTEST_ASSERT_EQ(1, veve[4]); IUTEST_ASSERT_EQ(1 + 20, veve[5]); ptr2 = task.AddNewTask<ct>(4); task.Execute(4); task.RemoveTaskByID(21); task.Execute(5); IUTEST_ASSERT_EQ(4, veve[8]); IUTEST_ASSERT_EQ(4 + 20, veve[9]); } IUTEST(gtfTest, ReuseContainer) { TaskManager task; auto ptr = task.AddNewTask< CTekitou2<int, ExclusiveTaskBase> >(1); IUTEST_ASSERT_NE((void*)IUTEST_PEEP_GET(task, TaskManager, FindTask)(ptr->GetID()).lock().get(), (void*)ptr.get()); task.Destroy(); task.Execute(0); IUTEST_ASSERT_EQ((void*)task.GetTopExclusiveTask().lock().get(), (void*)nullptr); auto ptr3 = task.AddNewTask< CTekitou2<int, ExclusiveTaskBase> >(1); task.Execute(0); IUTEST_ASSERT_NE((void*)IUTEST_PEEP_GET(task, TaskManager, FindTask)(ptr3->GetID()).lock().get(), (void*)ptr3.get()); } IUTEST(gtfTest, ExTaskSelfDeestruct) { TaskManager task; veve.clear(); auto ptr = task.AddNewTask< CTekitou2<int, ExclusiveTaskBase> >(1); task.Execute(0); auto ptr2 = task.AddNewTask< CExTaskSelfDestruct<int> >(2); task.Execute(0); task.Execute(0); IUTEST_ASSERT_EQ(1, veve[0]); IUTEST_ASSERT_EQ(2, veve[1]); IUTEST_ASSERT_EQ(1, veve[2]); } int main(int argc, char** argv) { IUTEST_INIT(&argc, argv); return IUTEST_RUN_ALL_TESTS(); } <commit_msg>fix(test): fixed overload<commit_after>#define gtf_HEADER_ONLY #include "../iutest/include/iutest.hpp" #include "../src/system/task.h" #include <vector> using namespace gtf; IUTEST_MAKE_PEEP(weak_ptr<BackgroundTaskBase> (TaskManager::*)(unsigned int) const, TaskManager, FindBGTask); static std::vector<int> veve; template<typename T, class B> class CTekitou : public B { public: CTekitou(T init) : hogehoge(init) { } ~CTekitou() {} T hogehoge; unsigned int GetID() const override { return hogehoge; } int GetDrawPriority() const override { return 1; } void Draw() override { veve.push_back(hogehoge); } }; template<typename T, class B, typename... Arg> class CTekitou2 : public B { public: CTekitou2(T init, Arg&&... args) : B(forward<Arg>(args)...), hogehoge(init) { } ~CTekitou2() {} T hogehoge; bool Execute(double /* e */) override{ veve.push_back(hogehoge); return true; } unsigned int GetID()const override{ return hogehoge; } }; template<typename T, typename... Arg> class CExTaskSelfDestruct : public ExclusiveTaskBase { public: CExTaskSelfDestruct(T init, Arg&&... args) : ExclusiveTaskBase(forward<Arg>(args)...), hogehoge(init) { } ~CExTaskSelfDestruct() {} T hogehoge; bool Execute(double /* e */) override{ veve.push_back(hogehoge); return false; } unsigned int GetID()const override{ return hogehoge; } }; IUTEST(gtfTest, TestMethod1) { TaskManager task; auto ptr = task.AddNewTask< CTekitou<int, TaskBase> >(1); IUTEST_ASSERT_EQ((void*)task.FindTask<TaskBase>(ptr->GetID()).get(), (void*)ptr.get()); } IUTEST(gtfTest, TestMethod2) { TaskManager task; auto ptr = task.AddNewTask< CTekitou2<int, BackgroundTaskBase> >(1); IUTEST_ASSERT_EQ((void*)(task.FindTask<BackgroundTaskBase>(ptr->GetID())).get(), (void*)ptr.get()); } IUTEST(gtfTest, TestMethod3) { TaskManager task; auto ptr = task.AddNewTask< CTekitou2<int, ExclusiveTaskBase> >(1); IUTEST_ASSERT_NE((void*)task.FindTask<TaskBase>(ptr->GetID()).get(), (void*)ptr.get()); } IUTEST(gtfTest, RunOrder1) { TaskManager task; veve.clear(); auto ptr = task.AddNewTask< CTekitou2<int, ExclusiveTaskBase> >(1); auto ptr2 = task.AddNewTask< CTekitou2<int, TaskBase> >(2); //modify veve task.Execute(0); task.Execute(1); IUTEST_ASSERT_EQ(1, veve[0]); IUTEST_ASSERT_EQ(1, veve[1]); } IUTEST(gtfTest, RunOrder2) { static TaskManager task; class ct : public CTekitou2 < int, ExclusiveTaskBase > { public: ct(int init) : CTekitou2 < int, ExclusiveTaskBase >(init) {} void Initialize() { task.AddNewTask< CTekitou2<int, TaskBase> >(2); } }; veve.clear(); auto ptr = task.AddNewTask<ct>(1); task.Execute(0); task.Execute(1); IUTEST_ASSERT_EQ(1, veve[0]); IUTEST_ASSERT_EQ(2, veve[1]); } IUTEST(gtfTest, Draw1) { static TaskManager task; class ct2 : public CTekitou2 < int, ExclusiveTaskBase > { public: ct2(int init) : CTekitou2 < int, ExclusiveTaskBase >(init) { } void Initialize() { task.AddNewTask< CTekitou<int, TaskBase> >(hogehoge + 1); } }; for (int i = 1; i < 257; i++) { task.AddNewTask<ct2>(i * 2); task.Execute(0); } veve.clear(); task.RemoveTaskByID(1); for (int i = 0; i < 4; i++) task.Draw(); IUTEST_ASSERT_EQ(513, veve[0]); } IUTEST(gtfTest, Draw2) { static TaskManager task; class ct2 : public CTekitou2 < int, ExclusiveTaskBase > { public: ct2(int init) : CTekitou2 < int, ExclusiveTaskBase >(init) { } void Initialize() { task.AddNewTask< CTekitou<int, BackgroundTaskBase> >(hogehoge + 1); } }; for (int i = 1; i < 5; i++) { task.AddNewTask<ct2>(i * 2); task.Execute(0); } veve.clear(); task.RemoveTaskByID(1); for (int i = 0; i < 4; i++) task.Draw(); IUTEST_ASSERT_EQ(3, veve[0]); } IUTEST(gtfTest, DrawFallthrough) { static TaskManager task; class ct2 : public CTekitou2 < int, ExclusiveTaskBase, bool > { public: ct2(int init) : CTekitou2 < int, ExclusiveTaskBase, bool >(init, true) { } void Initialize() { task.AddNewTask< CTekitou<int, TaskBase> >(hogehoge + 1); } }; for (int i = 1; i < 5; i++) { task.AddNewTask<ct2>(i * 2); task.Execute(0); } veve.clear(); task.RemoveTaskByID(1); for (int i = 0; i < 4; i++) task.Draw(); IUTEST_ASSERT_EQ(3, veve[0]); } IUTEST(gtfTest, TaskDependency) { static TaskManager task; class ct : public CTekitou2 < int, ExclusiveTaskBase > { public: ct(int init) : CTekitou2 < int, ExclusiveTaskBase >(init) { } void Initialize() { task.AddNewTask< CTekitou2<int, TaskBase> >(hogehoge + 20); } virtual bool Inactivate(unsigned int /* nextTaskID */){ return true; }//!< 他の排他タスクが開始したときに呼ばれる }; veve.clear(); auto ptr = task.AddNewTask<ct>(1); task.Execute(0); auto ptr2 = task.AddNewTask<ct>(3); task.Execute(1); IUTEST_ASSERT_EQ(1, veve[0]); IUTEST_ASSERT_EQ(1 + 20, veve[1]); IUTEST_ASSERT_EQ(3, veve[2]); IUTEST_ASSERT_EQ(3 + 20, veve[3]); task.RevertExclusiveTaskByID(1); task.Execute(3); IUTEST_ASSERT_EQ(1, veve[4]); IUTEST_ASSERT_EQ(1 + 20, veve[5]); ptr2 = task.AddNewTask<ct>(4); task.Execute(4); task.RemoveTaskByID(21); task.Execute(5); IUTEST_ASSERT_EQ(4, veve[8]); IUTEST_ASSERT_EQ(4 + 20, veve[9]); } IUTEST(gtfTest, ReuseContainer) { TaskManager task; auto ptr = task.AddNewTask< CTekitou2<int, ExclusiveTaskBase> >(1); IUTEST_ASSERT_NE((void*)task.FindTask<TaskBase>(ptr->GetID()).get(), (void*)ptr.get()); task.Destroy(); task.Execute(0); IUTEST_ASSERT_EQ((void*)task.GetTopExclusiveTask().lock().get(), (void*)nullptr); auto ptr3 = task.AddNewTask< CTekitou2<int, ExclusiveTaskBase> >(1); task.Execute(0); IUTEST_ASSERT_NE((void*)task.FindTask<TaskBase>(ptr3->GetID()).get(), (void*)ptr3.get()); } IUTEST(gtfTest, ExTaskSelfDeestruct) { TaskManager task; veve.clear(); auto ptr = task.AddNewTask< CTekitou2<int, ExclusiveTaskBase> >(1); task.Execute(0); auto ptr2 = task.AddNewTask< CExTaskSelfDestruct<int> >(2); task.Execute(0); task.Execute(0); IUTEST_ASSERT_EQ(1, veve[0]); IUTEST_ASSERT_EQ(2, veve[1]); IUTEST_ASSERT_EQ(1, veve[2]); } int main(int argc, char** argv) { IUTEST_INIT(&argc, argv); return IUTEST_RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "tmath.hpp" /* ================================ SINE ======================================== */ TMath::DOUBLE TMath::sin(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1), n) * pow(x, 2 * n + 1) / fac(2 * n + 1); } return r; } TMath::DOUBLE TMath::asin(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 1; delta > 1e-6; n++) { LONG odd = 2 * n - 1; DOUBLE oddf = oddfacd(odd - 2); DOUBLE f = facd(odd); DOUBLE p = pow(x, odd); DOUBLE d = p / f * oddf * oddf; delta = abs(d); r += p / f * oddf * oddf; } return r; } TMath::DOUBLE TMath::sinh(DOUBLE x) { return 0.5 * (exp(x) - exp(-x)); } /* ================================ COSINE ======================================== */ TMath::DOUBLE TMath::cos(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1.0), n) * pow(x, 2 * n) / fac(2 * n); } return r; } TMath::DOUBLE TMath::acos(DOUBLE x) { return PI / 2 - asin(x); } TMath::DOUBLE TMath::cosh(DOUBLE x) { return 0.5 * (exp(x) + exp(-x)); } /* ================================ TANGENT ======================================== */ TMath::DOUBLE TMath::tan(DOUBLE x) { return sin(x) / cos(x); } TMath::DOUBLE TMath::atan(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 0; delta > 1e-4; n++) { LONG odd = 2 * n + 1; DOUBLE d = DOUBLE(pow(-1LL, n)) * pow(x, odd) / DOUBLE(odd); delta = abs(d); r += d; } return r; } TMath::DOUBLE TMath::tanh(DOUBLE x) { return sinh(x) / cosh(x); } /* ================================ COTANGENT ======================================== */ TMath::DOUBLE TMath::cot(DOUBLE x) { return cos(x) / sin(x); } TMath::DOUBLE TMath::acot(DOUBLE x) { return PI / 2 - atan(x); } TMath::DOUBLE TMath::coth(DOUBLE x) { return cosh(x) / sinh(x); } /* ================================ SECANT ======================================== */ TMath::DOUBLE TMath::sec(DOUBLE x) { return 1 / cos(x); } TMath::DOUBLE TMath::asec(DOUBLE x) { return acos(1 / x); } TMath::DOUBLE TMath::sech(DOUBLE x) { return 1 / cosh(x); } /* ================================ COSECANT ======================================== */ TMath::DOUBLE TMath::cosec(DOUBLE x) { return 1 / sin(x); } TMath::DOUBLE TMath::acsc(DOUBLE x) { return asin(1 / x); } TMath::DOUBLE TMath::csch(DOUBLE x) { return 1 / sinh(x); } /* ================================= FLOOR, CEIL AND MODULO ======================================== */ TMath::LONG TMath::floor(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { if (truncated > x) { return truncated - 1; } else { return truncated; } } else { return truncated; } } TMath::LONG TMath::ceil(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { return truncated; } else { return truncated + 1; } } TMath::DOUBLE TMath::mod(DOUBLE x, DOUBLE y) { return y * ((x / y) - floor(x / y)); } /* =============================== EXPONENTIAL FUNCTION, SQRT, LOGARITHM ======================= */ TMath::DOUBLE TMath::exp(DOUBLE x) { DOUBLE r = 0; for (LONG n = 0; n <= 15L; n++) { r += pow(x, n) / fac(n); } return r; } TMath::DOUBLE TMath::sqrt(DOUBLE x) { return root(x, 2); } TMath::DOUBLE TMath::root(DOUBLE x, DOUBLE n) { return pow(x, 1 / n); } TMath::DOUBLE TMath::ln(DOUBLE x) { x = (x - 1) / (x + 1); DOUBLE r = 0; for (LONG n = 0; n <= 100L; n++) { r += 2 * pow(x, 2 * n + 1) / (2 * n + 1); } return r; } TMath::DOUBLE TMath::lg(DOUBLE x) { return ln(x) / ln(10); } TMath::DOUBLE TMath::lb(DOUBLE x) { return ln(x) / ln(2); } TMath::DOUBLE TMath::log(DOUBLE x, DOUBLE n) { return ln(x) / ln(n); } /* =================================== POWER FUNCTIONS =====================================================*/ TMath::DOUBLE TMath::pow(DOUBLE x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } DOUBLE r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::LONG TMath::pow(LONG x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } LONG r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::DOUBLE TMath::pow(DOUBLE x, DOUBLE n) { return exp(n * ln(x)); } /* ========================================== FACULTY ============================================*/ TMath::LONG TMath::fac(LONG n) { LONG r = 1; for (LONG i = 2; i <= n; i++) { r *= i; } return r; } TMath::DOUBLE TMath::facd(LONG n) { DOUBLE r = 1; for (LONG i = 2; i <= n; i++) { r *= DOUBLE(i); } return r; } TMath::LONG TMath::oddfac(LONG n) { LONG r = 1; for (LONG i = 3; i <= n; i++) { r *= i; } return r; } TMath::DOUBLE TMath::oddfacd(LONG n) { DOUBLE r = 1; for (LONG i = 3; i <= n; i += 2) { r *= DOUBLE(i); } return r; } TMath::DOUBLE TMath::abs(DOUBLE x) { if (x < 0) return -x; else return x; } /* ========================================== DEGREE / RADIANT CONVERSION ================================*/ TMath::DOUBLE TMath::rad(DOUBLE deg) { return PI / 180 * deg; } TMath::DOUBLE TMath::deg(DOUBLE rad) { return 180 / PI * rad; } <commit_msg>fix: error in oddfac<commit_after>#include "tmath.hpp" /* ================================ SINE ======================================== */ TMath::DOUBLE TMath::sin(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1), n) * pow(x, 2 * n + 1) / fac(2 * n + 1); } return r; } TMath::DOUBLE TMath::asin(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 1; delta > 1e-6; n++) { LONG odd = 2 * n - 1; DOUBLE oddf = oddfacd(odd - 2); DOUBLE f = facd(odd); DOUBLE p = pow(x, odd); DOUBLE d = p / f * oddf * oddf; delta = abs(d); r += p / f * oddf * oddf; } return r; } TMath::DOUBLE TMath::sinh(DOUBLE x) { return 0.5 * (exp(x) - exp(-x)); } /* ================================ COSINE ======================================== */ TMath::DOUBLE TMath::cos(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1.0), n) * pow(x, 2 * n) / fac(2 * n); } return r; } TMath::DOUBLE TMath::acos(DOUBLE x) { return PI / 2 - asin(x); } TMath::DOUBLE TMath::cosh(DOUBLE x) { return 0.5 * (exp(x) + exp(-x)); } /* ================================ TANGENT ======================================== */ TMath::DOUBLE TMath::tan(DOUBLE x) { return sin(x) / cos(x); } TMath::DOUBLE TMath::atan(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 0; delta > 1e-4; n++) { LONG odd = 2 * n + 1; DOUBLE d = DOUBLE(pow(-1LL, n)) * pow(x, odd) / DOUBLE(odd); delta = abs(d); r += d; } return r; } TMath::DOUBLE TMath::tanh(DOUBLE x) { return sinh(x) / cosh(x); } /* ================================ COTANGENT ======================================== */ TMath::DOUBLE TMath::cot(DOUBLE x) { return cos(x) / sin(x); } TMath::DOUBLE TMath::acot(DOUBLE x) { return PI / 2 - atan(x); } TMath::DOUBLE TMath::coth(DOUBLE x) { return cosh(x) / sinh(x); } /* ================================ SECANT ======================================== */ TMath::DOUBLE TMath::sec(DOUBLE x) { return 1 / cos(x); } TMath::DOUBLE TMath::asec(DOUBLE x) { return acos(1 / x); } TMath::DOUBLE TMath::sech(DOUBLE x) { return 1 / cosh(x); } /* ================================ COSECANT ======================================== */ TMath::DOUBLE TMath::cosec(DOUBLE x) { return 1 / sin(x); } TMath::DOUBLE TMath::acsc(DOUBLE x) { return asin(1 / x); } TMath::DOUBLE TMath::csch(DOUBLE x) { return 1 / sinh(x); } /* ================================= FLOOR, CEIL AND MODULO ======================================== */ TMath::LONG TMath::floor(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { if (truncated > x) { return truncated - 1; } else { return truncated; } } else { return truncated; } } TMath::LONG TMath::ceil(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { return truncated; } else { return truncated + 1; } } TMath::DOUBLE TMath::mod(DOUBLE x, DOUBLE y) { return y * ((x / y) - floor(x / y)); } /* =============================== EXPONENTIAL FUNCTION, SQRT, LOGARITHM ======================= */ TMath::DOUBLE TMath::exp(DOUBLE x) { DOUBLE r = 0; for (LONG n = 0; n <= 15L; n++) { r += pow(x, n) / fac(n); } return r; } TMath::DOUBLE TMath::sqrt(DOUBLE x) { return root(x, 2); } TMath::DOUBLE TMath::root(DOUBLE x, DOUBLE n) { return pow(x, 1 / n); } TMath::DOUBLE TMath::ln(DOUBLE x) { x = (x - 1) / (x + 1); DOUBLE r = 0; for (LONG n = 0; n <= 100L; n++) { r += 2 * pow(x, 2 * n + 1) / (2 * n + 1); } return r; } TMath::DOUBLE TMath::lg(DOUBLE x) { return ln(x) / ln(10); } TMath::DOUBLE TMath::lb(DOUBLE x) { return ln(x) / ln(2); } TMath::DOUBLE TMath::log(DOUBLE x, DOUBLE n) { return ln(x) / ln(n); } /* =================================== POWER FUNCTIONS =====================================================*/ TMath::DOUBLE TMath::pow(DOUBLE x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } DOUBLE r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::LONG TMath::pow(LONG x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } LONG r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::DOUBLE TMath::pow(DOUBLE x, DOUBLE n) { return exp(n * ln(x)); } /* ========================================== FACULTY ============================================*/ TMath::LONG TMath::fac(LONG n) { LONG r = 1; for (LONG i = 2; i <= n; i++) { r *= i; } return r; } TMath::DOUBLE TMath::facd(LONG n) { DOUBLE r = 1; for (LONG i = 2; i <= n; i++) { r *= DOUBLE(i); } return r; } TMath::LONG TMath::oddfac(LONG n) { LONG r = 1; for (LONG i = 3; i <= n; i += 2) { r *= i; } return r; } TMath::DOUBLE TMath::oddfacd(LONG n) { DOUBLE r = 1; for (LONG i = 3; i <= n; i += 2) { r *= DOUBLE(i); } return r; } TMath::DOUBLE TMath::abs(DOUBLE x) { if (x < 0) return -x; else return x; } /* ========================================== DEGREE / RADIANT CONVERSION ================================*/ TMath::DOUBLE TMath::rad(DOUBLE deg) { return PI / 180 * deg; } TMath::DOUBLE TMath::deg(DOUBLE rad) { return 180 / PI * rad; } <|endoftext|>
<commit_before>/* ******************************************************************************* \file test.cpp \brief Tests \project GF2 [GF(2) algebra library] \author () Sergey Agievich [agievich@{bsu.by|gmail.com}] \created 2016.07.06 \version 2016.07.22 \license This program is released under the MIT License. See Copyright Notices in GF2/info.h. ******************************************************************************* */ #include "gf2/buchb.h" #include "gf2/func.h" #include "gf2/ideal.h" #include <sstream> using namespace GF2; using namespace std; /* ******************************************************************************* ******************************************************************************* */ template class Word<127>; template class Monom<129>; template class ZZ<130>; template struct OrderGr<OrderLR<OrderLex<65>, OrderGrlex<66> > >; template struct OrderRL<OrderRev<OrderGrevlex<68> >, OrderLex<67> >; template class MPoly<135, OrderLex<135> >; template class Ideal<136, OrderGrevlex<136> >; template class Buchb<137, OrderGrlex<137> >; template class Func<5, int>; template class BFunc<6>; template class VFunc<7, 8>; template class VSubst<8>; /* ******************************************************************************* # orderTest: OrderGrlex<6> OrderGr<OrderLex<6> >; # bentTest: -; # sboxTest: 4- S- (by.gost28147.params.1); # bashTest: , S- Bash; # commuteTest: 2. ******************************************************************************* */ bool orderTest() { OrderGrlex<6> o1; OrderGr<OrderLex<6> > o2; Monom<6> m1; do { Monom<6> m2; do { if (o1.Compare(m1, m2) != o2.Compare(m1, m2)) return false; } while (m2.Next()); } while (m1.Next()); return true; } bool bentTest() { typedef Monom<12> X; MPoly<12> p; BFunc<12> bf; // p = X(0,6) + X(1, 7) + X(2, 8) + X(3, 9); p += X(4, 10) + X(5, 11); // bf.From(p); return bf.IsBent(); } bool sboxTest() { static const word s_table[16] = {2,6,3,14,12,15,7,5,11,13,8,9,10,0,4,1}; VSubst<4> s(s_table); // return s.Nl() == 4 && s.Deg() == 3 && s.DegSpan() == 3 && s.Dc(0) == 4 && s.Dc(1) == 4 && s.Dc(2) == 4 && s.Dc(3) == 3; } bool bashTest() { typedef OrderGrevlex<6> O; typedef Monom<6> X; // S- word s_table[] = {1, 2, 3, 4, 6, 7, 5, 0}; VSubst<3> s(s_table); Ideal<6, O> i; // i <- {x_{k + 3} - s_k(x_0, s_1, x_2): k = 0, 1, 2} MPoly<3, O> p; BFunc<3> bf; s.GetCoord(0, bf); bf.To(p); i.Insert(MPoly<6, O>(p) + X(3)); s.GetCoord(1, bf); bf.To(p); i.Insert(MPoly<6, O>(p) + X(4)); s.GetCoord(2, bf); bf.To(p); i.Insert(MPoly<6, O>(p) + X(5)); // Buchb<6, O> bb; bb.Init(); bb.Update(i); bb.Process(); bb.Done(i); // Env::Trace(""); return i.Size() == 14; } bool commuteTest() { typedef OrderGrevlex<8> O; // stringstream ss; ss << "{ x0 x3 + x1 x2 + 1," /* */ " x1 x6 + x2 x5," /* */ " x1 x7 + x3 x5 + x0 x5 + x1 x4," /* */ " x2 x7 + x3 x6 + x0 x6 + x2 x4," /* */ " x4 x7 + x5 x6 + 1}"; /* */ Ideal<8, O> i; ss >> i; // Buchb<8, O> bb; bb.Init(); bb.Update(i); bb.Process(); bb.Done(i); // ? if (!i.IsGB()) return false; // return i.QuotientBasisDim() == (word)18; } /* ******************************************************************************* main ******************************************************************************* */ int main() { bool code; int ret = 0; Env::Print("gf2/test [gf2 version %s]\n", Env::Version()); Env::Print("orderTest: %s\n", (code = orderTest()) ? "OK" : "Err"), ret |= !code; Env::Print("bentTest: %s\n", (code = bentTest()) ? "OK" : "Err"), ret |= !code; Env::Print("sboxTest: %s\n", (code = sboxTest()) ? "OK" : "Err"), ret |= !code; Env::Print("bashTest: %s\n", (code = bashTest()) ? "OK" : "Err"), ret |= !code; Env::Print("commuteTest: %s\n", (code = commuteTest()) ? "OK" : "Err"), ret |= !code; return ret; } <commit_msg>+= beltTest<commit_after>/* ******************************************************************************* \file test.cpp \brief Tests \project GF2 [GF(2) algebra library] \author (С) Sergey Agievich [agievich@{bsu.by|gmail.com}] \created 2016.07.06 \version 2017.06.02 \license This program is released under the MIT License. See Copyright Notices in GF2/info.h. ******************************************************************************* */ #include "gf2/buchb.h" #include "gf2/func.h" #include "gf2/ideal.h" #include <sstream> using namespace GF2; using namespace std; /* ******************************************************************************* Явное проверочное инстанциирование ******************************************************************************* */ template class Word<127>; template class Monom<129>; template class ZZ<130>; template struct OrderGr<OrderLR<OrderLex<65>, OrderGrlex<66> > >; template struct OrderRL<OrderRev<OrderGrevlex<68> >, OrderLex<67> >; template class MPoly<135, OrderLex<135> >; template class Ideal<136, OrderGrevlex<136> >; template class Buchb<137, OrderGrlex<137> >; template class Func<5, int>; template class BFunc<6>; template class VFunc<7, 8>; template class VSubst<8>; /* ******************************************************************************* Тесты # orderTest: проверка тождественности OrderGrlex<6> и OrderGr<OrderLex<6> >; # bentTest: проверка бентовости функции Майораны-МакФарланда; # sboxTest: проверка криптографических характеристик 4-битового S-блока (by.gost28147.params.1); # beltTest: проверка криптографических характеристик 8-битового S-блока belt (СТБ 34.101.31); # bashTest: базис Гребнера идеала, описывающего S-блок Bash; # commuteTest: коммутируемые обратимые двоичные матрицы порядка 2. ******************************************************************************* */ bool orderTest() { OrderGrlex<6> o1; OrderGr<OrderLex<6> > o2; Monom<6> m1; do { Monom<6> m2; do { if (o1.Compare(m1, m2) != o2.Compare(m1, m2)) return false; } while (m2.Next()); } while (m1.Next()); return true; } bool bentTest() { typedef Monom<12> X; MPoly<12> p; BFunc<12> bf; // многочлен p = X(0,6) + X(1, 7) + X(2, 8) + X(3, 9); p += X(4, 10) + X(5, 11); // функция bf.From(p); return bf.IsBent(); } bool sboxTest() { static const word s_table[16] = {2,6,3,14,12,15,7,5,11,13,8,9,10,0,4,1}; VSubst<4> s(s_table); // характеристики return s.Nl() == 4 && s.Deg() == 3 && s.DegSpan() == 3 && s.Dc(0) == 4 && s.Dc(1) == 4 && s.Dc(2) == 4 && s.Dc(3) == 3; } bool beltTest(bool verbose = false) { static const word h_table[256] = { 0xB1,0x94,0xBA,0xC8,0x0A,0x08,0xF5,0x3B,0x36,0x6D,0x00,0x8E,0x58,0x4A,0x5D,0xE4, 0x85,0x04,0xFA,0x9D,0x1B,0xB6,0xC7,0xAC,0x25,0x2E,0x72,0xC2,0x02,0xFD,0xCE,0x0D, 0x5B,0xE3,0xD6,0x12,0x17,0xB9,0x61,0x81,0xFE,0x67,0x86,0xAD,0x71,0x6B,0x89,0x0B, 0x5C,0xB0,0xC0,0xFF,0x33,0xC3,0x56,0xB8,0x35,0xC4,0x05,0xAE,0xD8,0xE0,0x7F,0x99, 0xE1,0x2B,0xDC,0x1A,0xE2,0x82,0x57,0xEC,0x70,0x3F,0xCC,0xF0,0x95,0xEE,0x8D,0xF1, 0xC1,0xAB,0x76,0x38,0x9F,0xE6,0x78,0xCA,0xF7,0xC6,0xF8,0x60,0xD5,0xBB,0x9C,0x4F, 0xF3,0x3C,0x65,0x7B,0x63,0x7C,0x30,0x6A,0xDD,0x4E,0xA7,0x79,0x9E,0xB2,0x3D,0x31, 0x3E,0x98,0xB5,0x6E,0x27,0xD3,0xBC,0xCF,0x59,0x1E,0x18,0x1F,0x4C,0x5A,0xB7,0x93, 0xE9,0xDE,0xE7,0x2C,0x8F,0x0C,0x0F,0xA6,0x2D,0xDB,0x49,0xF4,0x6F,0x73,0x96,0x47, 0x06,0x07,0x53,0x16,0xED,0x24,0x7A,0x37,0x39,0xCB,0xA3,0x83,0x03,0xA9,0x8B,0xF6, 0x92,0xBD,0x9B,0x1C,0xE5,0xD1,0x41,0x01,0x54,0x45,0xFB,0xC9,0x5E,0x4D,0x0E,0xF2, 0x68,0x20,0x80,0xAA,0x22,0x7D,0x64,0x2F,0x26,0x87,0xF9,0x34,0x90,0x40,0x55,0x11, 0xBE,0x32,0x97,0x13,0x43,0xFC,0x9A,0x48,0xA0,0x2A,0x88,0x5F,0x19,0x4B,0x09,0xA1, 0x7E,0xCD,0xA4,0xD0,0x15,0x44,0xAF,0x8C,0xA5,0x84,0x50,0xBF,0x66,0xD2,0xE8,0x8A, 0xA2,0xD7,0x46,0x52,0x42,0xA8,0xDF,0xB3,0x69,0x74,0xC5,0x51,0xEB,0x23,0x29,0x21, 0xD4,0xEF,0xD9,0xB4,0x3A,0x62,0x28,0x75,0x91,0x14,0x10,0xEA,0x77,0x6C,0xDA,0x1D, }; VSubst<8> s(h_table); word a, x; // характеристики s if (s.Nl() != 102 || s.Deg() != 7 || s.DegSpan() != 6 || s.Dc(0) != 8 || s.Dc(1) != 6 || s.Dc(2) != 3 || s.Dc(3) != 7) return false; if (!verbose) return true; // характеристики add-семейства for (a = 1; a < 256; ++a) { VSubst<8> t; for (x = 0; x < 256; ++x) t[x] = s[(x + a) % 256]; if (t.Nl() < 96 || t.Deg() != 7 || t.Dc(0) > 10 || t.Dc(1) > 8) return false; } return true; } bool bashTest() { typedef OrderGrevlex<6> O; typedef Monom<6> X; // S-блок и его идеал word s_table[] = {1, 2, 3, 4, 6, 7, 5, 0}; VSubst<3> s(s_table); Ideal<6, O> i; // i <- {x_{k + 3} - s_k(x_0, s_1, x_2): k = 0, 1, 2} MPoly<3, O> p; BFunc<3> bf; s.GetCoord(0, bf); bf.To(p); i.Insert(MPoly<6, O>(p) + X(3)); s.GetCoord(1, bf); bf.To(p); i.Insert(MPoly<6, O>(p) + X(4)); s.GetCoord(2, bf); bf.To(p); i.Insert(MPoly<6, O>(p) + X(5)); // базис Гребнера Buchb<6, O> bb; bb.Init(); bb.Update(i); bb.Process(); bb.Done(i); // завершение Env::Trace(""); return i.Size() == 14; } bool commuteTest() { typedef OrderGrevlex<8> O; // система stringstream ss; ss << "{ x0 x3 + x1 x2 + 1," /* обратимость первой матрицы */ " x1 x6 + x2 x5," /* коммутируемость */ " x1 x7 + x3 x5 + x0 x5 + x1 x4," /* коммутируемость */ " x2 x7 + x3 x6 + x0 x6 + x2 x4," /* коммутируемость */ " x4 x7 + x5 x6 + 1}"; /* обратимость второй матрицы */ Ideal<8, O> i; ss >> i; // базис Гребнера Buchb<8, O> bb; bb.Init(); bb.Update(i); bb.Process(); bb.Done(i); // базис Гребнера? if (!i.IsGB()) return false; // количество матриц return i.QuotientBasisDim() == (word)18; } /* ******************************************************************************* main ******************************************************************************* */ int main() { bool code; int ret = 0; Env::Print("gf2/test [gf2 version %s]\n", Env::Version()); Env::Print("orderTest: %s\n", (code = orderTest()) ? "OK" : "Err"), ret |= !code; Env::Print("bentTest: %s\n", (code = bentTest()) ? "OK" : "Err"), ret |= !code; Env::Print("sboxTest: %s\n", (code = sboxTest()) ? "OK" : "Err"), ret |= !code; Env::Print("beltTest: %s\n", (code = beltTest()) ? "OK" : "Err"), ret |= !code; Env::Print("bashTest: %s\n", (code = bashTest()) ? "OK" : "Err"), ret |= !code; Env::Print("commuteTest: %s\n", (code = commuteTest()) ? "OK" : "Err"), ret |= !code; return ret; } <|endoftext|>
<commit_before>#include "token.hpp" namespace laskin { static inline bool isword(char); token::token(enum type type, const std::string& data) : m_type(type) , m_data(data) {} token::token(const token& that) : m_type(that.m_type) , m_data(that.m_data) {} std::vector<token> token::scan(std::istream& is) throw(syntax_error) { std::vector<token> tokens; std::string buffer; for (std::istreambuf_iterator<char> current(is), end; current != end;) { char c = *current++; switch (c) { // Skip comments. case '#': while (current != end) { if (*current++ == '\n') { break; } } break; // Skip whitespace. case ' ': case '\t': case '\r': case '\n': break; // Various separators. case '(': case ')': case '[': case ']': case '{': case '}': case ':': tokens.push_back(token( c == '(' ? type_lparen : c == ')' ? type_rparen : c == '[' ? type_lbrack : c == ']' ? type_rbrack : c == '{' ? type_lbrace : c == '}' ? type_rbrace : type_colon )); break; // Parse numbers from zero. case '0': buffer.assign(1, '0'); if (current != end) { SCAN_NUMBER_FROM_ZERO: switch (c = *current++) { case 'b': case 'B': buffer.append(1, c); while (current != end && std::isdigit(*current)) { if ((c = *current++) != '0' && c != '1') { throw syntax_error( "invalid binary digit" ); } buffer.append(1, c); } break; case 'x': case 'X': buffer.append(1, 'x'); while (current != end && std::isxdigit(*current)) { buffer.append(1, *current++); } break; case 'o': case 'O': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': buffer.append(1, c); while (current != end && std::isdigit(*current)) { if ((c = *current++) > '7') { throw syntax_error( "invalid octal digit" ); } buffer.append(1, c); } break; case '8': case '9': throw syntax_error("invalid octal digit"); case 'e': case 'E': goto SCAN_EXPONENT; case '.': goto SCAN_REAL; } } tokens.push_back(token(type_integer, buffer)); break; // Parse numbers. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer.assign(1, c); SCAN_NUMBER: while (current != end && std::isdigit(*current)) { buffer.append(1, *current++); } if (current != end && *current == '.') { ++current; SCAN_REAL: buffer.append(1, '.'); if (current == end || !std::isdigit(*current)) { throw syntax_error("missing digits after `.'"); } do { buffer.append(1, *current++); } while (current != end && std::isdigit(*current)); if (current != end && (*current == 'e' || *current == 'E')) { SCAN_EXPONENT: buffer.append(1, 'e'); ++current; if (current != end && (*current == '+' || *current == '-')) { buffer.append(1, *current++); } if (current == end || !std::isdigit(*current)) { throw syntax_error("missing exponent"); } do { buffer.append(1, *current++); } while (current != end && std::isdigit(*current)); } tokens.push_back(token(type_real, buffer)); } else { tokens.push_back(token(type_integer, buffer)); } break; // Parse string literals. case '"': case '\'': { buffer.clear(); while (current != end && *current != c) { if (*current == '\\') { // TODO: process escape sequence } else { buffer.append(1, *current++); } } if (current == end) { throw syntax_error("unterminated string literal"); } tokens.push_back(token(type_string, buffer)); ++current; break; } case '-': case '+': buffer.assign(1, c); if (current != end) { if (*current == '0') { goto SCAN_NUMBER_FROM_ZERO; } else if (std::isdigit(*current)) { goto SCAN_NUMBER; } } goto SCAN_WORD; default: if (isword(c)) { buffer.assign(1, c); SCAN_WORD: while (current != end && isword(*current)) { buffer.append(1, *current++); } tokens.push_back(token(type_word, buffer)); } else { throw syntax_error("unexpected input"); } } } return tokens; } token& token::assign(const token& that) { m_type = that.m_type; m_data = that.m_data; return *this; } std::ostream& operator<<(std::ostream& os, const class token& token) { switch (token.type()) { case token::type_lparen: os << "`('"; break; case token::type_rparen: os << "`)'"; break; case token::type_lbrack: os << "`['"; break; case token::type_rbrack: os << "`]'"; break; case token::type_lbrace: os << "`{'"; break; case token::type_rbrace: os << "`}'"; break; case token::type_colon: os << "`:'"; break; case token::type_integer: case token::type_real: os << token.data(); break; case token::type_string: os << "string literal"; break; case token::type_word: os << "`" << token.data() << "'"; } return os; } std::ostream& operator<<(std::ostream& os, enum token::type type) { switch (type) { case token::type_lparen: os << "`('"; break; case token::type_rparen: os << "`)'"; break; case token::type_lbrack: os << "`['"; break; case token::type_rbrack: os << "`]'"; break; case token::type_lbrace: os << "`{'"; break; case token::type_rbrace: os << "`}'"; break; case token::type_colon: os << "`:'"; break; case token::type_integer: case token::type_real: os << "number literal"; break; case token::type_string: os << "string literal"; break; case token::type_word: os << "word"; } return os; } static inline bool isword(char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '!' || c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' || c == '+' || c == ',' || c == '-' || c == '.' || c == '/' || c == ';' || c == '<' || c == '>' || c == '=' || c == '?' || c == '@' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~'; } } <commit_msg>fix number scaning routine<commit_after>#include "token.hpp" namespace laskin { static inline bool isword(char); token::token(enum type type, const std::string& data) : m_type(type) , m_data(data) {} token::token(const token& that) : m_type(that.m_type) , m_data(that.m_data) {} std::vector<token> token::scan(std::istream& is) throw(syntax_error) { std::vector<token> tokens; std::string buffer; for (std::istreambuf_iterator<char> current(is), end; current != end;) { char c = *current++; switch (c) { // Skip comments. case '#': while (current != end) { if (*current++ == '\n') { break; } } break; // Skip whitespace. case ' ': case '\t': case '\r': case '\n': break; // Various separators. case '(': case ')': case '[': case ']': case '{': case '}': case ':': tokens.push_back(token( c == '(' ? type_lparen : c == ')' ? type_rparen : c == '[' ? type_lbrack : c == ']' ? type_rbrack : c == '{' ? type_lbrace : c == '}' ? type_rbrace : type_colon )); break; // Parse numbers from zero. case '0': buffer.assign(1, '0'); if (current != end) { SCAN_NUMBER_FROM_ZERO: switch (c = *current++) { case 'b': case 'B': buffer.append(1, c); while (current != end && std::isdigit(*current)) { if ((c = *current++) != '0' && c != '1') { throw syntax_error( "invalid binary digit" ); } buffer.append(1, c); } break; case 'x': case 'X': buffer.append(1, 'x'); while (current != end && std::isxdigit(*current)) { buffer.append(1, *current++); } break; case 'o': case 'O': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': buffer.append(1, c); while (current != end && std::isdigit(*current)) { if ((c = *current++) > '7') { throw syntax_error( "invalid octal digit" ); } buffer.append(1, c); } break; case '8': case '9': throw syntax_error("invalid octal digit"); case 'e': case 'E': goto SCAN_EXPONENT; case '.': goto SCAN_REAL; } } tokens.push_back(token(type_integer, buffer)); break; // Parse numbers. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer.assign(1, c); SCAN_NUMBER: while (current != end && std::isdigit(*current)) { buffer.append(1, *current++); } if (current != end && *current == '.') { ++current; SCAN_REAL: buffer.append(1, '.'); if (current == end || !std::isdigit(*current)) { throw syntax_error("missing digits after `.'"); } do { buffer.append(1, *current++); } while (current != end && std::isdigit(*current)); if (current != end && (*current == 'e' || *current == 'E')) { SCAN_EXPONENT: buffer.append(1, 'e'); ++current; if (current != end && (*current == '+' || *current == '-')) { buffer.append(1, *current++); } if (current == end || !std::isdigit(*current)) { throw syntax_error("missing exponent"); } do { buffer.append(1, *current++); } while (current != end && std::isdigit(*current)); } tokens.push_back(token(type_real, buffer)); } else { tokens.push_back(token(type_integer, buffer)); } break; // Parse string literals. case '"': case '\'': { buffer.clear(); while (current != end && *current != c) { if (*current == '\\') { // TODO: process escape sequence } else { buffer.append(1, *current++); } } if (current == end) { throw syntax_error("unterminated string literal"); } tokens.push_back(token(type_string, buffer)); ++current; break; } case '-': case '+': buffer.assign(1, c); if (current != end) { if (*current == '0') { buffer.append(1, *current++); goto SCAN_NUMBER_FROM_ZERO; } else if (std::isdigit(*current)) { buffer.append(1, *current++); goto SCAN_NUMBER; } } goto SCAN_WORD; default: if (isword(c)) { buffer.assign(1, c); SCAN_WORD: while (current != end && isword(*current)) { buffer.append(1, *current++); } tokens.push_back(token(type_word, buffer)); } else { throw syntax_error("unexpected input"); } } } return tokens; } token& token::assign(const token& that) { m_type = that.m_type; m_data = that.m_data; return *this; } std::ostream& operator<<(std::ostream& os, const class token& token) { switch (token.type()) { case token::type_lparen: os << "`('"; break; case token::type_rparen: os << "`)'"; break; case token::type_lbrack: os << "`['"; break; case token::type_rbrack: os << "`]'"; break; case token::type_lbrace: os << "`{'"; break; case token::type_rbrace: os << "`}'"; break; case token::type_colon: os << "`:'"; break; case token::type_integer: case token::type_real: os << token.data(); break; case token::type_string: os << "string literal"; break; case token::type_word: os << "`" << token.data() << "'"; } return os; } std::ostream& operator<<(std::ostream& os, enum token::type type) { switch (type) { case token::type_lparen: os << "`('"; break; case token::type_rparen: os << "`)'"; break; case token::type_lbrack: os << "`['"; break; case token::type_rbrack: os << "`]'"; break; case token::type_lbrace: os << "`{'"; break; case token::type_rbrace: os << "`}'"; break; case token::type_colon: os << "`:'"; break; case token::type_integer: case token::type_real: os << "number literal"; break; case token::type_string: os << "string literal"; break; case token::type_word: os << "word"; } return os; } static inline bool isword(char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '!' || c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' || c == '+' || c == ',' || c == '-' || c == '.' || c == '/' || c == ';' || c == '<' || c == '>' || c == '=' || c == '?' || c == '@' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~'; } } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "gridpoint.hpp" TEST(Point, gribpoint_check) { GridPoint p1(2,2); GridPoint p2(3,3); GridPoint p3(5,5); GridPoint a = p1+p2; GridPoint b = p3-p1; ASSERT_TRUE(p3==a); ASSERT_TRUE(p2==b); p1.calH(p3); p1.calG(p2); p1.calF(); ASSERT_GE(p1.getG(), 10); ASSERT_GT(p1.getH(), 0); ASSERT_GT(p1.getF(), 0); } <commit_msg>Added Test<commit_after>#include <gtest/gtest.h> #include "gridpoint.hpp" TEST(Point, gribpoint_check) { GridPoint p1(2,2); GridPoint p2(3,3); GridPoint p3(5,5); GridPoint a = p1+p2; GridPoint b = p3-p1; ASSERT_TRUE(p3==a); ASSERT_TRUE(p2==b); p1.calH(p3); p1.calG(p2); p1.calF(); ASSERT_GE(p1.getG(), 10); ASSERT_GT(p1.getH(), 0); ASSERT_GT(p1.getF(), 0); p1.setStatus(PATH); ASSERT_EQ(p1.getStatus(), 3); } <|endoftext|>
<commit_before>#include <iostream> #include "tools.h" using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; Tools::Tools() {} Tools::~Tools() {} VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { // Calculate the RMSE. VectorXd rmse(4); rmse << 0, 0, 0, 0; // check the validity of the following inputs: // * the estimation vector size should not be zero // * the estimation vector size should equal ground truth vector size if (estimations.size() != ground_truth.size() || estimations.size() == 0){ cout << "Invalid estimation or ground_truth data" << endl; return rmse; } // Accumulate squared residuals for(unsigned int i = 0; i < estimations.size(); ++i) { VectorXd residual = estimations[i] - ground_truth[i]; // Coefficient-wise multiplication residual = residual.array() * residual.array(); rmse += residual; } // Calculate the mean rmse = rmse / estimations.size(); // Calculate the squared root rmse = rmse.array().sqrt(); // Return the result return rmse; } MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) { // Calculate a Jacobian. MatrixXd Hj(3, 4); // Recover state parameters float px = x_state(0); float py = x_state(1); float vx = x_state(2); float vy = x_state(3); // Pre-compute a set of terms to avoid repeated calculation float c1 = px*px + py*py; float c2 = sqrt(c1); float c3 = (c1*c2); // Check division by zero if (fabs(c1) < 0.0001) { cout << "CalculateJacobian () - Error - Division by Zero" << endl; return Hj; } // Compute the Jacobian matrix Hj << (px/c2), (py/c2), 0, 0, -(py/c1), (px/c1), 0, 0, py*(vx*py - vy*px)/c3, px*(px*vy - py*vx)/c3, px/c2, py/c2; return Hj; } <commit_msg>Minor fixes<commit_after>#include <iostream> #include "tools.h" using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; Tools::Tools() {} Tools::~Tools() {} VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { // Calculate the RMSE. VectorXd rmse(4); rmse << 0, 0, 0, 0; // check the validity of the following inputs: // * the estimation vector size should not be zero // * the estimation vector size should equal ground truth vector size if (estimations.size() != ground_truth.size() || estimations.size() == 0){ cout << "Invalid estimation or ground_truth data" << endl; return rmse; } // Accumulate squared residuals for(unsigned int i = 0; i < estimations.size(); ++i) { VectorXd residual = estimations[i] - ground_truth[i]; // Coefficient-wise multiplication residual = residual.array() * residual.array(); rmse += residual; } // Calculate the mean rmse = rmse / estimations.size(); // Calculate the squared root rmse = rmse.array().sqrt(); // Return the result return rmse; } MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) { // Calculate a Jacobian. MatrixXd Hj(3, 4); // Recover state parameters float px = x_state(0); float py = x_state(1); float vx = x_state(2); float vy = x_state(3); // Pre-compute a set of terms to avoid repeated calculation float c1 = px*px + py*py; float c2 = sqrt(c1); float c3 = (c1*c2); // Check division by zero if (fabs(c1) < 0.0001) { cout << "CalculateJacobian () - Error - Division by Zero" << endl; return Hj; } // Compute the Jacobian matrix Hj << (px/c2), (py/c2), 0, 0, -(py/c1), (px/c1), 0, 0, py*(vx*py - vy*px)/c3, px*(px*vy - py*vx)/c3, px/c2, py/c2; return Hj; } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include <catch.hpp> #include "../picojson_serializer.h" #include "test_helpers.h" namespace { struct Point { double x, y, z; friend class picojson::convert::access; template<class Archive> void json(Archive & ar) const { ar & picojson::convert::member("x", x); ar & picojson::convert::member("y", y); ar & picojson::convert::member("z", z); } template<class Archive> void json(Archive & ar) { ar & picojson::convert::member("x", x); ar & picojson::convert::member("y", y); ar & picojson::convert::member("z", z); } }; struct NamedPoint { std::string name; Point point; friend class picojson::convert::access; template<class Archive> void json(Archive & ar) const { ar & picojson::convert::member("name", name); ar & picojson::convert::member("point", point); } template<class Archive> void json(Archive & ar) { ar & picojson::convert::member("name", name); ar & picojson::convert::member("point", point); } }; } TEST_CASE() { SECTION("serialization") { Point p = { 1, 2, 3 }; picojson::value pv = picojson::convert::to_value(p); CHECK(has<double>(pv, "x", 1)); CHECK(has<double>(pv, "y", 2)); CHECK(has<double>(pv, "z", 3)); std::string test_point_name("test point"); NamedPoint np = { test_point_name , p }; picojson::value npv = picojson::convert::to_value(np); CHECK(has<std::string>(npv, "name", test_point_name)); CHECK(has<picojson::object>(npv, "point")); SECTION("deserialization from value") { Point np_ = { 0, 0, 0 }; picojson::convert::from_value(pv, np_); CHECK(np_.x == 1); CHECK(np_.y == 2); CHECK(np_.z == 3); NamedPoint nnp = { "", { 0, 0, 0 } }; picojson::convert::from_value(npv, nnp); CHECK(nnp.name == test_point_name); CHECK(nnp.point.x == 1); CHECK(nnp.point.y == 2); CHECK(nnp.point.z == 3); SECTION("deserialization from string") { std::string ps = picojson::convert::to_string(p); Point pss = { 0, 0, 0 }; picojson::convert::from_string(ps, pss); CHECK(pss.x == 1); CHECK(pss.y == 2); CHECK(pss.z == 3); std::string nps = picojson::convert::to_string(np); NamedPoint npss = { "", { 0, 0, 0 } }; picojson::convert::from_string(nps, npss); CHECK(npss.name == test_point_name); CHECK(npss.point.x == 1); CHECK(npss.point.y == 2); CHECK(npss.point.z == 3); } } SECTION("const data") { Point const pc = { 1, 2, 3 }; pv = picojson::convert::to_value(pc); CHECK(has<double>(pv, "x", 1)); CHECK(has<double>(pv, "y", 2)); CHECK(has<double>(pv, "z", 3)); NamedPoint const npc = { test_point_name , p }; npv = picojson::convert::to_value(npc); CHECK(has<std::string>(npv, "name", test_point_name)); CHECK(has<picojson::object>(npv, "point")); } } SECTION("boundary cases") { const Point p1 = { 1, 2, 3 }; SECTION("cannot deserialize an object from an array") { picojson::array a; a.emplace_back(picojson::convert::to_value(p1)); Point p2 = { 0, 0, 0 }; picojson::convert::from_string(picojson::value(a).serialize(), p2); CHECK(p2.x == 0); CHECK(p2.y == 0); CHECK(p2.z == 0); } SECTION("missing fields are ignored") { picojson::value p1v(picojson::convert::to_value(p1)); REQUIRE(p1v.is<picojson::object>()); p1v.get<picojson::object>()["z"] = picojson::value(); Point p2 = { 42, 42, 42 }; picojson::convert::from_value(p1v, p2); CHECK(p2.x == 1); CHECK(p2.y == 2); CHECK(p2.z == 42); } } } <commit_msg>test is c++03<commit_after>#define CATCH_CONFIG_MAIN #include <catch.hpp> #include "../picojson_serializer.h" #include "test_helpers.h" namespace { struct Point { double x, y, z; friend class picojson::convert::access; template<class Archive> void json(Archive & ar) const { ar & picojson::convert::member("x", x); ar & picojson::convert::member("y", y); ar & picojson::convert::member("z", z); } template<class Archive> void json(Archive & ar) { ar & picojson::convert::member("x", x); ar & picojson::convert::member("y", y); ar & picojson::convert::member("z", z); } }; struct NamedPoint { std::string name; Point point; friend class picojson::convert::access; template<class Archive> void json(Archive & ar) const { ar & picojson::convert::member("name", name); ar & picojson::convert::member("point", point); } template<class Archive> void json(Archive & ar) { ar & picojson::convert::member("name", name); ar & picojson::convert::member("point", point); } }; } TEST_CASE() { SECTION("serialization") { Point p = { 1, 2, 3 }; picojson::value pv = picojson::convert::to_value(p); CHECK(has<double>(pv, "x", 1)); CHECK(has<double>(pv, "y", 2)); CHECK(has<double>(pv, "z", 3)); std::string test_point_name("test point"); NamedPoint np = { test_point_name , p }; picojson::value npv = picojson::convert::to_value(np); CHECK(has<std::string>(npv, "name", test_point_name)); CHECK(has<picojson::object>(npv, "point")); SECTION("deserialization from value") { Point np_ = { 0, 0, 0 }; picojson::convert::from_value(pv, np_); CHECK(np_.x == 1); CHECK(np_.y == 2); CHECK(np_.z == 3); NamedPoint nnp = { "", { 0, 0, 0 } }; picojson::convert::from_value(npv, nnp); CHECK(nnp.name == test_point_name); CHECK(nnp.point.x == 1); CHECK(nnp.point.y == 2); CHECK(nnp.point.z == 3); SECTION("deserialization from string") { std::string ps = picojson::convert::to_string(p); Point pss = { 0, 0, 0 }; picojson::convert::from_string(ps, pss); CHECK(pss.x == 1); CHECK(pss.y == 2); CHECK(pss.z == 3); std::string nps = picojson::convert::to_string(np); NamedPoint npss = { "", { 0, 0, 0 } }; picojson::convert::from_string(nps, npss); CHECK(npss.name == test_point_name); CHECK(npss.point.x == 1); CHECK(npss.point.y == 2); CHECK(npss.point.z == 3); } } SECTION("const data") { Point const pc = { 1, 2, 3 }; pv = picojson::convert::to_value(pc); CHECK(has<double>(pv, "x", 1)); CHECK(has<double>(pv, "y", 2)); CHECK(has<double>(pv, "z", 3)); NamedPoint const npc = { test_point_name , p }; npv = picojson::convert::to_value(npc); CHECK(has<std::string>(npv, "name", test_point_name)); CHECK(has<picojson::object>(npv, "point")); } } SECTION("boundary cases") { const Point p1 = { 1, 2, 3 }; SECTION("cannot deserialize an object from an array") { picojson::array a; a.push_back(picojson::convert::to_value(p1)); Point p2 = { 0, 0, 0 }; picojson::convert::from_string(picojson::value(a).serialize(), p2); CHECK(p2.x == 0); CHECK(p2.y == 0); CHECK(p2.z == 0); } SECTION("missing fields are ignored") { picojson::value p1v(picojson::convert::to_value(p1)); REQUIRE(p1v.is<picojson::object>()); p1v.get<picojson::object>()["z"] = picojson::value(); Point p2 = { 42, 42, 42 }; picojson::convert::from_value(p1v, p2); CHECK(p2.x == 1); CHECK(p2.y == 2); CHECK(p2.z == 42); } } } <|endoftext|>
<commit_before>/* */ #include"types.hpp" #include"heaps.hpp" #include"processes.hpp" #include"errors.hpp" #include"executors.hpp" #include"phandles.hpp" /*O(N), where N is the number of objects involved!*/ /*necessary for determining the size of the semispace to be allocated when sending messages. */ size_t Generic::total_size(ToPointerLock& toptrs, std::stack<Generic**>& s){ Generic** gpp; Generic* to; size_t rv = get_size(); /*Use the to-pointers as expensive marks*/ toptrs.pointto(this, this); get_refs(s); while(!s.empty()){ gpp = s.top(); s.pop(); to = toptrs.to(*gpp); if(to == NULL){ toptrs.pointto(*gpp, *gpp); rv += (*gpp)->get_size(); (*gpp)->get_refs(s); } } /*toptrs' dtor should clear the to-pointers of the objects*/ return rv; } Generic* Generic::type(Process& proc) { return new(proc) Sym(type_atom()); } Generic* Generic::car(void) { throw ArcError("apply", "'car expects an object of type 'cons"); } Generic* Generic::cdr(void) { throw ArcError("apply", "'cdr expects an object of type 'cons"); } Generic* Generic::sv_ref(void) { throw ArcError("container", "expected an object of type 'container"); } Generic* Generic::make_sv(Process& proc) { SharedVar* sp = new(proc) SharedVar(); sp->val = this; return sp; } Generic* Cons::car(void){ return a; } Generic* Cons::cdr(void){ return d; } Generic* SharedVar::sv_ref(void) { return val; } Generic* Sym::car(void){ if(isnil()) return this; else Generic::car(); } Generic* Sym::cdr(void){ if(isnil()) return this; else Generic::cdr(); } Closure::Closure(Executor* c, size_t s) : Generic(), cd(c), vars(s) {} Closure::Closure(boost::shared_ptr<Executor> c, size_t s) : Generic(), cd(c), vars(s) {} KClosure::KClosure(Executor* c, size_t s) : Closure(c, s), nonreusable(0) {} KClosure::KClosure(boost::shared_ptr<Executor> c, size_t s) : Closure(c, s), nonreusable(0) {} ArcBytecodeSequence::ArcBytecodeSequence() : Generic(), seq(new BytecodeSequence()) {} void ArcBytecodeSequence::append(Bytecode* b){ seq->append(b); } /*DEBUG CODE*/ #include<iostream> #define INDENT(ind) for(size_t i = 0; i < ind; ++i) std::cout << "\t" void Cons::probe(size_t ind){ INDENT(ind); std::cout << "CONS cell@" << std::hex << ((size_t)(this)) << std::endl; a->probe(ind+1); d->probe(ind+1); } void MetadataCons::probe(size_t ind){ Cons::probe(ind); INDENT(ind); std::cout << "(metadata)" << std::endl; line->probe(ind+1); file->probe(ind+1); } #include"atoms.hpp" void Sym::probe(size_t ind){ INDENT(ind); std::cout << "SYMBOL: "; GlobalAtom* gp = dynamic_cast<GlobalAtom*>(a.get()); if(gp != NULL) {gp->emit(); std::cout << std::endl;} else std::cout << "<uniq>" << std::endl; } void Closure::probe(size_t ind){ INDENT(ind); std::cout << "CLOSURE: fn@" << std::hex << ((size_t) cd.get()) << " {" << std::endl; for(size_t i = 0; i < vars.size(); ++i){ vars[i]->probe(ind+1); } INDENT(ind); std::cout << "}" << std::endl; } void KClosure::probe(size_t ind){ Closure::probe(ind); INDENT(ind); std::cout << "(" << (nonreusable ? "" : "reusable ") << "continuation)" << std::endl; } void Integer::probe(size_t ind){ INDENT(ind); std::cout << "INTEGER: " << std::dec << val << " @" << std::hex << ((size_t)(this)) << std::endl; } void ArcBytecodeSequence::probe(size_t ind){ INDENT(ind); std::cout << "BYTECODE @" << std::hex << ((size_t) seq.get()) << std::endl; } void Tagged::probe(size_t ind){ INDENT(ind); std::cout << "TAGGED @" << std::hex << ((size_t) this) << std::endl; INDENT(ind); std::cout << "type:" << std::endl; type_o->probe(ind+1); INDENT(ind); std::cout << "rep:" << std::endl; rep_o->probe(ind+1); } void SharedVar::probe(size_t ind){ INDENT(ind); std::cout << "SHAREDVAR @" << std::hex << ((size_t) this) << std::endl; val->probe(ind+1); } void Pid::probe(size_t ind){ INDENT(ind); std::cout << "PID @" << std::hex << ((size_t) this) << " referring to: " << ((size_t) hproc->pproc.get()) << std::endl; } void BinaryBlob::probe(size_t ind){ INDENT(ind); std::cout << "BINARY @" << std::hex << ((size_t) this) << " referring to:" << ((size_t) pdat.get()) << std::endl; for(size_t i = 0; i < pdat->size; ++i){ INDENT(ind+1); std::cout << (*pdat)[i] << std::endl; } } void SemispacePackage(size_t ind){ INDENT(ind); std::cout << "PACKAGE @" << std::hex << ((size_t) this) << std::endl; INDENT(ind); std::cout << "Semispace @" << ((size_t) ns.get()) << std::endl; gp->probe(ind+1); } <commit_msg>types: fixed compilation errors<commit_after>/* */ #include"types.hpp" #include"heaps.hpp" #include"processes.hpp" #include"errors.hpp" #include"executors.hpp" #include"phandles.hpp" /*O(N), where N is the number of objects involved!*/ /*necessary for determining the size of the semispace to be allocated when sending messages. */ size_t Generic::total_size(ToPointerLock& toptrs, std::stack<Generic**>& s){ Generic** gpp; Generic* to; size_t rv = get_size(); /*Use the to-pointers as expensive marks*/ toptrs.pointto(this, this); get_refs(s); while(!s.empty()){ gpp = s.top(); s.pop(); to = toptrs.to(*gpp); if(to == NULL){ toptrs.pointto(*gpp, *gpp); rv += (*gpp)->get_size(); (*gpp)->get_refs(s); } } /*toptrs' dtor should clear the to-pointers of the objects*/ return rv; } Generic* Generic::type(Process& proc) { return new(proc) Sym(type_atom()); } Generic* Generic::car(void) { throw ArcError("apply", "'car expects an object of type 'cons"); } Generic* Generic::cdr(void) { throw ArcError("apply", "'cdr expects an object of type 'cons"); } Generic* Generic::sv_ref(void) { throw ArcError("container", "expected an object of type 'container"); } Generic* Generic::make_sv(Process& proc) { SharedVar* sp = new(proc) SharedVar(); sp->val = this; return sp; } Generic* Cons::car(void){ return a; } Generic* Cons::cdr(void){ return d; } Generic* SharedVar::sv_ref(void) { return val; } Generic* Sym::car(void){ if(isnil()) return this; else Generic::car(); } Generic* Sym::cdr(void){ if(isnil()) return this; else Generic::cdr(); } Closure::Closure(Executor* c, size_t s) : Generic(), cd(c), vars(s) {} Closure::Closure(boost::shared_ptr<Executor> c, size_t s) : Generic(), cd(c), vars(s) {} KClosure::KClosure(Executor* c, size_t s) : Closure(c, s), nonreusable(0) {} KClosure::KClosure(boost::shared_ptr<Executor> c, size_t s) : Closure(c, s), nonreusable(0) {} ArcBytecodeSequence::ArcBytecodeSequence() : Generic(), seq(new BytecodeSequence()) {} void ArcBytecodeSequence::append(Bytecode* b){ seq->append(b); } /*DEBUG CODE*/ #include<iostream> #define INDENT(ind) for(size_t __i = 0; __i < ind; ++__i) std::cout << "\t" void Cons::probe(size_t ind){ INDENT(ind); std::cout << "CONS cell@" << std::hex << ((size_t)(this)) << std::endl; a->probe(ind+1); d->probe(ind+1); } void MetadataCons::probe(size_t ind){ Cons::probe(ind); INDENT(ind); std::cout << "(metadata)" << std::endl; line->probe(ind+1); file->probe(ind+1); } #include"atoms.hpp" void Sym::probe(size_t ind){ INDENT(ind); std::cout << "SYMBOL: "; GlobalAtom* gp = dynamic_cast<GlobalAtom*>(a.get()); if(gp != NULL) {gp->emit(); std::cout << std::endl;} else std::cout << "<uniq>" << std::endl; } void Closure::probe(size_t ind){ INDENT(ind); std::cout << "CLOSURE: fn@" << std::hex << ((size_t) cd.get()) << " {" << std::endl; for(size_t i = 0; i < vars.size(); ++i){ vars[i]->probe(ind+1); } INDENT(ind); std::cout << "}" << std::endl; } void KClosure::probe(size_t ind){ Closure::probe(ind); INDENT(ind); std::cout << "(" << (nonreusable ? "" : "reusable ") << "continuation)" << std::endl; } void Integer::probe(size_t ind){ INDENT(ind); std::cout << "INTEGER: " << std::dec << val << " @" << std::hex << ((size_t)(this)) << std::endl; } void ArcBytecodeSequence::probe(size_t ind){ INDENT(ind); std::cout << "BYTECODE @" << std::hex << ((size_t) seq.get()) << std::endl; } void Tagged::probe(size_t ind){ INDENT(ind); std::cout << "TAGGED @" << std::hex << ((size_t) this) << std::endl; INDENT(ind); std::cout << "type:" << std::endl; type_o->probe(ind+1); INDENT(ind); std::cout << "rep:" << std::endl; rep_o->probe(ind+1); } void SharedVar::probe(size_t ind){ INDENT(ind); std::cout << "SHAREDVAR @" << std::hex << ((size_t) this) << std::endl; val->probe(ind+1); } void Pid::probe(size_t ind){ INDENT(ind); std::cout << "PID @" << std::hex << ((size_t) this) << " referring to: " << ((size_t) hproc->pproc.get()) << std::endl; } void BinaryBlob::probe(size_t ind){ INDENT(ind); std::cout << "BINARY @" << std::hex << ((size_t) this) << " referring to:" << ((size_t) pdat.get()) << std::endl; for(size_t i = 0; i < pdat->size(); ++i){ INDENT(ind+1); std::cout << (*pdat)[i] << std::endl; } } void SemispacePackage::probe(size_t ind){ INDENT(ind); std::cout << "PACKAGE @" << std::hex << ((size_t) this) << std::endl; INDENT(ind); std::cout << "Semispace @" << ((size_t) ns.get()) << std::endl; gp->probe(ind+1); } <|endoftext|>
<commit_before>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: wangtaize@baidu.com #include "agent/task_manager.h" #include "common/logging.h" #include "agent/cgroup.h" extern std::string FLAGS_container; namespace galaxy { int TaskManager::Add(const ::galaxy::TaskInfo& task_info, DefaultWorkspace * workspace) { MutexLock lock(m_mutex); LOG(INFO, "add task with id %d", task_info.task_id()); if (m_task_runner_map.find(task_info.task_id()) != m_task_runner_map.end()) { LOG(WARNING, "task with id %d has exist", task_info.task_id()); return 0; } // do download TaskRunner* runner = NULL; if(FLAGS_container.compare("cgroup") == 0){ LOG(INFO,"use cgroup task runner for task %d",task_info.task_id()); runner = new ContainerTaskRunner(task_info,"/cgroup", workspace); }else{ LOG(INFO,"use command task runner for task %d",task_info.task_id()); runner = new CommandTaskRunner(task_info,workspace); } int ret = runner->Prepare(); if(ret != 0 ){ LOG(INFO,"fail to prepare runner ,ret is %d",ret); return ret; } m_task_runner_map[task_info.task_id()] = runner; //ret = runner->Start(); //if (ret == 0) { // LOG(INFO, "add task with id %d successfully", task_info.task_id()); // m_task_runner_map[task_info.task_id()] = runner; //} else { // LOG(FATAL, "fail to add task with %d", task_info.task_id()); //} return ret; } int TaskManager::Remove(const int64_t& task_info_id) { MutexLock lock(m_mutex); if (m_task_runner_map.find(task_info_id) == m_task_runner_map.end()) { LOG(WARNING, "task with id %d does not exist", task_info_id); return 0; } TaskRunner* runner = m_task_runner_map[task_info_id]; if(NULL == runner){ return 0; } int status = runner->Stop(); if(status == 0){ LOG(INFO,"stop task %d successfully",task_info_id); } m_task_runner_map.erase(task_info_id); delete runner; return status; } int TaskManager::Status(std::vector< TaskStatus >& task_status_vector) { std::map<int64_t, TaskRunner*>::iterator it = m_task_runner_map.begin(); for (; it != m_task_runner_map.end(); ++it) { TaskStatus status; status.set_task_id(it->first); int ret = it->second->IsRunning(); if(ret == 0){ status.set_status(RUNNING); }else if(ret == 1){ status.set_status(COMPLETE); Remove(it->first); }else{ if (it->second->ReStart() == 0) { status.set_status(RESTART); } else { // if restart failed, // 1. retry times more than limit, no need retry any more. // 2. stop failed // 3. start failed status.set_status(ERROR); } } task_status_vector.push_back(status); } return 0; } } <commit_msg>add mutex when check task status<commit_after>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: wangtaize@baidu.com #include "agent/task_manager.h" #include "common/logging.h" #include "agent/cgroup.h" extern std::string FLAGS_container; namespace galaxy { int TaskManager::Add(const ::galaxy::TaskInfo& task_info, DefaultWorkspace * workspace) { MutexLock lock(m_mutex); LOG(INFO, "add task with id %d", task_info.task_id()); if (m_task_runner_map.find(task_info.task_id()) != m_task_runner_map.end()) { LOG(WARNING, "task with id %d has exist", task_info.task_id()); return 0; } // do download TaskRunner* runner = NULL; if(FLAGS_container.compare("cgroup") == 0){ LOG(INFO,"use cgroup task runner for task %d",task_info.task_id()); runner = new ContainerTaskRunner(task_info,"/cgroup", workspace); }else{ LOG(INFO,"use command task runner for task %d",task_info.task_id()); runner = new CommandTaskRunner(task_info,workspace); } int ret = runner->Prepare(); if(ret != 0 ){ LOG(INFO,"fail to prepare runner ,ret is %d",ret); return ret; } m_task_runner_map[task_info.task_id()] = runner; //ret = runner->Start(); //if (ret == 0) { // LOG(INFO, "add task with id %d successfully", task_info.task_id()); // m_task_runner_map[task_info.task_id()] = runner; //} else { // LOG(FATAL, "fail to add task with %d", task_info.task_id()); //} return ret; } int TaskManager::Remove(const int64_t& task_info_id) { MutexLock lock(m_mutex); if (m_task_runner_map.find(task_info_id) == m_task_runner_map.end()) { LOG(WARNING, "task with id %d does not exist", task_info_id); return 0; } TaskRunner* runner = m_task_runner_map[task_info_id]; if(NULL == runner){ return 0; } int status = runner->Stop(); if(status == 0){ LOG(INFO,"stop task %d successfully",task_info_id); } m_task_runner_map.erase(task_info_id); delete runner; return status; } int TaskManager::Status(std::vector< TaskStatus >& task_status_vector) { MutexLock lock(m_mutex); std::map<int64_t, TaskRunner*>::iterator it = m_task_runner_map.begin(); for (; it != m_task_runner_map.end(); ++it) { TaskStatus status; status.set_task_id(it->first); int ret = it->second->IsRunning(); if(ret == 0){ status.set_status(RUNNING); }else if(ret == 1){ status.set_status(COMPLETE); Remove(it->first); }else{ if (it->second->ReStart() == 0) { status.set_status(RESTART); } else { // if restart failed, // 1. retry times more than limit, no need retry any more. // 2. stop failed // 3. start failed status.set_status(ERROR); } } task_status_vector.push_back(status); } return 0; } } <|endoftext|>
<commit_before>#ifndef EVEREST_TYPES_HPP_ #define EVEREST_TYPES_HPP_ #include <http_parser.h> #include <list> #include <functional> namespace everest { /// Log level used in the logging callback enum class LogLevel : int { TRACE, DEBUG, INFO, WARN, ERROR, }; typedef std::function<void(LogLevel, const std::string& message)> LogCallback; typedef ::http_method HTTPMethod; typedef std::list<std::pair<std::string, std::string>> headers_t; } // namespace everest #endif // EVEREST_TYPES_HPP_<commit_msg>Copied HTTP Method enum<commit_after>#ifndef EVEREST_TYPES_HPP_ #define EVEREST_TYPES_HPP_ #include <list> #include <functional> namespace everest { /// Log level used in the logging callback enum class LogLevel : int { TRACE, DEBUG, INFO, WARN, ERROR, }; typedef std::function<void(LogLevel, const std::string& message)> LogCallback; typedef std::list<std::pair<std::string, std::string>> headers_t; // Copied from http-parser #define HTTP_METHOD_MAP(XX) \ XX(0, DELETE, DELETE) \ XX(1, GET, GET) \ XX(2, HEAD, HEAD) \ XX(3, POST, POST) \ XX(4, PUT, PUT) \ /* pathological */ \ XX(5, CONNECT, CONNECT) \ XX(6, OPTIONS, OPTIONS) \ XX(7, TRACE, TRACE) \ /* WebDAV */ \ XX(8, COPY, COPY) \ XX(9, LOCK, LOCK) \ XX(10, MKCOL, MKCOL) \ XX(11, MOVE, MOVE) \ XX(12, PROPFIND, PROPFIND) \ XX(13, PROPPATCH, PROPPATCH) \ XX(14, SEARCH, SEARCH) \ XX(15, UNLOCK, UNLOCK) \ XX(16, BIND, BIND) \ XX(17, REBIND, REBIND) \ XX(18, UNBIND, UNBIND) \ XX(19, ACL, ACL) \ /* subversion */ \ XX(20, REPORT, REPORT) \ XX(21, MKACTIVITY, MKACTIVITY) \ XX(22, CHECKOUT, CHECKOUT) \ XX(23, MERGE, MERGE) \ /* upnp */ \ XX(24, MSEARCH, M-SEARCH) \ XX(25, NOTIFY, NOTIFY) \ XX(26, SUBSCRIBE, SUBSCRIBE) \ XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \ /* RFC-5789 */ \ XX(28, PATCH, PATCH) \ XX(29, PURGE, PURGE) \ /* CalDAV */ \ XX(30, MKCALENDAR, MKCALENDAR) \ /* RFC-2068, section 19.6.1.2 */ \ XX(31, LINK, LINK) \ XX(32, UNLINK, UNLINK) \ enum HTTPMethod { #define XX(num, name, string) HTTP_##name = num, HTTP_METHOD_MAP(XX) #undef XX }; } // namespace everest #endif // EVEREST_TYPES_HPP_<|endoftext|>
<commit_before>#include <string> #include <map> #include "Config.h" #include "Log.h" #include "NetDb.hpp" #include "Transports.h" #include "Tunnel.h" #include "RouterContext.h" #include "Identity.h" #include "Destination.h" #include "Crypto.h" #include "FS.h" #include "api.h" namespace i2p { namespace api { void InitI2P (int argc, char* argv[], const char * appName) { i2p::config::Init (); i2p::config::ParseCmdline (argc, argv, true); // ignore unknown options and help i2p::config::Finalize (); std::string datadir; i2p::config::GetOption("datadir", datadir); i2p::fs::SetAppName (appName); i2p::fs::DetectDataDir(datadir, false); i2p::fs::Init(); #if defined(__x86_64__) i2p::crypto::InitCrypto (false); #else i2p::crypto::InitCrypto (true); #endif int netID; i2p::config::GetOption("netid", netID); i2p::context.SetNetID (netID); i2p::context.Init (); } void TerminateI2P () { i2p::crypto::TerminateCrypto (); } void StartI2P (std::shared_ptr<std::ostream> logStream) { if (logStream) i2p::log::Logger().SendTo (logStream); else i2p::log::Logger().SendTo (i2p::fs::DataDirPath (i2p::fs::GetAppName () + ".log")); i2p::log::Logger().Start (); LogPrint(eLogInfo, "API: starting NetDB"); i2p::data::netdb.Start(); LogPrint(eLogInfo, "API: starting Transports"); i2p::transport::transports.Start(); LogPrint(eLogInfo, "API: starting Tunnels"); i2p::tunnel::tunnels.Start(); } void StopI2P () { LogPrint(eLogInfo, "API: shutting down"); LogPrint(eLogInfo, "API: stopping Tunnels"); i2p::tunnel::tunnels.Stop(); LogPrint(eLogInfo, "API: stopping Transports"); i2p::transport::transports.Stop(); LogPrint(eLogInfo, "API: stopping NetDB"); i2p::data::netdb.Stop(); i2p::log::Logger().Stop (); } void RunPeerTest () { i2p::transport::transports.PeerTest (); } std::shared_ptr<i2p::client::ClientDestination> CreateLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic, const std::map<std::string, std::string> * params) { auto localDestination = std::make_shared<i2p::client::ClientDestination> (keys, isPublic, params); localDestination->Start (); return localDestination; } std::shared_ptr<i2p::client::ClientDestination> CreateLocalDestination (bool isPublic, i2p::data::SigningKeyType sigType, const std::map<std::string, std::string> * params) { i2p::data::PrivateKeys keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType); auto localDestination = std::make_shared<i2p::client::ClientDestination> (keys, isPublic, params); localDestination->Start (); return localDestination; } void DestroyLocalDestination (std::shared_ptr<i2p::client::ClientDestination> dest) { if (dest) dest->Stop (); } void RequestLeaseSet (std::shared_ptr<i2p::client::ClientDestination> dest, const i2p::data::IdentHash& remote) { if (dest) dest->RequestDestination (remote); } std::shared_ptr<i2p::stream::Stream> CreateStream (std::shared_ptr<i2p::client::ClientDestination> dest, const i2p::data::IdentHash& remote) { if (!dest) return nullptr; auto leaseSet = dest->FindLeaseSet (remote); if (leaseSet) { auto stream = dest->CreateStream (leaseSet); stream->Send (nullptr, 0); // connect return stream; } else { RequestLeaseSet (dest, remote); return nullptr; } } void AcceptStream (std::shared_ptr<i2p::client::ClientDestination> dest, const i2p::stream::StreamingDestination::Acceptor& acceptor) { if (dest) dest->AcceptStreams (acceptor); } void DestroyStream (std::shared_ptr<i2p::stream::Stream> stream) { if (stream) stream->Close (); } } } <commit_msg>take elgamal percomputation from config<commit_after>#include <string> #include <map> #include "Config.h" #include "Log.h" #include "NetDb.hpp" #include "Transports.h" #include "Tunnel.h" #include "RouterContext.h" #include "Identity.h" #include "Destination.h" #include "Crypto.h" #include "FS.h" #include "api.h" namespace i2p { namespace api { void InitI2P (int argc, char* argv[], const char * appName) { i2p::config::Init (); i2p::config::ParseCmdline (argc, argv, true); // ignore unknown options and help i2p::config::Finalize (); std::string datadir; i2p::config::GetOption("datadir", datadir); i2p::fs::SetAppName (appName); i2p::fs::DetectDataDir(datadir, false); i2p::fs::Init(); bool precomputation; i2p::config::GetOption("precomputation.elgamal", precomputation); i2p::crypto::InitCrypto (precomputation); int netID; i2p::config::GetOption("netid", netID); i2p::context.SetNetID (netID); i2p::context.Init (); } void TerminateI2P () { i2p::crypto::TerminateCrypto (); } void StartI2P (std::shared_ptr<std::ostream> logStream) { if (logStream) i2p::log::Logger().SendTo (logStream); else i2p::log::Logger().SendTo (i2p::fs::DataDirPath (i2p::fs::GetAppName () + ".log")); i2p::log::Logger().Start (); LogPrint(eLogInfo, "API: starting NetDB"); i2p::data::netdb.Start(); LogPrint(eLogInfo, "API: starting Transports"); i2p::transport::transports.Start(); LogPrint(eLogInfo, "API: starting Tunnels"); i2p::tunnel::tunnels.Start(); } void StopI2P () { LogPrint(eLogInfo, "API: shutting down"); LogPrint(eLogInfo, "API: stopping Tunnels"); i2p::tunnel::tunnels.Stop(); LogPrint(eLogInfo, "API: stopping Transports"); i2p::transport::transports.Stop(); LogPrint(eLogInfo, "API: stopping NetDB"); i2p::data::netdb.Stop(); i2p::log::Logger().Stop (); } void RunPeerTest () { i2p::transport::transports.PeerTest (); } std::shared_ptr<i2p::client::ClientDestination> CreateLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic, const std::map<std::string, std::string> * params) { auto localDestination = std::make_shared<i2p::client::ClientDestination> (keys, isPublic, params); localDestination->Start (); return localDestination; } std::shared_ptr<i2p::client::ClientDestination> CreateLocalDestination (bool isPublic, i2p::data::SigningKeyType sigType, const std::map<std::string, std::string> * params) { i2p::data::PrivateKeys keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType); auto localDestination = std::make_shared<i2p::client::ClientDestination> (keys, isPublic, params); localDestination->Start (); return localDestination; } void DestroyLocalDestination (std::shared_ptr<i2p::client::ClientDestination> dest) { if (dest) dest->Stop (); } void RequestLeaseSet (std::shared_ptr<i2p::client::ClientDestination> dest, const i2p::data::IdentHash& remote) { if (dest) dest->RequestDestination (remote); } std::shared_ptr<i2p::stream::Stream> CreateStream (std::shared_ptr<i2p::client::ClientDestination> dest, const i2p::data::IdentHash& remote) { if (!dest) return nullptr; auto leaseSet = dest->FindLeaseSet (remote); if (leaseSet) { auto stream = dest->CreateStream (leaseSet); stream->Send (nullptr, 0); // connect return stream; } else { RequestLeaseSet (dest, remote); return nullptr; } } void AcceptStream (std::shared_ptr<i2p::client::ClientDestination> dest, const i2p::stream::StreamingDestination::Acceptor& acceptor) { if (dest) dest->AcceptStreams (acceptor); } void DestroyStream (std::shared_ptr<i2p::stream::Stream> stream) { if (stream) stream->Close (); } } } <|endoftext|>
<commit_before>#include "utils.h" #include <sys/stat.h> #include <algorithm> #include <cctype> // ::isspace #include <cstring> #include <fstream> #include <iostream> #include <regex> #include <sstream> #include <stdexcept> #include <glibmm/fileutils.h> #include <glibmm/uriutils.h> #include "debug.h" #include "ui.h" #include "gettext.h" using namespace std; using namespace Glib; const DB_playItem_t *last; static const ustring LW_FMT = "http://lyrics.wikia.com/api.php?action=lyrics&fmt=xml&artist=%1&song=%2"; static const char *home_cache = getenv("XDG_CACHE_HOME"); static const string lyrics_dir = (home_cache ? string(home_cache) : string(getenv("HOME")) + "/.cache") + "/deadbeef/lyrics/"; static experimental::optional<ustring>(*const providers[])(DB_playItem_t *) = {&download_lyrics_from_lyricwiki}; inline string cached_filename(string artist, string title) { replace(artist.begin(), artist.end(), '/', '_'); replace(title.begin(), title.end(), '/', '_'); return lyrics_dir + artist + '-' + title; } extern "C" bool is_cached(const char *artist, const char *title) { return artist && title && access(cached_filename(artist, title).c_str(), 0) == 0; } extern "C" void ensure_lyrics_path_exists() { mkpath(lyrics_dir, 0755); } /** * Loads the cached lyrics * @param artist The artist name * @param title The song title * @note Have no idea about the encodings, so a bug possible here */ experimental::optional<ustring> load_cached_lyrics(const char *artist, const char *title) { string filename = cached_filename(artist, title); debug_out << "filename = '" << filename << "'\n"; try { return {file_get_contents(filename)}; } catch (const FileError& error) { debug_out << error.what(); return {}; } } bool save_cached_lyrics(const string &artist, const string &title, const string &lyrics) { string filename = cached_filename(artist, title); ofstream t(filename); if (!t) { cerr << "lyricbar: could not open file for writing: " << filename << endl; return false; } t << lyrics; return true; } bool is_playing(DB_playItem_t *track) { DB_playItem_t *pl_track = deadbeef->streamer_get_playing_track(); if (!pl_track) return false; deadbeef->pl_item_unref(pl_track); return pl_track == track; } static experimental::optional<ustring> get_lyrics_from_id3v2(DB_playItem_t *track) { const char *path; { pl_lock_guard guard; path = deadbeef->pl_find_meta(track, ":URI"); } DB_FILE *fp = deadbeef->fopen(path); if (!fp) { cerr << "lyricbar: tried to get lyrics from tag but couldn't fopen the file" << endl; return {}; } id3v2_tag id3; int res = deadbeef->junk_id3v2_read_full(track, &id3.tag, fp); deadbeef->fclose(fp); if (res != 0) { debug_out << "junk_id3v2_read_full returned " << res << endl; return {}; } for (auto frame = id3.tag.frames; frame; frame = frame->next) { if (!strcmp(frame->id, "USLT") && frame->size > 5) return ustring{reinterpret_cast<const char*>(frame->data + 5)}; } return {}; } static experimental::optional<ustring> get_lyrics_from_metadata(DB_playItem_t *track) { pl_lock_guard guard; const char *lyrics = deadbeef->pl_find_meta(track, "lyrics"); if (lyrics) return ustring{lyrics}; else return {}; } experimental::optional<ustring> get_lyrics_from_tag(DB_playItem_t *track) { if (auto ans = get_lyrics_from_metadata(track)) return ans; else return get_lyrics_from_id3v2(track); } experimental::optional<ustring> download_lyrics_from_lyricwiki(DB_playItem_t *track) { const char *artist; const char *title; { pl_lock_guard guard; artist = deadbeef->pl_find_meta(track, "artist"); title = deadbeef->pl_find_meta(track, "title"); } ustring api_url = ustring::compose(LW_FMT, uri_escape_string(artist, {}, false) , uri_escape_string(title, {}, false)); string url; try { xmlpp::TextReader reader{api_url}; while (reader.read()) { if (reader.get_node_type() == xmlpp::TextReader::NodeType::Element && reader.get_name() == "lyrics") { reader.read(); // got the cropped version of lyrics — display it before the complete one is got if (reader.get_value() == "Not found") return {}; else set_lyrics(track, reader.get_value()); } else if (reader.get_name() == "url") { reader.read(); url = reader.get_value(); break; } } } catch (const exception &e) { cerr << "lyricbar: couldn't parse XML (URI is '" << api_url << "'), what(): " << e.what() << endl; return {}; } url.replace(0, strlen("http://lyrics.wikia.com/"), "http://lyrics.wikia.com/api.php?action=query&prop=revisions&rvprop=content&format=xml&titles="); string raw_lyrics; try { xmlpp::TextReader reader{url}; while (reader.read()) { if (reader.get_name() == "rev") { reader.read(); raw_lyrics = reader.get_value(); break; } } } catch (const exception &e) { cerr << "lyricbar: couldn't parse XML, what(): " << e.what() << endl; return {}; } // although counter-intuitive, this seems to be the right way to do the parsing const static regex r{R"(<lyrics>\s*([^]*?)\s*</lyrics>)"}; smatch match; regex_search(raw_lyrics, match, r); if (match.size() < 2) { return {}; } return ustring{match[1]}; } void update_lyrics(void *tr) { DB_playItem_t *track = static_cast<DB_playItem_t*>(tr); if (track == last) return; if (auto lyrics = get_lyrics_from_tag(track)) { set_lyrics(track, *lyrics); return; } set_lyrics(track, _("Loading...")); const char *artist; const char *title; { pl_lock_guard guard; artist = deadbeef->pl_find_meta(track, "artist"); title = deadbeef->pl_find_meta(track, "title"); } if (artist && title) { if (auto lyrics = load_cached_lyrics(artist, title)) { set_lyrics(track, *lyrics); return; } // No lyrics in the tag or cache; try to get some and cache if succeeded for (auto f : providers) { if (auto lyrics = f(track)) { set_lyrics(track, *lyrics); save_cached_lyrics(artist, title, *lyrics); return; } } } set_lyrics(track, _("Lyrics not found")); } /** * Creates the directory tree. * @param name the directory path, including trailing slash * @return 0 on success; errno after mkdir call if something went wrong */ int mkpath(const string &name, mode_t mode) { string dir; size_t pos = 0; while ((pos = name.find_first_of('/', pos)) != string::npos){ dir = name.substr(0, pos++); if (dir.empty()) continue; // ignore the leading slash if (mkdir(dir.c_str(), mode) && errno != EEXIST) return errno; } return 0; } int remove_from_cache_action(DB_plugin_action_t *, int ctx) { if (ctx == DDB_ACTION_CTX_SELECTION) { pl_lock_guard guard; ddb_playlist_t *playlist = deadbeef->plt_get_curr(); if (playlist) { DB_playItem_t *current = deadbeef->plt_get_first(playlist, PL_MAIN); while (current) { if (deadbeef->pl_is_selected (current)) { const char *artist = deadbeef->pl_find_meta(current, "artist"); const char *title = deadbeef->pl_find_meta(current, "title"); if (is_cached(artist, title)) remove(cached_filename(artist, title).c_str()); } DB_playItem_t *next = deadbeef->pl_get_next(current, PL_MAIN); deadbeef->pl_item_unref(current); current = next; } deadbeef->plt_unref(playlist); } } return 0; } <commit_msg>Fix memory management<commit_after>#include "utils.h" #include <sys/stat.h> #include <algorithm> #include <cctype> // ::isspace #include <cstring> #include <fstream> #include <iostream> #include <regex> #include <sstream> #include <stdexcept> #include <glibmm/fileutils.h> #include <glibmm/uriutils.h> #include "debug.h" #include "ui.h" #include "gettext.h" using namespace std; using namespace Glib; const DB_playItem_t *last; static const ustring LW_FMT = "http://lyrics.wikia.com/api.php?action=lyrics&fmt=xml&artist=%1&song=%2"; static const char *home_cache = getenv("XDG_CACHE_HOME"); static const string lyrics_dir = (home_cache ? string(home_cache) : string(getenv("HOME")) + "/.cache") + "/deadbeef/lyrics/"; static experimental::optional<ustring>(*const providers[])(DB_playItem_t *) = {&download_lyrics_from_lyricwiki}; inline string cached_filename(string artist, string title) { replace(artist.begin(), artist.end(), '/', '_'); replace(title.begin(), title.end(), '/', '_'); return lyrics_dir + artist + '-' + title; } extern "C" bool is_cached(const char *artist, const char *title) { return artist && title && access(cached_filename(artist, title).c_str(), 0) == 0; } extern "C" void ensure_lyrics_path_exists() { mkpath(lyrics_dir, 0755); } /** * Loads the cached lyrics * @param artist The artist name * @param title The song title * @note Have no idea about the encodings, so a bug possible here */ experimental::optional<ustring> load_cached_lyrics(const char *artist, const char *title) { string filename = cached_filename(artist, title); debug_out << "filename = '" << filename << "'\n"; try { return {file_get_contents(filename)}; } catch (const FileError& error) { debug_out << error.what(); return {}; } } bool save_cached_lyrics(const string &artist, const string &title, const string &lyrics) { string filename = cached_filename(artist, title); ofstream t(filename); if (!t) { cerr << "lyricbar: could not open file for writing: " << filename << endl; return false; } t << lyrics; return true; } bool is_playing(DB_playItem_t *track) { DB_playItem_t *pl_track = deadbeef->streamer_get_playing_track(); if (!pl_track) return false; deadbeef->pl_item_unref(pl_track); return pl_track == track; } static experimental::optional<ustring> get_lyrics_from_id3v2(DB_playItem_t *track) { const char *path; { pl_lock_guard guard; path = deadbeef->pl_find_meta(track, ":URI"); } DB_FILE *fp = deadbeef->fopen(path); if (!fp) { cerr << "lyricbar: tried to get lyrics from tag but couldn't fopen the file" << endl; return {}; } id3v2_tag id3; int res = deadbeef->junk_id3v2_read_full(track, &id3.tag, fp); deadbeef->fclose(fp); if (res != 0) { debug_out << "junk_id3v2_read_full returned " << res << endl; return {}; } for (auto frame = id3.tag.frames; frame; frame = frame->next) { if (!strcmp(frame->id, "USLT") && frame->size > 5) return ustring{reinterpret_cast<const char*>(frame->data + 5)}; } return {}; } static experimental::optional<ustring> get_lyrics_from_metadata(DB_playItem_t *track) { pl_lock_guard guard; const char *lyrics = deadbeef->pl_find_meta(track, "lyrics"); if (lyrics) return ustring{lyrics}; else return {}; } experimental::optional<ustring> get_lyrics_from_tag(DB_playItem_t *track) { if (auto ans = get_lyrics_from_metadata(track)) return ans; else return get_lyrics_from_id3v2(track); } experimental::optional<ustring> download_lyrics_from_lyricwiki(DB_playItem_t *track) { ustring artist; ustring title; { pl_lock_guard guard; artist = deadbeef->pl_find_meta(track, "artist"); title = deadbeef->pl_find_meta(track, "title"); } ustring api_url = ustring::compose(LW_FMT, uri_escape_string(artist, {}, false) , uri_escape_string(title, {}, false)); string url; try { xmlpp::TextReader reader{api_url}; while (reader.read()) { if (reader.get_node_type() == xmlpp::TextReader::NodeType::Element && reader.get_name() == "lyrics") { reader.read(); // got the cropped version of lyrics — display it before the complete one is got if (reader.get_value() == "Not found") return {}; else set_lyrics(track, reader.get_value()); } else if (reader.get_name() == "url") { reader.read(); url = reader.get_value(); break; } } } catch (const exception &e) { cerr << "lyricbar: couldn't parse XML (URI is '" << api_url << "'), what(): " << e.what() << endl; return {}; } url.replace(0, strlen("http://lyrics.wikia.com/"), "http://lyrics.wikia.com/api.php?action=query&prop=revisions&rvprop=content&format=xml&titles="); string raw_lyrics; try { xmlpp::TextReader reader{url}; while (reader.read()) { if (reader.get_name() == "rev") { reader.read(); raw_lyrics = reader.get_value(); break; } } } catch (const exception &e) { cerr << "lyricbar: couldn't parse XML, what(): " << e.what() << endl; return {}; } // although counter-intuitive, this seems to be the right way to do the parsing const static regex r{R"(<lyrics>\s*([^]*?)\s*</lyrics>)"}; smatch match; regex_search(raw_lyrics, match, r); if (match.size() < 2) { return {}; } return ustring{match[1]}; } void update_lyrics(void *tr) { DB_playItem_t *track = static_cast<DB_playItem_t*>(tr); if (track == last) return; if (auto lyrics = get_lyrics_from_tag(track)) { set_lyrics(track, *lyrics); return; } set_lyrics(track, _("Loading...")); const char *artist; const char *title; { pl_lock_guard guard; artist = deadbeef->pl_find_meta(track, "artist"); title = deadbeef->pl_find_meta(track, "title"); } if (artist && title) { if (auto lyrics = load_cached_lyrics(artist, title)) { set_lyrics(track, *lyrics); return; } // No lyrics in the tag or cache; try to get some and cache if succeeded for (auto f : providers) { if (auto lyrics = f(track)) { set_lyrics(track, *lyrics); save_cached_lyrics(artist, title, *lyrics); return; } } } set_lyrics(track, _("Lyrics not found")); } /** * Creates the directory tree. * @param name the directory path, including trailing slash * @return 0 on success; errno after mkdir call if something went wrong */ int mkpath(const string &name, mode_t mode) { string dir; size_t pos = 0; while ((pos = name.find_first_of('/', pos)) != string::npos){ dir = name.substr(0, pos++); if (dir.empty()) continue; // ignore the leading slash if (mkdir(dir.c_str(), mode) && errno != EEXIST) return errno; } return 0; } int remove_from_cache_action(DB_plugin_action_t *, int ctx) { if (ctx == DDB_ACTION_CTX_SELECTION) { pl_lock_guard guard; ddb_playlist_t *playlist = deadbeef->plt_get_curr(); if (playlist) { DB_playItem_t *current = deadbeef->plt_get_first(playlist, PL_MAIN); while (current) { if (deadbeef->pl_is_selected (current)) { const char *artist = deadbeef->pl_find_meta(current, "artist"); const char *title = deadbeef->pl_find_meta(current, "title"); if (is_cached(artist, title)) remove(cached_filename(artist, title).c_str()); } DB_playItem_t *next = deadbeef->pl_get_next(current, PL_MAIN); deadbeef->pl_item_unref(current); current = next; } deadbeef->plt_unref(playlist); } } return 0; } <|endoftext|>
<commit_before>#include "utils.h" #include <QDebug> #include <QSettings> #include <QStandardPaths> #include <math.h> using namespace Utils; GetDirInfoTask::GetDirInfoTask(QDir dir) : _dir(dir) { } void GetDirInfoTask::run() { quint64 size = 0; quint64 count = 0; size = getDirSize(_dir); count = getDirCount(_dir); emit result(size, count); } quint64 GetDirInfoTask::getDirSize(QDir dir) { quint64 size = 0; if(dir.exists()) { dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden | QDir::NoSymLinks); QFileInfoList list = dir.entryInfoList(); for(int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); if(fileInfo.isDir()) { size += getDirSize(QDir(fileInfo.absoluteFilePath())); } else size += static_cast<quint64>(fileInfo.size()); } } return size; } quint64 GetDirInfoTask::getDirCount(QDir dir) { quint64 count = 0; if(dir.exists()) { dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden | QDir::NoSymLinks); QFileInfoList list = dir.entryInfoList(); for(int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); if(fileInfo.isDir()) { count += getDirCount(QDir(fileInfo.absoluteFilePath())); } ++count; } } return count; } QString Utils::humanBytes(quint64 bytes, int fieldWidth) { QSettings settings; bool IEC = settings.value("app/iec_prefixes", false).toBool(); quint64 unit = IEC ? 1024 : 1000; if(bytes < unit) return QString::number(bytes) + " B"; int exp = static_cast<int>(log(bytes) / log(unit)); QString pre = QString(IEC ? "KMGTPE" : "kMGTPE").at(exp - 1) + QString(IEC ? "i" : ""); return QString("%1 %2B") .arg(bytes / pow(unit, exp), fieldWidth, 'f', 2) .arg(pre); } QString Utils::validateTarsnapCache(QString path) { QString result; if(!path.isEmpty()) { QFileInfo candidate(path); if(candidate.exists() && candidate.isDir() && candidate.isWritable()) result = candidate.canonicalFilePath(); } return result; } QString Utils::validateAppDataDir(QString path) { QString result; if(!path.isEmpty()) { QFileInfo candidate(path); if(candidate.exists() && candidate.isDir() && candidate.isWritable()) result = candidate.canonicalFilePath(); } return result; } QString Utils::findTarsnapClientInPath(QString path, bool keygenToo) { QStringList searchPaths; QString executable; if(!path.isEmpty()) searchPaths << path; executable = QStandardPaths::findExecutable(CMD_TARSNAP, searchPaths); if(executable.isEmpty() || !QFileInfo(executable).isReadable() || !QFileInfo(executable).isExecutable()) return ""; else if(keygenToo) { executable = QStandardPaths::findExecutable(CMD_TARSNAPKEYGEN, searchPaths); } if(executable.isEmpty() || !QFileInfo(executable).isReadable() || !QFileInfo(executable).isExecutable()) return ""; else if(path.isEmpty()) path = QFileInfo(executable).absolutePath(); return path; } QFileInfoList Utils::findKeysInPath(QString path) { QFileInfoList result; QDir dir(path); if(!dir.exists()) return result; dir.setFilter(QDir::Files | QDir::Readable); dir.setSorting(QDir::Time); dir.setNameFilters(QStringList("*.key")); return dir.entryInfoList(); } bool Utils::tarsnapVersionMinimum(const QString &minVersion) { QSettings settings; QString tarsnapVersion = settings.value("tarsnap/version", "").toString(); QRegExp versionRx("(\\d+\\.\\d+\\.\\d+(\\.\\d+)?)"); return (-1 != versionRx.indexIn(tarsnapVersion)) && (versionRx.cap(0) >= minVersion); } QString Utils::quoteCommandLine(QStringList args) { QStringList escaped; QRegExp rx("^[0-9a-z-A-Z/._-]*$"); QString cmdLine; for(int i = 0; i < args.size(); ++i) { QString arg = args.at(i); if(rx.indexIn(arg) >= 0) { escaped.append(arg); } else { escaped.append(arg.prepend("\'").append("\'")); } } cmdLine = escaped.join(' '); return (cmdLine); } <commit_msg>findTarsnapClientInPath(): also search /usr/local/bin<commit_after>#include "utils.h" #include <QDebug> #include <QSettings> #include <QStandardPaths> #include <math.h> using namespace Utils; GetDirInfoTask::GetDirInfoTask(QDir dir) : _dir(dir) { } void GetDirInfoTask::run() { quint64 size = 0; quint64 count = 0; size = getDirSize(_dir); count = getDirCount(_dir); emit result(size, count); } quint64 GetDirInfoTask::getDirSize(QDir dir) { quint64 size = 0; if(dir.exists()) { dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden | QDir::NoSymLinks); QFileInfoList list = dir.entryInfoList(); for(int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); if(fileInfo.isDir()) { size += getDirSize(QDir(fileInfo.absoluteFilePath())); } else size += static_cast<quint64>(fileInfo.size()); } } return size; } quint64 GetDirInfoTask::getDirCount(QDir dir) { quint64 count = 0; if(dir.exists()) { dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden | QDir::NoSymLinks); QFileInfoList list = dir.entryInfoList(); for(int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); if(fileInfo.isDir()) { count += getDirCount(QDir(fileInfo.absoluteFilePath())); } ++count; } } return count; } QString Utils::humanBytes(quint64 bytes, int fieldWidth) { QSettings settings; bool IEC = settings.value("app/iec_prefixes", false).toBool(); quint64 unit = IEC ? 1024 : 1000; if(bytes < unit) return QString::number(bytes) + " B"; int exp = static_cast<int>(log(bytes) / log(unit)); QString pre = QString(IEC ? "KMGTPE" : "kMGTPE").at(exp - 1) + QString(IEC ? "i" : ""); return QString("%1 %2B") .arg(bytes / pow(unit, exp), fieldWidth, 'f', 2) .arg(pre); } QString Utils::validateTarsnapCache(QString path) { QString result; if(!path.isEmpty()) { QFileInfo candidate(path); if(candidate.exists() && candidate.isDir() && candidate.isWritable()) result = candidate.canonicalFilePath(); } return result; } QString Utils::validateAppDataDir(QString path) { QString result; if(!path.isEmpty()) { QFileInfo candidate(path); if(candidate.exists() && candidate.isDir() && candidate.isWritable()) result = candidate.canonicalFilePath(); } return result; } QString Utils::findTarsnapClientInPath(QString path, bool keygenToo) { QStringList searchPaths; QString executable; if(!path.isEmpty()) searchPaths << path; executable = QStandardPaths::findExecutable(CMD_TARSNAP, searchPaths); #if defined(Q_OS_OSX) // If we haven't found the command in the default PATH, look // in /usr/local/bin because that's where brew puts it. QStringList brew_bin = {"/usr/local/bin"}; if(executable.isEmpty() && searchPaths.isEmpty()) executable = QStandardPaths::findExecutable(CMD_TARSNAP, brew_bin); #endif if(executable.isEmpty() || !QFileInfo(executable).isReadable() || !QFileInfo(executable).isExecutable()) return ""; else if(keygenToo) { executable = QStandardPaths::findExecutable(CMD_TARSNAPKEYGEN, searchPaths); #if defined(Q_OS_OSX) if(executable.isEmpty() && searchPaths.isEmpty()) executable = QStandardPaths::findExecutable(CMD_TARSNAPKEYGEN, brew_bin); #endif } if(executable.isEmpty() || !QFileInfo(executable).isReadable() || !QFileInfo(executable).isExecutable()) return ""; else if(path.isEmpty()) path = QFileInfo(executable).absolutePath(); return path; } QFileInfoList Utils::findKeysInPath(QString path) { QFileInfoList result; QDir dir(path); if(!dir.exists()) return result; dir.setFilter(QDir::Files | QDir::Readable); dir.setSorting(QDir::Time); dir.setNameFilters(QStringList("*.key")); return dir.entryInfoList(); } bool Utils::tarsnapVersionMinimum(const QString &minVersion) { QSettings settings; QString tarsnapVersion = settings.value("tarsnap/version", "").toString(); QRegExp versionRx("(\\d+\\.\\d+\\.\\d+(\\.\\d+)?)"); return (-1 != versionRx.indexIn(tarsnapVersion)) && (versionRx.cap(0) >= minVersion); } QString Utils::quoteCommandLine(QStringList args) { QStringList escaped; QRegExp rx("^[0-9a-z-A-Z/._-]*$"); QString cmdLine; for(int i = 0; i < args.size(); ++i) { QString arg = args.at(i); if(rx.indexIn(arg) >= 0) { escaped.append(arg); } else { escaped.append(arg.prepend("\'").append("\'")); } } cmdLine = escaped.join(' '); return (cmdLine); } <|endoftext|>
<commit_before>// Chemfiles, a modern library for chemistry file reading and writing // Copyright (C) Guillaume Fraux and contributors -- BSD license #include <cerrno> #include <string> #include <vector> #include "chemfiles/utils.hpp" #ifdef CHEMFILES_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> // GetUserName & GetComputerNameEx #include <direct.h> // _getcwd #define getcwd _getcwd #else #include <unistd.h> #include <pwd.h> #endif std::string chemfiles::user_name() { #ifdef CHEMFILES_WINDOWS char name[1024] = {0}; DWORD size = 1024; if (!GetUserName(name, &size)) { return ""; } return name; #else auto user = getpwuid(getuid()); if (user != nullptr) { return user->pw_name; } else { return ""; } #endif } std::string chemfiles::hostname() { #ifdef CHEMFILES_WINDOWS char name[1024] = {0}; DWORD size = 1024; if (!GetComputerNameEx(ComputerNameDnsHostname, name, &size)) { return ""; } return name; #else #if defined(_POSIX_HOST_NAME_MAX) #define BUFFSIZE _POSIX_HOST_NAME_MAX #elif defined(MAXHOSTNAMELEN) #define BUFFSIZE MAXHOSTNAMELEN #else #define BUFFSIZE 1024 #endif char name[BUFFSIZE]; if (gethostname(name, sizeof(name)) != 0) { return ""; } return name; #endif } std::string chemfiles::current_directory() { // loop util buffer large enough for (size_t size = 128;; size *=2) { std::vector<char> buffer(size, '\0'); #ifdef CHEMFILES_WINDOWS auto result = getcwd(buffer.data(), static_cast<int>(size)); #else auto result = getcwd(buffer.data(), size); #endif if (result == nullptr) { if (errno == ERANGE) { continue; } else { return ""; } } // Remove additional '\0' from the string return std::string(buffer.data()); } } <commit_msg>Make calls to utils::username() thread-safe<commit_after>// Chemfiles, a modern library for chemistry file reading and writing // Copyright (C) Guillaume Fraux and contributors -- BSD license #include <cerrno> #include <string> #include <vector> #include "chemfiles/utils.hpp" #ifdef CHEMFILES_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> // GetUserName & GetComputerNameEx #include <direct.h> // _getcwd #define getcwd _getcwd #else #include <unistd.h> #endif std::string chemfiles::user_name() { #ifdef CHEMFILES_WINDOWS char name[1024] = {0}; DWORD size = 1024; if (!GetUserName(name, &size)) { return ""; } return name; #else char user[1024]; if (getlogin_r(user, sizeof(user)) != 0) { return ""; } return user; #endif } std::string chemfiles::hostname() { #ifdef CHEMFILES_WINDOWS char name[1024] = {0}; DWORD size = 1024; if (!GetComputerNameEx(ComputerNameDnsHostname, name, &size)) { return ""; } return name; #else #if defined(_POSIX_HOST_NAME_MAX) #define BUFFSIZE _POSIX_HOST_NAME_MAX #elif defined(MAXHOSTNAMELEN) #define BUFFSIZE MAXHOSTNAMELEN #else #define BUFFSIZE 1024 #endif char name[BUFFSIZE]; if (gethostname(name, sizeof(name)) != 0) { return ""; } return name; #endif } std::string chemfiles::current_directory() { // loop util buffer large enough for (size_t size = 128;; size *=2) { std::vector<char> buffer(size, '\0'); #ifdef CHEMFILES_WINDOWS auto result = getcwd(buffer.data(), static_cast<int>(size)); #else auto result = getcwd(buffer.data(), size); #endif if (result == nullptr) { if (errno == ERANGE) { continue; } else { return ""; } } // Remove additional '\0' from the string return std::string(buffer.data()); } } <|endoftext|>
<commit_before>#include "worker.h" #include <chrono> #include <thread> #include "utils.h" #include <pynumbuf/serialize.h> extern "C" { static PyObject *RayError; } Status WorkerServiceImpl::ExecuteTask(ServerContext* context, const ExecuteTaskRequest* request, ExecuteTaskReply* reply) { task_ = request->task(); // Copy task RAY_LOG(RAY_INFO, "invoked task " << request->task().name()); Task* taskptr = &task_; send_queue_.send(&taskptr); return Status::OK; } Worker::Worker(const std::string& worker_address, std::shared_ptr<Channel> scheduler_channel, std::shared_ptr<Channel> objstore_channel) : worker_address_(worker_address), scheduler_stub_(Scheduler::NewStub(scheduler_channel)) { receive_queue_.connect(worker_address_, true); connected_ = true; } SubmitTaskReply Worker::submit_task(SubmitTaskRequest* request, int max_retries, int retry_wait_milliseconds) { RAY_CHECK(connected_, "Attempted to perform submit_task but failed."); SubmitTaskReply reply; Status status; for (int i = 0; i < 1 + max_retries; ++i) { ClientContext context; status = scheduler_stub_->SubmitTask(&context, *request, &reply); if (reply.function_registered()) { break; } RAY_LOG(RAY_INFO, "The function " << request->task().name() << " was not registered, so attempting to resubmit the task."); std::this_thread::sleep_for(std::chrono::milliseconds(retry_wait_milliseconds)); } return reply; } void Worker::register_worker(const std::string& worker_address, const std::string& objstore_address) { RegisterWorkerRequest request; request.set_worker_address(worker_address); request.set_objstore_address(objstore_address); RegisterWorkerReply reply; ClientContext context; Status status = scheduler_stub_->RegisterWorker(&context, request, &reply); workerid_ = reply.workerid(); objstoreid_ = reply.objstoreid(); segmentpool_ = std::make_shared<MemorySegmentPool>(objstoreid_, false); request_obj_queue_.connect(std::string("queue:") + objstore_address + std::string(":obj"), false); std::string queue_name = std::string("queue:") + objstore_address + std::string(":worker:") + std::to_string(workerid_) + std::string(":obj"); receive_obj_queue_.connect(queue_name, true); return; } void Worker::request_object(ObjRef objref) { RAY_CHECK(connected_, "Attempted to perform request_object but failed."); RequestObjRequest request; request.set_workerid(workerid_); request.set_objref(objref); AckReply reply; ClientContext context; Status status = scheduler_stub_->RequestObj(&context, request, &reply); return; } ObjRef Worker::get_objref() { // first get objref for the new object RAY_CHECK(connected_, "Attempted to perform get_objref but failed."); PutObjRequest request; PutObjReply reply; ClientContext context; Status status = scheduler_stub_->PutObj(&context, request, &reply); return reply.objref(); } slice Worker::get_object(ObjRef objref) { // get_object assumes that objref is a canonical objref RAY_CHECK(connected_, "Attempted to perform get_object but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); slice slice; slice.data = segmentpool_->get_address(result); slice.len = result.size(); slice.segmentid = result.segmentid(); return slice; } // TODO(pcm): More error handling // contained_objrefs is a vector of all the objrefs contained in obj void Worker::put_object(ObjRef objref, const Obj* obj, std::vector<ObjRef> &contained_objrefs) { RAY_CHECK(connected_, "Attempted to perform put_object but failed."); std::string data; obj->SerializeToString(&data); // TODO(pcm): get rid of this serialization ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::ALLOC; request.objref = objref; request.size = data.size(); request_obj_queue_.send(&request); if (contained_objrefs.size() > 0) { RAY_LOG(RAY_REFCOUNT, "In put_object, calling increment_reference_count for contained objrefs"); increment_reference_count(contained_objrefs); // Notify the scheduler that some object references are serialized in the objstore. } ObjHandle result; receive_obj_queue_.receive(&result); uint8_t* target = segmentpool_->get_address(result); std::memcpy(target, &data[0], data.size()); // We immediately unmap here; if the object is going to be accessed again, it will be mapped again; // This is reqired because we do not have a mechanism to unmap the object later. segmentpool_->unmap_segment(result.segmentid()); request.type = ObjRequestType::WORKER_DONE; request.metadata_offset = 0; request_obj_queue_.send(&request); // Notify the scheduler about the objrefs that we are serializing in the objstore. AddContainedObjRefsRequest contained_objrefs_request; contained_objrefs_request.set_objref(objref); for (int i = 0; i < contained_objrefs.size(); ++i) { contained_objrefs_request.add_contained_objref(contained_objrefs[i]); // TODO(rkn): The naming here is bad } AckReply reply; ClientContext context; scheduler_stub_->AddContainedObjRefs(&context, contained_objrefs_request, &reply); } #define CHECK_ARROW_STATUS(s, msg) \ do { \ arrow::Status _s = (s); \ if (!_s.ok()) { \ std::string _errmsg = std::string(msg) + _s.ToString(); \ PyErr_SetString(RayError, _errmsg.c_str()); \ return NULL; \ } \ } while (0); PyObject* Worker::put_arrow(ObjRef objref, PyObject* value) { RAY_CHECK(connected_, "Attempted to perform put_arrow but failed."); ObjRequest request; pynumbuf::PythonObjectWriter writer; int64_t size; CHECK_ARROW_STATUS(writer.AssemblePayload(value), "error during AssemblePayload: "); CHECK_ARROW_STATUS(writer.GetTotalSize(&size), "error during GetTotalSize: "); request.workerid = workerid_; request.type = ObjRequestType::ALLOC; request.objref = objref; request.size = size; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); int64_t metadata_offset; uint8_t* address = segmentpool_->get_address(result); auto source = std::make_shared<BufferMemorySource>(address, size); CHECK_ARROW_STATUS(writer.Write(source.get(), &metadata_offset), "error during Write: "); // We immediately unmap here; if the object is going to be accessed again, it will be mapped again; // This is reqired because we do not have a mechanism to unmap the object later. segmentpool_->unmap_segment(result.segmentid()); request.type = ObjRequestType::WORKER_DONE; request.metadata_offset = metadata_offset; request_obj_queue_.send(&request); Py_RETURN_NONE; } // returns python list containing the value represented by objref and the // segmentid in which the object is stored PyObject* Worker::get_arrow(ObjRef objref, SegmentId& segmentid) { RAY_CHECK(connected_, "Attempted to perform get_arrow but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); uint8_t* address = segmentpool_->get_address(result); auto source = std::make_shared<BufferMemorySource>(address, result.size()); segmentid = result.segmentid(); PyObject* value; CHECK_ARROW_STATUS(pynumbuf::ReadPythonObjectFrom(source.get(), result.metadata_offset(), &value), "error during ReadPythonObjectFrom: "); return value; } bool Worker::is_arrow(ObjRef objref) { RAY_CHECK(connected_, "Attempted to perform is_arrow but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); return result.metadata_offset() != 0; } void Worker::unmap_object(ObjRef objref) { if (!connected_) { RAY_LOG(RAY_DEBUG, "Attempted to perform unmap_object but failed."); return; } segmentpool_->unmap_segment(objref); } void Worker::alias_objrefs(ObjRef alias_objref, ObjRef target_objref) { RAY_CHECK(connected_, "Attempted to perform alias_objrefs but failed."); ClientContext context; AliasObjRefsRequest request; request.set_alias_objref(alias_objref); request.set_target_objref(target_objref); AckReply reply; scheduler_stub_->AliasObjRefs(&context, request, &reply); } void Worker::increment_reference_count(std::vector<ObjRef> &objrefs) { if (!connected_) { RAY_LOG(RAY_DEBUG, "Attempting to increment_reference_count for objrefs, but connected_ = " << connected_ << " so returning instead."); return; } if (objrefs.size() > 0) { ClientContext context; IncrementRefCountRequest request; for (int i = 0; i < objrefs.size(); ++i) { RAY_LOG(RAY_REFCOUNT, "Incrementing reference count for objref " << objrefs[i]); request.add_objref(objrefs[i]); } AckReply reply; scheduler_stub_->IncrementRefCount(&context, request, &reply); } } void Worker::decrement_reference_count(std::vector<ObjRef> &objrefs) { if (!connected_) { RAY_LOG(RAY_DEBUG, "Attempting to decrement_reference_count, but connected_ = " << connected_ << " so returning instead."); return; } if (objrefs.size() > 0) { ClientContext context; DecrementRefCountRequest request; for (int i = 0; i < objrefs.size(); ++i) { RAY_LOG(RAY_REFCOUNT, "Decrementing reference count for objref " << objrefs[i]); request.add_objref(objrefs[i]); } AckReply reply; scheduler_stub_->DecrementRefCount(&context, request, &reply); } } void Worker::register_function(const std::string& name, size_t num_return_vals) { RAY_CHECK(connected_, "Attempted to perform register_function but failed."); ClientContext context; RegisterFunctionRequest request; request.set_fnname(name); request.set_num_return_vals(num_return_vals); request.set_workerid(workerid_); AckReply reply; scheduler_stub_->RegisterFunction(&context, request, &reply); } Task* Worker::receive_next_task() { Task* task; receive_queue_.receive(&task); return task; } void Worker::notify_task_completed(bool task_succeeded, std::string error_message) { RAY_CHECK(connected_, "Attempted to perform notify_task_completed but failed."); ClientContext context; ReadyForNewTaskRequest request; request.set_workerid(workerid_); ReadyForNewTaskRequest::PreviousTaskInfo* previous_task_info = request.mutable_previous_task_info(); previous_task_info->set_task_succeeded(task_succeeded); previous_task_info->set_error_message(error_message); AckReply reply; scheduler_stub_->ReadyForNewTask(&context, request, &reply); } void Worker::disconnect() { connected_ = false; } bool Worker::connected() { return connected_; } // TODO(rkn): Should we be using pointers or references? And should they be const? void Worker::scheduler_info(ClientContext &context, SchedulerInfoRequest &request, SchedulerInfoReply &reply) { RAY_CHECK(connected_, "Attempted to get scheduler info but failed."); scheduler_stub_->SchedulerInfo(&context, request, &reply); } void Worker::task_info(ClientContext &context, TaskInfoRequest &request, TaskInfoReply &reply) { RAY_CHECK(connected_, "Attempted to get worker info but failed."); scheduler_stub_->TaskInfo(&context, request, &reply); } // Communication between the WorkerServer and the Worker happens via a message // queue. This is because the Python interpreter needs to be single threaded // (in our case running in the main thread), whereas the WorkerService will // run in a separate thread and potentially utilize multiple threads. void Worker::start_worker_service() { const char* service_addr = worker_address_.c_str(); worker_server_thread_ = std::thread([this, service_addr]() { std::string service_address(service_addr); std::string::iterator split_point = split_ip_address(service_address); std::string port; port.assign(split_point, service_address.end()); WorkerServiceImpl service(service_address); ServerBuilder builder; builder.AddListeningPort(std::string("0.0.0.0:") + port, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<Server> server(builder.BuildAndStart()); RAY_LOG(RAY_INFO, "worker server listening on " << service_address); ClientContext context; ReadyForNewTaskRequest request; request.set_workerid(workerid_); AckReply reply; scheduler_stub_->ReadyForNewTask(&context, request, &reply); server->Wait(); }); } <commit_msg>Set the workerid in submit_task and get_objref<commit_after>#include "worker.h" #include <chrono> #include <thread> #include "utils.h" #include <pynumbuf/serialize.h> extern "C" { static PyObject *RayError; } Status WorkerServiceImpl::ExecuteTask(ServerContext* context, const ExecuteTaskRequest* request, ExecuteTaskReply* reply) { task_ = request->task(); // Copy task RAY_LOG(RAY_INFO, "invoked task " << request->task().name()); Task* taskptr = &task_; send_queue_.send(&taskptr); return Status::OK; } Worker::Worker(const std::string& worker_address, std::shared_ptr<Channel> scheduler_channel, std::shared_ptr<Channel> objstore_channel) : worker_address_(worker_address), scheduler_stub_(Scheduler::NewStub(scheduler_channel)) { receive_queue_.connect(worker_address_, true); connected_ = true; } SubmitTaskReply Worker::submit_task(SubmitTaskRequest* request, int max_retries, int retry_wait_milliseconds) { RAY_CHECK(connected_, "Attempted to perform submit_task but failed."); SubmitTaskReply reply; Status status; request->set_workerid(workerid_); for (int i = 0; i < 1 + max_retries; ++i) { ClientContext context; status = scheduler_stub_->SubmitTask(&context, *request, &reply); if (reply.function_registered()) { break; } RAY_LOG(RAY_INFO, "The function " << request->task().name() << " was not registered, so attempting to resubmit the task."); std::this_thread::sleep_for(std::chrono::milliseconds(retry_wait_milliseconds)); } return reply; } void Worker::register_worker(const std::string& worker_address, const std::string& objstore_address) { RegisterWorkerRequest request; request.set_worker_address(worker_address); request.set_objstore_address(objstore_address); RegisterWorkerReply reply; ClientContext context; Status status = scheduler_stub_->RegisterWorker(&context, request, &reply); workerid_ = reply.workerid(); objstoreid_ = reply.objstoreid(); segmentpool_ = std::make_shared<MemorySegmentPool>(objstoreid_, false); request_obj_queue_.connect(std::string("queue:") + objstore_address + std::string(":obj"), false); std::string queue_name = std::string("queue:") + objstore_address + std::string(":worker:") + std::to_string(workerid_) + std::string(":obj"); receive_obj_queue_.connect(queue_name, true); return; } void Worker::request_object(ObjRef objref) { RAY_CHECK(connected_, "Attempted to perform request_object but failed."); RequestObjRequest request; request.set_workerid(workerid_); request.set_objref(objref); AckReply reply; ClientContext context; Status status = scheduler_stub_->RequestObj(&context, request, &reply); return; } ObjRef Worker::get_objref() { // first get objref for the new object RAY_CHECK(connected_, "Attempted to perform get_objref but failed."); PutObjRequest request; request.set_workerid(workerid_); PutObjReply reply; ClientContext context; Status status = scheduler_stub_->PutObj(&context, request, &reply); return reply.objref(); } slice Worker::get_object(ObjRef objref) { // get_object assumes that objref is a canonical objref RAY_CHECK(connected_, "Attempted to perform get_object but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); slice slice; slice.data = segmentpool_->get_address(result); slice.len = result.size(); slice.segmentid = result.segmentid(); return slice; } // TODO(pcm): More error handling // contained_objrefs is a vector of all the objrefs contained in obj void Worker::put_object(ObjRef objref, const Obj* obj, std::vector<ObjRef> &contained_objrefs) { RAY_CHECK(connected_, "Attempted to perform put_object but failed."); std::string data; obj->SerializeToString(&data); // TODO(pcm): get rid of this serialization ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::ALLOC; request.objref = objref; request.size = data.size(); request_obj_queue_.send(&request); if (contained_objrefs.size() > 0) { RAY_LOG(RAY_REFCOUNT, "In put_object, calling increment_reference_count for contained objrefs"); increment_reference_count(contained_objrefs); // Notify the scheduler that some object references are serialized in the objstore. } ObjHandle result; receive_obj_queue_.receive(&result); uint8_t* target = segmentpool_->get_address(result); std::memcpy(target, &data[0], data.size()); // We immediately unmap here; if the object is going to be accessed again, it will be mapped again; // This is reqired because we do not have a mechanism to unmap the object later. segmentpool_->unmap_segment(result.segmentid()); request.type = ObjRequestType::WORKER_DONE; request.metadata_offset = 0; request_obj_queue_.send(&request); // Notify the scheduler about the objrefs that we are serializing in the objstore. AddContainedObjRefsRequest contained_objrefs_request; contained_objrefs_request.set_objref(objref); for (int i = 0; i < contained_objrefs.size(); ++i) { contained_objrefs_request.add_contained_objref(contained_objrefs[i]); // TODO(rkn): The naming here is bad } AckReply reply; ClientContext context; scheduler_stub_->AddContainedObjRefs(&context, contained_objrefs_request, &reply); } #define CHECK_ARROW_STATUS(s, msg) \ do { \ arrow::Status _s = (s); \ if (!_s.ok()) { \ std::string _errmsg = std::string(msg) + _s.ToString(); \ PyErr_SetString(RayError, _errmsg.c_str()); \ return NULL; \ } \ } while (0); PyObject* Worker::put_arrow(ObjRef objref, PyObject* value) { RAY_CHECK(connected_, "Attempted to perform put_arrow but failed."); ObjRequest request; pynumbuf::PythonObjectWriter writer; int64_t size; CHECK_ARROW_STATUS(writer.AssemblePayload(value), "error during AssemblePayload: "); CHECK_ARROW_STATUS(writer.GetTotalSize(&size), "error during GetTotalSize: "); request.workerid = workerid_; request.type = ObjRequestType::ALLOC; request.objref = objref; request.size = size; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); int64_t metadata_offset; uint8_t* address = segmentpool_->get_address(result); auto source = std::make_shared<BufferMemorySource>(address, size); CHECK_ARROW_STATUS(writer.Write(source.get(), &metadata_offset), "error during Write: "); // We immediately unmap here; if the object is going to be accessed again, it will be mapped again; // This is reqired because we do not have a mechanism to unmap the object later. segmentpool_->unmap_segment(result.segmentid()); request.type = ObjRequestType::WORKER_DONE; request.metadata_offset = metadata_offset; request_obj_queue_.send(&request); Py_RETURN_NONE; } // returns python list containing the value represented by objref and the // segmentid in which the object is stored PyObject* Worker::get_arrow(ObjRef objref, SegmentId& segmentid) { RAY_CHECK(connected_, "Attempted to perform get_arrow but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); uint8_t* address = segmentpool_->get_address(result); auto source = std::make_shared<BufferMemorySource>(address, result.size()); segmentid = result.segmentid(); PyObject* value; CHECK_ARROW_STATUS(pynumbuf::ReadPythonObjectFrom(source.get(), result.metadata_offset(), &value), "error during ReadPythonObjectFrom: "); return value; } bool Worker::is_arrow(ObjRef objref) { RAY_CHECK(connected_, "Attempted to perform is_arrow but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); return result.metadata_offset() != 0; } void Worker::unmap_object(ObjRef objref) { if (!connected_) { RAY_LOG(RAY_DEBUG, "Attempted to perform unmap_object but failed."); return; } segmentpool_->unmap_segment(objref); } void Worker::alias_objrefs(ObjRef alias_objref, ObjRef target_objref) { RAY_CHECK(connected_, "Attempted to perform alias_objrefs but failed."); ClientContext context; AliasObjRefsRequest request; request.set_alias_objref(alias_objref); request.set_target_objref(target_objref); AckReply reply; scheduler_stub_->AliasObjRefs(&context, request, &reply); } void Worker::increment_reference_count(std::vector<ObjRef> &objrefs) { if (!connected_) { RAY_LOG(RAY_DEBUG, "Attempting to increment_reference_count for objrefs, but connected_ = " << connected_ << " so returning instead."); return; } if (objrefs.size() > 0) { ClientContext context; IncrementRefCountRequest request; for (int i = 0; i < objrefs.size(); ++i) { RAY_LOG(RAY_REFCOUNT, "Incrementing reference count for objref " << objrefs[i]); request.add_objref(objrefs[i]); } AckReply reply; scheduler_stub_->IncrementRefCount(&context, request, &reply); } } void Worker::decrement_reference_count(std::vector<ObjRef> &objrefs) { if (!connected_) { RAY_LOG(RAY_DEBUG, "Attempting to decrement_reference_count, but connected_ = " << connected_ << " so returning instead."); return; } if (objrefs.size() > 0) { ClientContext context; DecrementRefCountRequest request; for (int i = 0; i < objrefs.size(); ++i) { RAY_LOG(RAY_REFCOUNT, "Decrementing reference count for objref " << objrefs[i]); request.add_objref(objrefs[i]); } AckReply reply; scheduler_stub_->DecrementRefCount(&context, request, &reply); } } void Worker::register_function(const std::string& name, size_t num_return_vals) { RAY_CHECK(connected_, "Attempted to perform register_function but failed."); ClientContext context; RegisterFunctionRequest request; request.set_fnname(name); request.set_num_return_vals(num_return_vals); request.set_workerid(workerid_); AckReply reply; scheduler_stub_->RegisterFunction(&context, request, &reply); } Task* Worker::receive_next_task() { Task* task; receive_queue_.receive(&task); return task; } void Worker::notify_task_completed(bool task_succeeded, std::string error_message) { RAY_CHECK(connected_, "Attempted to perform notify_task_completed but failed."); ClientContext context; ReadyForNewTaskRequest request; request.set_workerid(workerid_); ReadyForNewTaskRequest::PreviousTaskInfo* previous_task_info = request.mutable_previous_task_info(); previous_task_info->set_task_succeeded(task_succeeded); previous_task_info->set_error_message(error_message); AckReply reply; scheduler_stub_->ReadyForNewTask(&context, request, &reply); } void Worker::disconnect() { connected_ = false; } bool Worker::connected() { return connected_; } // TODO(rkn): Should we be using pointers or references? And should they be const? void Worker::scheduler_info(ClientContext &context, SchedulerInfoRequest &request, SchedulerInfoReply &reply) { RAY_CHECK(connected_, "Attempted to get scheduler info but failed."); scheduler_stub_->SchedulerInfo(&context, request, &reply); } void Worker::task_info(ClientContext &context, TaskInfoRequest &request, TaskInfoReply &reply) { RAY_CHECK(connected_, "Attempted to get worker info but failed."); scheduler_stub_->TaskInfo(&context, request, &reply); } // Communication between the WorkerServer and the Worker happens via a message // queue. This is because the Python interpreter needs to be single threaded // (in our case running in the main thread), whereas the WorkerService will // run in a separate thread and potentially utilize multiple threads. void Worker::start_worker_service() { const char* service_addr = worker_address_.c_str(); worker_server_thread_ = std::thread([this, service_addr]() { std::string service_address(service_addr); std::string::iterator split_point = split_ip_address(service_address); std::string port; port.assign(split_point, service_address.end()); WorkerServiceImpl service(service_address); ServerBuilder builder; builder.AddListeningPort(std::string("0.0.0.0:") + port, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<Server> server(builder.BuildAndStart()); RAY_LOG(RAY_INFO, "worker server listening on " << service_address); ClientContext context; ReadyForNewTaskRequest request; request.set_workerid(workerid_); AckReply reply; scheduler_stub_->ReadyForNewTask(&context, request, &reply); server->Wait(); }); } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org> Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk> Copyright (C) 2007 Mirko Stocker <me@misto.ch> Copyright (C) 2009 Dominik Haumann <dhaumann kde org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //BEGIN Includes #include "katefilebrowser.h" #include "katefilebrowser.moc" #include "katebookmarkhandler.h" #include <ktexteditor/document.h> #include <ktexteditor/view.h> #include <KActionCollection> #include <KActionMenu> #include <KConfigGroup> #include <KDebug> #include <KDirOperator> #include <KFilePlacesModel> #include <KHistoryComboBox> #include <KLocale> #include <KToolBar> #include <KUrlNavigator> #include <QAbstractItemView> #include <QDir> #include <QLabel> #include <QLineEdit> #include <QToolButton> #include <kdeversion.h> //END Includes KateFileBrowser::KateFileBrowser(Kate::MainWindow *mainWindow, QWidget * parent, const char * name) : KVBox (parent) , m_mainWindow(mainWindow) { setObjectName(name); m_toolbar = new KToolBar(this); m_toolbar->setMovable(false); m_toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); m_toolbar->setContextMenuPolicy(Qt::NoContextMenu); // includes some actions, but not hooked into the shortcut dialog atm m_actionCollection = new KActionCollection(this); m_actionCollection->addAssociatedWidget(this); KFilePlacesModel* model = new KFilePlacesModel(this); m_urlNavigator = new KUrlNavigator(model, KUrl(QDir::homePath()), this); connect(m_urlNavigator, SIGNAL(urlChanged(const KUrl&)), SLOT(updateDirOperator(const KUrl&))); m_dirOperator = new KDirOperator(KUrl(), this); m_dirOperator->setView(KFile::/* Simple */Detail); m_dirOperator->view()->setSelectionMode(QAbstractItemView::ExtendedSelection); m_dirOperator->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); // Mime filter for the KDirOperator QStringList filter; filter << "text/plain" << "text/html" << "inode/directory"; #if KDE_IS_VERSION(4, 4, 60) m_dirOperator->setNewFileMenuSupportedMimeTypes(filter); #endif setFocusProxy(m_dirOperator); connect(m_dirOperator, SIGNAL(viewChanged(QAbstractItemView *)), this, SLOT(selectorViewChanged(QAbstractItemView *))); connect(m_urlNavigator, SIGNAL(urlChanged(const KUrl&)), m_dirOperator, SLOT(setFocus())); // now all actions exist in dir operator and we can use them in the toolbar setupActions(); setupToolbar(); KHBox* filterBox = new KHBox(this); QLabel* filterLabel = new QLabel(i18n("Filter:"), filterBox); m_filter = new KHistoryComboBox(true, filterBox); filterLabel->setBuddy(m_filter); m_filter->setMaxCount(10); m_filter->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); connect(m_filter, SIGNAL(editTextChanged(const QString&)), SLOT(slotFilterChange(const QString&))); connect(m_filter, SIGNAL(returnPressed(const QString&)), m_filter, SLOT(addToHistory(const QString&))); connect(m_filter, SIGNAL(returnPressed(const QString&)), m_dirOperator, SLOT(setFocus())); connect(m_dirOperator, SIGNAL(urlEntered(const KUrl&)), this, SLOT(updateUrlNavigator(const KUrl&))); // Connect the bookmark handler connect(m_bookmarkHandler, SIGNAL(openUrl(const QString&)), this, SLOT(setDir(const QString&))); m_filter->setWhatsThis(i18n("Enter a name filter to limit which files are displayed.")); connect(m_dirOperator, SIGNAL(fileSelected(const KFileItem&)), this, SLOT(fileSelected(const KFileItem&))); connect(m_mainWindow, SIGNAL(viewChanged()), this, SLOT(autoSyncFolder())); } KateFileBrowser::~KateFileBrowser() { } //END Constroctor/Destrctor //BEGIN Public Methods void KateFileBrowser::setupToolbar() { KConfigGroup config(KGlobal::config(), "filebrowser"); QStringList actions = config.readEntry( "toolbar actions", QStringList() ); if ( actions.isEmpty() ) // default toolbar actions << "back" << "forward" << "bookmarks" << "sync_dir" << "configure"; // remove all actions from the toolbar (there should be none) m_toolbar->clear(); // now add all actions to the toolbar foreach (QString it, actions) { QAction *ac = 0; if (it.isEmpty()) continue; if (it == "bookmarks" || it == "sync_dir" || it == "configure") ac = actionCollection()->action(it); else ac = m_dirOperator->actionCollection()->action(it); if (ac) m_toolbar->addAction(ac); } } void KateFileBrowser::readSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->readConfig(cgDir); m_dirOperator->setView(KFile::Default); KConfigGroup cg(config, name); m_urlNavigator->setUrl(cg.readPathEntry("location", QDir::homePath())); setDir(cg.readPathEntry("location", QDir::homePath())); m_autoSyncFolder->setChecked(cg.readEntry("auto sync folder", false)); m_filter->setHistoryItems(cg.readEntry("filter history", QStringList()), true); } void KateFileBrowser::writeSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->writeConfig(cgDir); KConfigGroup cg = KConfigGroup(config, name); cg.writePathEntry("location", m_urlNavigator->url().url()); cg.writeEntry("auto sync folder", m_autoSyncFolder->isChecked()); cg.writeEntry("filter history", m_filter->historyItems()); } //END Public Methods //BEGIN Public Slots void KateFileBrowser::slotFilterChange(const QString & nf) { QString f = nf.trimmed(); const bool empty = f.isEmpty() || f == "*"; if (empty) { m_dirOperator->clearFilter(); } else { m_dirOperator->setNameFilter(f); } m_dirOperator->updateDir(); } bool kateFileSelectorIsReadable (const KUrl& url) { if (!url.isLocalFile()) return true; // what else can we say? QDir dir(url.toLocalFile()); return dir.exists (); } void KateFileBrowser::setDir(KUrl u) { KUrl newurl; if (!u.isValid()) newurl.setPath(QDir::homePath()); else newurl = u; QString pathstr = newurl.path(KUrl::AddTrailingSlash); newurl.setPath(pathstr); if (!kateFileSelectorIsReadable (newurl)) newurl.cd(QString::fromLatin1("..")); if (!kateFileSelectorIsReadable (newurl)) newurl.setPath(QDir::homePath()); m_dirOperator->setUrl(newurl, true); } //END Public Slots //BEGIN Private Slots void KateFileBrowser::fileSelected(const KFileItem & /*file*/) { openSelectedFiles(); } void KateFileBrowser::openSelectedFiles() { const KFileItemList list = m_dirOperator->selectedItems(); foreach (const KFileItem& item, list) { m_mainWindow->openUrl(item.url()); } m_dirOperator->view()->selectionModel()->clear(); } void KateFileBrowser::updateDirOperator(const KUrl& u) { m_dirOperator->setUrl(u, true); } void KateFileBrowser::updateUrlNavigator(const KUrl& u) { m_urlNavigator->setUrl(u); } void KateFileBrowser::setActiveDocumentDir() { // kDebug(13001)<<"KateFileBrowser::setActiveDocumentDir()"; KUrl u = activeDocumentUrl(); // kDebug(13001)<<"URL: "<<u.prettyUrl(); if (!u.isEmpty()) setDir(u.upUrl()); // kDebug(13001)<<"... setActiveDocumentDir() DONE!"; } void KateFileBrowser::autoSyncFolder() { if (m_autoSyncFolder->isChecked()) { setActiveDocumentDir(); } } void KateFileBrowser::selectorViewChanged(QAbstractItemView * newView) { newView->setSelectionMode(QAbstractItemView::ExtendedSelection); } //END Private Slots //BEGIN Protected KUrl KateFileBrowser::activeDocumentUrl() { KTextEditor::View *v = m_mainWindow->activeView(); if (v) return v->document()->url(); return KUrl(); } void KateFileBrowser::setupActions() { // bookmarks action! KActionMenu *acmBookmarks = new KActionMenu(KIcon("bookmarks"), i18n("Bookmarks"), this); acmBookmarks->setDelayed(false); m_bookmarkHandler = new KateBookmarkHandler(this, acmBookmarks->menu()); acmBookmarks->setShortcutContext(Qt::WidgetWithChildrenShortcut); // action for synchronizing the dir operator with the current document path KAction* syncFolder = new KAction(this); syncFolder->setShortcutContext(Qt::WidgetWithChildrenShortcut); syncFolder->setText(i18n("Current Document Folder")); syncFolder->setIcon(KIcon("system-switch-user")); connect(syncFolder, SIGNAL(triggered()), this, SLOT(setActiveDocumentDir())); m_actionCollection->addAction("sync_dir", syncFolder); m_actionCollection->addAction("bookmarks", acmBookmarks); // section for settings menu KActionMenu *optionsMenu = new KActionMenu(KIcon("configure"), i18n("Options"), this); optionsMenu->setDelayed(false); optionsMenu->addAction(m_dirOperator->actionCollection()->action("short view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("tree view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed tree view")); optionsMenu->addSeparator(); optionsMenu->addAction(m_dirOperator->actionCollection()->action("show hidden")); // action for synchronising the dir operator with the current document path m_autoSyncFolder = new KAction(this); m_autoSyncFolder->setCheckable(true); m_autoSyncFolder->setText(i18n("Automatically synchronize with current document")); m_autoSyncFolder->setIcon(KIcon("system-switch-user")); connect(m_autoSyncFolder, SIGNAL(triggered()), this, SLOT(autoSyncFolder())); optionsMenu->addAction(m_autoSyncFolder); m_actionCollection->addAction("configure", optionsMenu); } //END Protected // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>move ifdef<commit_after>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org> Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk> Copyright (C) 2007 Mirko Stocker <me@misto.ch> Copyright (C) 2009 Dominik Haumann <dhaumann kde org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //BEGIN Includes #include "katefilebrowser.h" #include "katefilebrowser.moc" #include "katebookmarkhandler.h" #include <ktexteditor/document.h> #include <ktexteditor/view.h> #include <KActionCollection> #include <KActionMenu> #include <KConfigGroup> #include <KDebug> #include <KDirOperator> #include <KFilePlacesModel> #include <KHistoryComboBox> #include <KLocale> #include <KToolBar> #include <KUrlNavigator> #include <QAbstractItemView> #include <QDir> #include <QLabel> #include <QLineEdit> #include <QToolButton> #include <kdeversion.h> //END Includes KateFileBrowser::KateFileBrowser(Kate::MainWindow *mainWindow, QWidget * parent, const char * name) : KVBox (parent) , m_mainWindow(mainWindow) { setObjectName(name); m_toolbar = new KToolBar(this); m_toolbar->setMovable(false); m_toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); m_toolbar->setContextMenuPolicy(Qt::NoContextMenu); // includes some actions, but not hooked into the shortcut dialog atm m_actionCollection = new KActionCollection(this); m_actionCollection->addAssociatedWidget(this); KFilePlacesModel* model = new KFilePlacesModel(this); m_urlNavigator = new KUrlNavigator(model, KUrl(QDir::homePath()), this); connect(m_urlNavigator, SIGNAL(urlChanged(const KUrl&)), SLOT(updateDirOperator(const KUrl&))); m_dirOperator = new KDirOperator(KUrl(), this); m_dirOperator->setView(KFile::/* Simple */Detail); m_dirOperator->view()->setSelectionMode(QAbstractItemView::ExtendedSelection); m_dirOperator->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); #if KDE_IS_VERSION(4, 4, 60) // Mime filter for the KDirOperator QStringList filter; filter << "text/plain" << "text/html" << "inode/directory"; m_dirOperator->setNewFileMenuSupportedMimeTypes(filter); #endif setFocusProxy(m_dirOperator); connect(m_dirOperator, SIGNAL(viewChanged(QAbstractItemView *)), this, SLOT(selectorViewChanged(QAbstractItemView *))); connect(m_urlNavigator, SIGNAL(urlChanged(const KUrl&)), m_dirOperator, SLOT(setFocus())); // now all actions exist in dir operator and we can use them in the toolbar setupActions(); setupToolbar(); KHBox* filterBox = new KHBox(this); QLabel* filterLabel = new QLabel(i18n("Filter:"), filterBox); m_filter = new KHistoryComboBox(true, filterBox); filterLabel->setBuddy(m_filter); m_filter->setMaxCount(10); m_filter->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); connect(m_filter, SIGNAL(editTextChanged(const QString&)), SLOT(slotFilterChange(const QString&))); connect(m_filter, SIGNAL(returnPressed(const QString&)), m_filter, SLOT(addToHistory(const QString&))); connect(m_filter, SIGNAL(returnPressed(const QString&)), m_dirOperator, SLOT(setFocus())); connect(m_dirOperator, SIGNAL(urlEntered(const KUrl&)), this, SLOT(updateUrlNavigator(const KUrl&))); // Connect the bookmark handler connect(m_bookmarkHandler, SIGNAL(openUrl(const QString&)), this, SLOT(setDir(const QString&))); m_filter->setWhatsThis(i18n("Enter a name filter to limit which files are displayed.")); connect(m_dirOperator, SIGNAL(fileSelected(const KFileItem&)), this, SLOT(fileSelected(const KFileItem&))); connect(m_mainWindow, SIGNAL(viewChanged()), this, SLOT(autoSyncFolder())); } KateFileBrowser::~KateFileBrowser() { } //END Constroctor/Destrctor //BEGIN Public Methods void KateFileBrowser::setupToolbar() { KConfigGroup config(KGlobal::config(), "filebrowser"); QStringList actions = config.readEntry( "toolbar actions", QStringList() ); if ( actions.isEmpty() ) // default toolbar actions << "back" << "forward" << "bookmarks" << "sync_dir" << "configure"; // remove all actions from the toolbar (there should be none) m_toolbar->clear(); // now add all actions to the toolbar foreach (QString it, actions) { QAction *ac = 0; if (it.isEmpty()) continue; if (it == "bookmarks" || it == "sync_dir" || it == "configure") ac = actionCollection()->action(it); else ac = m_dirOperator->actionCollection()->action(it); if (ac) m_toolbar->addAction(ac); } } void KateFileBrowser::readSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->readConfig(cgDir); m_dirOperator->setView(KFile::Default); KConfigGroup cg(config, name); m_urlNavigator->setUrl(cg.readPathEntry("location", QDir::homePath())); setDir(cg.readPathEntry("location", QDir::homePath())); m_autoSyncFolder->setChecked(cg.readEntry("auto sync folder", false)); m_filter->setHistoryItems(cg.readEntry("filter history", QStringList()), true); } void KateFileBrowser::writeSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->writeConfig(cgDir); KConfigGroup cg = KConfigGroup(config, name); cg.writePathEntry("location", m_urlNavigator->url().url()); cg.writeEntry("auto sync folder", m_autoSyncFolder->isChecked()); cg.writeEntry("filter history", m_filter->historyItems()); } //END Public Methods //BEGIN Public Slots void KateFileBrowser::slotFilterChange(const QString & nf) { QString f = nf.trimmed(); const bool empty = f.isEmpty() || f == "*"; if (empty) { m_dirOperator->clearFilter(); } else { m_dirOperator->setNameFilter(f); } m_dirOperator->updateDir(); } bool kateFileSelectorIsReadable (const KUrl& url) { if (!url.isLocalFile()) return true; // what else can we say? QDir dir(url.toLocalFile()); return dir.exists (); } void KateFileBrowser::setDir(KUrl u) { KUrl newurl; if (!u.isValid()) newurl.setPath(QDir::homePath()); else newurl = u; QString pathstr = newurl.path(KUrl::AddTrailingSlash); newurl.setPath(pathstr); if (!kateFileSelectorIsReadable (newurl)) newurl.cd(QString::fromLatin1("..")); if (!kateFileSelectorIsReadable (newurl)) newurl.setPath(QDir::homePath()); m_dirOperator->setUrl(newurl, true); } //END Public Slots //BEGIN Private Slots void KateFileBrowser::fileSelected(const KFileItem & /*file*/) { openSelectedFiles(); } void KateFileBrowser::openSelectedFiles() { const KFileItemList list = m_dirOperator->selectedItems(); foreach (const KFileItem& item, list) { m_mainWindow->openUrl(item.url()); } m_dirOperator->view()->selectionModel()->clear(); } void KateFileBrowser::updateDirOperator(const KUrl& u) { m_dirOperator->setUrl(u, true); } void KateFileBrowser::updateUrlNavigator(const KUrl& u) { m_urlNavigator->setUrl(u); } void KateFileBrowser::setActiveDocumentDir() { // kDebug(13001)<<"KateFileBrowser::setActiveDocumentDir()"; KUrl u = activeDocumentUrl(); // kDebug(13001)<<"URL: "<<u.prettyUrl(); if (!u.isEmpty()) setDir(u.upUrl()); // kDebug(13001)<<"... setActiveDocumentDir() DONE!"; } void KateFileBrowser::autoSyncFolder() { if (m_autoSyncFolder->isChecked()) { setActiveDocumentDir(); } } void KateFileBrowser::selectorViewChanged(QAbstractItemView * newView) { newView->setSelectionMode(QAbstractItemView::ExtendedSelection); } //END Private Slots //BEGIN Protected KUrl KateFileBrowser::activeDocumentUrl() { KTextEditor::View *v = m_mainWindow->activeView(); if (v) return v->document()->url(); return KUrl(); } void KateFileBrowser::setupActions() { // bookmarks action! KActionMenu *acmBookmarks = new KActionMenu(KIcon("bookmarks"), i18n("Bookmarks"), this); acmBookmarks->setDelayed(false); m_bookmarkHandler = new KateBookmarkHandler(this, acmBookmarks->menu()); acmBookmarks->setShortcutContext(Qt::WidgetWithChildrenShortcut); // action for synchronizing the dir operator with the current document path KAction* syncFolder = new KAction(this); syncFolder->setShortcutContext(Qt::WidgetWithChildrenShortcut); syncFolder->setText(i18n("Current Document Folder")); syncFolder->setIcon(KIcon("system-switch-user")); connect(syncFolder, SIGNAL(triggered()), this, SLOT(setActiveDocumentDir())); m_actionCollection->addAction("sync_dir", syncFolder); m_actionCollection->addAction("bookmarks", acmBookmarks); // section for settings menu KActionMenu *optionsMenu = new KActionMenu(KIcon("configure"), i18n("Options"), this); optionsMenu->setDelayed(false); optionsMenu->addAction(m_dirOperator->actionCollection()->action("short view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("tree view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed tree view")); optionsMenu->addSeparator(); optionsMenu->addAction(m_dirOperator->actionCollection()->action("show hidden")); // action for synchronising the dir operator with the current document path m_autoSyncFolder = new KAction(this); m_autoSyncFolder->setCheckable(true); m_autoSyncFolder->setText(i18n("Automatically synchronize with current document")); m_autoSyncFolder->setIcon(KIcon("system-switch-user")); connect(m_autoSyncFolder, SIGNAL(triggered()), this, SLOT(autoSyncFolder())); optionsMenu->addAction(m_autoSyncFolder); m_actionCollection->addAction("configure", optionsMenu); } //END Protected // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>// // Author: Michael Cameron // Email: chronokun@hotmail.com // // Libraries Include #include "libraries.h" // Local Includes #include "objloader.h" #include "brush.h" static CObjLoader s_ObjLoader; std::string StringFromBrush(const TBrush& _krBrush) { std::stringstream ssOut; ssOut << "brush" << std::endl; ssOut << "\tvertices" << std::endl; ssOut << std::fixed; for(const TVector3d& krVertex : _krBrush.m_Positions) { ssOut << "\t\t" << krVertex.m_dX << " " << krVertex.m_dY << " " << krVertex.m_dZ << std::endl; } ssOut << "\tfaces" << std::endl; for(const std::vector<size_t>& krFace : _krBrush.m_Faces) { ssOut << "\t\t" << 0.0f << " " << 0.0f << " " << 1.0f << " " << 1.0f << " " << 0.0f; for(const size_t kIndex : krFace) { ssOut << " " << kIndex; } ssOut << std::endl; } return(ssOut.str()); } int main() { const bool kbLoaded = s_ObjLoader.LoadFile("monkey.obj"); if(!kbLoaded) { return(2); } std::vector<TBrush> Brushes; for(size_t i = 0; i < s_ObjLoader.GetFaceCount(0); ++i) { std::vector<TVector3d> Face; s_ObjLoader.GetFace(Face, 0, i); Brushes.push_back(ExtrudeBrushFromFace(Face)); } std::ofstream OutFile; OutFile.open("output.map"); if(OutFile.is_open()) { OutFile << "reflex map version 6\n" << "entity\n" << "\ttype WorldSpawn\n" << "\tColourXRGB32 clearColor ffffff\n" << "\tColourXRGB32 worldColor0 0\n" << "\tColourXRGB32 worldColor1 0\n"; for(const TBrush& krBrush : Brushes) { OutFile << StringFromBrush(krBrush); } OutFile.close(); } else { return(1); } return(0); }<commit_msg>Modified to take commandline arguments for file names.<commit_after>// // Author: Michael Cameron // Email: chronokun@hotmail.com // // Libraries Include #include "libraries.h" // Local Includes #include "objloader.h" #include "brush.h" static CObjLoader s_ObjLoader; std::string StringFromBrush(const TBrush& _krBrush) { std::stringstream ssOut; ssOut << "brush" << std::endl; ssOut << "\tvertices" << std::endl; ssOut << std::fixed; for(const TVector3d& krVertex : _krBrush.m_Positions) { ssOut << "\t\t" << krVertex.m_dX << " " << krVertex.m_dY << " " << krVertex.m_dZ << std::endl; } ssOut << "\tfaces" << std::endl; for(const std::vector<size_t>& krFace : _krBrush.m_Faces) { ssOut << "\t\t" << 0.0f << " " << 0.0f << " " << 1.0f << " " << 1.0f << " " << 0.0f; for(const size_t kIndex : krFace) { ssOut << " " << kIndex; } ssOut << std::endl; } return(ssOut.str()); } int main(const int _kiArgC, const char** _kppcArgv) { // Check we have correct number of parameters if(_kiArgC < 3) { return(3); } const bool kbLoaded = s_ObjLoader.LoadFile(_kppcArgv[1]); if(!kbLoaded) { return(2); } std::vector<TBrush> Brushes; for(size_t i = 0; i < s_ObjLoader.GetFaceCount(0); ++i) { std::vector<TVector3d> Face; s_ObjLoader.GetFace(Face, 0, i); Brushes.push_back(ExtrudeBrushFromFace(Face)); } std::ofstream OutFile; OutFile.open(_kppcArgv[2]); if(OutFile.is_open()) { OutFile << "reflex map version 6\n" << "entity\n" << "\ttype WorldSpawn\n" << "\tColourXRGB32 clearColor ffffff\n" << "\tColourXRGB32 worldColor0 0\n" << "\tColourXRGB32 worldColor1 0\n"; for(const TBrush& krBrush : Brushes) { OutFile << StringFromBrush(krBrush); } OutFile.close(); } else { return(1); } return(0); }<|endoftext|>
<commit_before>// Copyright (c) 2022 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "test_roudi_portmanager_fixture.hpp" namespace iox_test_roudi_portmanager { using namespace iox::popo; constexpr uint64_t RESPONSE_QUEUE_CAPACITY{2U}; constexpr uint64_t REQUEST_QUEUE_CAPACITY{2U}; ClientOptions createTestClientOptions() { return ClientOptions{RESPONSE_QUEUE_CAPACITY, iox::NodeName_t("node")}; } ServerOptions createTestServerOptions() { return ServerOptions{REQUEST_QUEUE_CAPACITY, iox::NodeName_t("node")}; } // BEGIN aquireClientPortData tests TEST_F(PortManager_test, AcquireClientPortDataReturnsPort) { ::testing::Test::RecordProperty("TEST_ID", "92225f2c-619a-425b-bba0-6a014822c4c3"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; clientOptions.responseQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; clientOptions.serverTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; m_portManager->acquireClientPortData(sd, clientOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .and_then([&](const auto& clientPortData) { EXPECT_THAT(clientPortData->m_serviceDescription, Eq(sd)); EXPECT_THAT(clientPortData->m_runtimeName, Eq(runtimeName)); EXPECT_THAT(clientPortData->m_nodeName, Eq(clientOptions.nodeName)); EXPECT_THAT(clientPortData->m_toBeDestroyed, Eq(false)); EXPECT_THAT(clientPortData->m_chunkReceiverData.m_queue.capacity(), Eq(clientOptions.responseQueueCapacity)); EXPECT_THAT(clientPortData->m_connectRequested, Eq(clientOptions.connectOnCreate)); EXPECT_THAT(clientPortData->m_chunkReceiverData.m_queueFullPolicy, Eq(clientOptions.responseQueueFullPolicy)); EXPECT_THAT(clientPortData->m_chunkSenderData.m_consumerTooSlowPolicy, Eq(clientOptions.serverTooSlowPolicy)); }) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); } // END aquireClientPortData tests // BEGIN aquireServerPortData tests TEST_F(PortManager_test, AcquireServerPortDataReturnsPort) { ::testing::Test::RecordProperty("TEST_ID", "776c51c4-074a-4404-b6a7-ed08f59f05a0"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = false; serverOptions.requestQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; serverOptions.clientTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .and_then([&](const auto& serverPortData) { EXPECT_THAT(serverPortData->m_serviceDescription, Eq(sd)); EXPECT_THAT(serverPortData->m_runtimeName, Eq(runtimeName)); EXPECT_THAT(serverPortData->m_nodeName, Eq(serverOptions.nodeName)); EXPECT_THAT(serverPortData->m_toBeDestroyed, Eq(false)); EXPECT_THAT(serverPortData->m_chunkReceiverData.m_queue.capacity(), Eq(serverOptions.requestQueueCapacity)); EXPECT_THAT(serverPortData->m_offeringRequested, Eq(serverOptions.offerOnCreate)); EXPECT_THAT(serverPortData->m_chunkReceiverData.m_queueFullPolicy, Eq(serverOptions.requestQueueFullPolicy)); EXPECT_THAT(serverPortData->m_chunkSenderData.m_consumerTooSlowPolicy, Eq(serverOptions.clientTooSlowPolicy)); }) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); } TEST_F(PortManager_test, AcquireServerPortDataWithSameServiceDescriptionTwiceCallsErrorHandlerAndReturnsError) { ::testing::Test::RecordProperty("TEST_ID", "9f2c24ba-192d-4ce8-a61a-fe40b42c655b"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto serverOptions = createTestServerOptions(); // first call must be successful m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); iox::cxx::optional<iox::Error> detectedError; auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler([&](const auto error, const auto, const auto errorLevel) { EXPECT_THAT(error, Eq(iox::Error::kPOSH__PORT_MANAGER_SERVERPORT_NOT_UNIQUE)); EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::MODERATE)); detectedError.emplace(error); }); // second call must fail m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .and_then([&](const auto&) { GTEST_FAIL() << "Expected PortPoolError::UNIQUE_SERVER_PORT_ALREADY_EXISTS but got ServerPortData"; }) .or_else([&](const auto& error) { EXPECT_THAT(error, Eq(PortPoolError::UNIQUE_SERVER_PORT_ALREADY_EXISTS)); }); EXPECT_TRUE(detectedError.has_value()); } TEST_F(PortManager_test, AcquireServerPortDataWithSameServiceDescriptionTwiceAndFirstPortMarkedToBeDestroyedReturnsPort) { ::testing::Test::RecordProperty("TEST_ID", "d7f2815d-f1ea-403d-9355-69470d92a10f"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto serverOptions = createTestServerOptions(); // first call must be successful auto serverPortDataResult = m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}); ASSERT_FALSE(serverPortDataResult.has_error()); serverPortDataResult.value()->m_toBeDestroyed = true; iox::cxx::optional<iox::Error> detectedError; auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler( [&](const auto error, const auto, const auto) { detectedError.emplace(error); }); // second call must now also succeed m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); detectedError.and_then( [&](const auto& error) { GTEST_FAIL() << "Expected error handler to not be called but got: " << error; }); } // END aquireServerPortData tests } // namespace iox_test_roudi_portmanager <commit_msg>iox-#27 Add PortManager tests for client and server discovery<commit_after>// Copyright (c) 2022 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "test_roudi_portmanager_fixture.hpp" namespace iox_test_roudi_portmanager { using namespace iox::popo; constexpr uint64_t RESPONSE_QUEUE_CAPACITY{2U}; constexpr uint64_t REQUEST_QUEUE_CAPACITY{2U}; ClientOptions createTestClientOptions() { return ClientOptions{RESPONSE_QUEUE_CAPACITY, iox::NodeName_t("node")}; } ServerOptions createTestServerOptions() { return ServerOptions{REQUEST_QUEUE_CAPACITY, iox::NodeName_t("node")}; } // BEGIN aquireClientPortData tests TEST_F(PortManager_test, AcquireClientPortDataReturnsPort) { ::testing::Test::RecordProperty("TEST_ID", "92225f2c-619a-425b-bba0-6a014822c4c3"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; clientOptions.responseQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; clientOptions.serverTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; m_portManager->acquireClientPortData(sd, clientOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .and_then([&](const auto& clientPortData) { EXPECT_THAT(clientPortData->m_serviceDescription, Eq(sd)); EXPECT_THAT(clientPortData->m_runtimeName, Eq(runtimeName)); EXPECT_THAT(clientPortData->m_nodeName, Eq(clientOptions.nodeName)); EXPECT_THAT(clientPortData->m_toBeDestroyed, Eq(false)); EXPECT_THAT(clientPortData->m_chunkReceiverData.m_queue.capacity(), Eq(clientOptions.responseQueueCapacity)); EXPECT_THAT(clientPortData->m_connectRequested, Eq(clientOptions.connectOnCreate)); EXPECT_THAT(clientPortData->m_chunkReceiverData.m_queueFullPolicy, Eq(clientOptions.responseQueueFullPolicy)); EXPECT_THAT(clientPortData->m_chunkSenderData.m_consumerTooSlowPolicy, Eq(clientOptions.serverTooSlowPolicy)); }) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); } // END aquireClientPortData tests // BEGIN aquireServerPortData tests TEST_F(PortManager_test, AcquireServerPortDataReturnsPort) { ::testing::Test::RecordProperty("TEST_ID", "776c51c4-074a-4404-b6a7-ed08f59f05a0"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = false; serverOptions.requestQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; serverOptions.clientTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .and_then([&](const auto& serverPortData) { EXPECT_THAT(serverPortData->m_serviceDescription, Eq(sd)); EXPECT_THAT(serverPortData->m_runtimeName, Eq(runtimeName)); EXPECT_THAT(serverPortData->m_nodeName, Eq(serverOptions.nodeName)); EXPECT_THAT(serverPortData->m_toBeDestroyed, Eq(false)); EXPECT_THAT(serverPortData->m_chunkReceiverData.m_queue.capacity(), Eq(serverOptions.requestQueueCapacity)); EXPECT_THAT(serverPortData->m_offeringRequested, Eq(serverOptions.offerOnCreate)); EXPECT_THAT(serverPortData->m_chunkReceiverData.m_queueFullPolicy, Eq(serverOptions.requestQueueFullPolicy)); EXPECT_THAT(serverPortData->m_chunkSenderData.m_consumerTooSlowPolicy, Eq(serverOptions.clientTooSlowPolicy)); }) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); } TEST_F(PortManager_test, AcquireServerPortDataWithSameServiceDescriptionTwiceCallsErrorHandlerAndReturnsError) { ::testing::Test::RecordProperty("TEST_ID", "9f2c24ba-192d-4ce8-a61a-fe40b42c655b"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto serverOptions = createTestServerOptions(); // first call must be successful m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); iox::cxx::optional<iox::Error> detectedError; auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler([&](const auto error, const auto, const auto errorLevel) { EXPECT_THAT(error, Eq(iox::Error::kPOSH__PORT_MANAGER_SERVERPORT_NOT_UNIQUE)); EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::MODERATE)); detectedError.emplace(error); }); // second call must fail m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .and_then([&](const auto&) { GTEST_FAIL() << "Expected PortPoolError::UNIQUE_SERVER_PORT_ALREADY_EXISTS but got ServerPortData"; }) .or_else([&](const auto& error) { EXPECT_THAT(error, Eq(PortPoolError::UNIQUE_SERVER_PORT_ALREADY_EXISTS)); }); EXPECT_TRUE(detectedError.has_value()); } TEST_F(PortManager_test, AcquireServerPortDataWithSameServiceDescriptionTwiceAndFirstPortMarkedToBeDestroyedReturnsPort) { ::testing::Test::RecordProperty("TEST_ID", "d7f2815d-f1ea-403d-9355-69470d92a10f"); const ServiceDescription sd{"hyp", "no", "toad"}; const RuntimeName_t runtimeName{"hypnotoad"}; auto serverOptions = createTestServerOptions(); // first call must be successful auto serverPortDataResult = m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}); ASSERT_FALSE(serverPortDataResult.has_error()); serverPortDataResult.value()->m_toBeDestroyed = true; iox::cxx::optional<iox::Error> detectedError; auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler( [&](const auto error, const auto, const auto) { detectedError.emplace(error); }); // second call must now also succeed m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {}) .or_else([&](const auto& error) { GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error); }); detectedError.and_then( [&](const auto& error) { GTEST_FAIL() << "Expected error handler to not be called but got: " << error; }); } // END aquireServerPortData tests // BEGIN discovery tests TEST_F(PortManager_test, CreateClientWithConnectOnCreateAndNoServerResultsInWaitForOffer) { ::testing::Test::RecordProperty("TEST_ID", "14070d7b-d8e1-4df5-84fc-119e5e126cde"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto clientPortUser = createClient(clientOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER)); } TEST_F(PortManager_test, DoDiscoveryWithClientConnectOnCreateAndNoServerResultsInClientNotConnected) { ::testing::Test::RecordProperty("TEST_ID", "6829e506-9f58-4253-bc42-469f2970a2c7"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto clientPortUser = createClient(clientOptions); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER)); } TEST_F(PortManager_test, CreateClientWithConnectOnCreateAndNotOfferingServerResultsInWaitForOffer) { ::testing::Test::RecordProperty("TEST_ID", "0f7098d0-2646-4c10-b347-9b57b0f593ce"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = false; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER)); } TEST_F(PortManager_test, CreateClientWithConnectOnCreateAndOfferingServerResultsInClientConnected) { ::testing::Test::RecordProperty("TEST_ID", "108170d4-786b-4266-ad2a-ef922188f70b"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, CreateServerWithOfferOnCreateAndClientWaitingToConnectResultsInClientConnected) { ::testing::Test::RecordProperty("TEST_ID", "b5bb10b2-bf9b-400e-ab5c-aa3a1e0e826f"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto clientPortUser = createClient(clientOptions); auto serverPortUser = createServer(serverOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, CreateClientWithNotConnectOnCreateAndNoServerResultsInClientNotConnected) { ::testing::Test::RecordProperty("TEST_ID", "fde662f1-f9e1-4302-be41-59a7a0bfa4e7"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; auto clientPortUser = createClient(clientOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED)); } TEST_F(PortManager_test, DoDiscoveryWithClientNotConnectOnCreateAndNoServerResultsInClientNotConnected) { ::testing::Test::RecordProperty("TEST_ID", "c59b7343-6277-4a4b-8204-506048726be4"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; auto clientPortUser = createClient(clientOptions); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED)); } TEST_F(PortManager_test, CreateClientWithNotConnectOnCreateAndOfferingServerResultsInClientNotConnected) { ::testing::Test::RecordProperty("TEST_ID", "17cf22ba-066a-418a-8366-1c6b75177b9a"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED)); } TEST_F(PortManager_test, DoDiscoveryWithClientNotConnectOnCreateAndServerResultsInConnectedWhenCallingConnect) { ::testing::Test::RecordProperty("TEST_ID", "87bbb991-4aaf-49c1-b238-d9b0bb18d699"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); clientPortUser.connect(); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInClientNotConnectedWhenCallingDisconnect) { ::testing::Test::RecordProperty("TEST_ID", "b6826f93-096d-473d-b846-ab824efff1ee"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); clientPortUser.disconnect(); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED)); } TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInWaitForOfferWhenCallingStopOffer) { ::testing::Test::RecordProperty("TEST_ID", "45c9cc27-4198-4539-943f-2111ae2d1368"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); serverPortUser.stopOffer(); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER)); } TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInWaitForOfferWhenServerIsDestroyed) { ::testing::Test::RecordProperty("TEST_ID", "585ad47d-1a03-4599-a4dc-57ea1fb6eac7"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); serverPortUser.destroy(); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER)); } TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInNoClientsWhenClientIsDestroyed) { ::testing::Test::RecordProperty("TEST_ID", "3be2f7b5-7e22-4676-a25b-c8a93a4aaa7d"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser = createClient(clientOptions); EXPECT_TRUE(serverPortUser.hasClients()); clientPortUser.destroy(); m_portManager->doDiscovery(); EXPECT_FALSE(serverPortUser.hasClients()); } TEST_F(PortManager_test, CreateMultipleClientsWithConnectOnCreateAndOfferingServerResultsInAllClientsConnected) { ::testing::Test::RecordProperty("TEST_ID", "08f9981f-2585-4574-b0fc-c16cf0eef7d4"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = true; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser1 = createClient(clientOptions); auto clientPortUser2 = createClient(clientOptions); EXPECT_THAT(clientPortUser1.getConnectionState(), Eq(ConnectionState::CONNECTED)); EXPECT_THAT(clientPortUser2.getConnectionState(), Eq(ConnectionState::CONNECTED)); } TEST_F(PortManager_test, DoDiscoveryWithMultipleClientsNotConnectedAndOfferingServerResultsSomeClientsConnectedWhenSomeClientsCallConnect) { ::testing::Test::RecordProperty("TEST_ID", "7d210259-7c50-479e-b108-bf9747ceb0ef"); auto clientOptions = createTestClientOptions(); clientOptions.connectOnCreate = false; auto serverOptions = createTestServerOptions(); serverOptions.offerOnCreate = true; auto serverPortUser = createServer(serverOptions); auto clientPortUser1 = createClient(clientOptions); auto clientPortUser2 = createClient(clientOptions); clientPortUser2.connect(); m_portManager->doDiscovery(); EXPECT_THAT(clientPortUser1.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED)); EXPECT_THAT(clientPortUser2.getConnectionState(), Eq(ConnectionState::CONNECTED)); } // END discovery tests } // namespace iox_test_roudi_portmanager <|endoftext|>
<commit_before>#include "include/settingsmas.h" #include <QApplication> #include <QSettings> #include <QVariant> #include <QDir> SettingsMAS::SettingsMAS(QObject *parent) : QObject(parent) { global = new QSettings( QApplication::organizationName(), QApplication::applicationName(), this ); } SettingsMAS::~SettingsMAS() { if( global ) delete global; if( kitFile ) delete kitFile; } SettingsMAS &SettingsMAS::Instance() { static SettingsMAS singleInstance; return singleInstance; } void SettingsMAS::load(Settings *settings) { global->beginGroup( "Global" ); readArray( "Saved_Kits", "Kit", global, settings->savedKits ); readArray( "Last_Session", "Session", global, settings->session ); settings->savedKits.removeAll(""); settings->session.removeAll(""); global->endGroup(); global->beginGroup( "Window" ); settings->maxOpenTabs = global->value( "Max_Tabs" ).toInt(); settings->winPosX = global->value( "Pos_X" ).toInt(); settings->winPosY = global->value( "Pos_Y" ).toInt(); settings->winSizeX = global->value( "Size_X" ).toInt(); settings->winSizeY = global->value( "Size_Y" ).toInt(); global->endGroup(); QString mDir = qApp->applicationDirPath(); mDir += "/Market Kits"; if( !QDir().exists(mDir) ) QDir().mkdir(mDir); } void SettingsMAS::save(const Settings *settings) { clear(); global->beginGroup( "Global" ); writeArray( "Saved_Kits", "Kit", global, settings->savedKits ); writeArray( "Last_Session", "Session", global, settings->session ); global->endGroup(); global->beginGroup( "Window" ); global->setValue( "Max_Tabs", settings->maxOpenTabs ); global->setValue( "Pos_X", settings->winPosX ); global->setValue( "Pos_Y", settings->winPosY ); global->setValue( "Size_X", settings->winSizeX ); global->setValue( "Size_Y", settings->winSizeY ); global->endGroup(); } bool SettingsMAS::load(ConfigMT4 *configKit) { if( configKit->nameKit.contains( "New Market Kit" ) ) { loadDefault( configKit ); return true; } QString configFile = QString("%1/%2").arg( configKit->kitPath ) .arg( "config.ini" ); if( !QDir().exists(configFile) ) { return false; } kitFile = new QSettings( configFile, QSettings::IniFormat); kitFile->beginGroup( "Main" ); configKit->nameKit = kitFile->value( "Kit_Name" ).toString(); configKit->kitPath = kitFile->value( "Kit_Path" ).toString(); configKit->mt4Path = kitFile->value( "Mt4_Path" ).toString(); configKit->mt4Account = kitFile->value( "Mt4_Account" ).toInt(); configKit->server = kitFile->value( "Mt4_Server" ).toString(); configKit->historyPath = kitFile->value( "History_Path" ).toString(); readArray( "Servers", "Srv", kitFile, configKit->servers ); readArray( "Symbols", "Smb", kitFile, configKit->symbols ); kitFile->endGroup(); kitFile->beginGroup( "Model_Parameters" ); readArray( "Periods", "Tf", kitFile, configKit->periods ); readArray( "Input", "In", kitFile, configKit->input ); readArray( "Output", "Out", kitFile, configKit->output ); configKit->recurrentModel = kitFile->value( "Recurrent_Model" ).toBool(); configKit->readVolume = kitFile->value( "Read_Volume" ).toBool(); configKit->depthHistory = kitFile->value( "Depth_History" ).toInt(); configKit->depthPrediction = kitFile->value( "Depth_Prediction" ).toInt(); configKit->layersCount = kitFile->value( "LayersNN_Count" ).toInt(); readArray( "LayersNN_Sizes", "Size", kitFile, configKit->layersSize ); configKit->trainingMethod = kitFile->value( "Training_Method" ).toString(); readArray( "Training_Allocation", "Part", kitFile, configKit->divideInstances ); configKit->lastTraining.fromTime_t( kitFile->value( "Last_Training" ).toInt() ); configKit->isReady = kitFile->value( "Is_Ready" ).toBool(); configKit->isTrained = kitFile->value( "Is_Trained" ).toBool(); if( configKit->isTrained ) configKit->isLoaded = true; kitFile->endGroup(); delete kitFile; kitFile = 0; loadMt4Conf( configKit ); return true; } void SettingsMAS::save(const ConfigMT4 *configKit) { kitFile = new QSettings( QString("%1/%2").arg( configKit->kitPath ) .arg( "config.ini" ), QSettings::IniFormat); kitFile->beginGroup( "Main" ); kitFile->setValue( "Kit_Name", configKit->nameKit ); kitFile->setValue( "Kit_Path", configKit->kitPath ); kitFile->setValue( "Mt4_Path", configKit->mt4Path ); kitFile->setValue( "Mt4_Account", configKit->mt4Account ); kitFile->setValue( "Mt4_Server", configKit->server ); kitFile->setValue( "History_Path", configKit->historyPath ); writeArray( "Servers", "Srv", kitFile, configKit->servers ); writeArray( "Symbols", "Smb", kitFile, configKit->symbols ); kitFile->endGroup(); kitFile->beginGroup( "Model_Parameters" ); writeArray( "Periods", "Tf", kitFile, configKit->periods ); writeArray( "Input", "In", kitFile, configKit->input ); writeArray( "Output", "Out", kitFile, configKit->output ); kitFile->setValue( "Recurrent_Model", configKit->recurrentModel ); kitFile->setValue( "Read_Volume", configKit->readVolume ); kitFile->setValue( "Depth_History", configKit->depthHistory ); kitFile->setValue( "Depth_Prediction", configKit->depthPrediction ); kitFile->setValue( "LayersNN_Count", configKit->layersCount ); writeArray( "LayersNN_Sizes", "Size", kitFile, configKit->layersSize ); kitFile->setValue( "Training_Method", configKit->trainingMethod ); writeArray( "Training_Allocation", "Part", kitFile, configKit->divideInstances ); kitFile->setValue( "Last_Training", configKit->lastTraining.toTime_t() ); kitFile->setValue( "Is_Ready", configKit->isReady ); kitFile->setValue( "Is_Trained", configKit->isTrained ); kitFile->endGroup(); delete kitFile; kitFile = 0; saveMt4Conf( configKit ); } void SettingsMAS::loadMt4Conf(ConfigMT4 *configKit) { kitFile = new QSettings( QString("%1%2").arg( configKit->mt4Path ) .arg( configKit->configFile ), QSettings::IniFormat); kitFile->beginGroup( "Main" ); configKit->mt4Account = kitFile->value( "Mt4_Account" ).toInt(); // readArray( "Servers", "Srv", kitFile, configKit->servers ); readArray( "Symbols", "Smb", kitFile, configKit->symbols ); kitFile->endGroup(); delete kitFile; kitFile = 0; } void SettingsMAS::saveMt4Conf(const ConfigMT4 *configKit) { kitFile = new QSettings( QString("%1%2").arg( configKit->mt4Path ) .arg( configKit->configFile ), QSettings::IniFormat); kitFile->beginGroup( "Main" ); QStringList temp; readArray( "Kit_Names", "Kit", kitFile, temp ); if( !temp.contains( configKit->nameKit ) ) temp.append( configKit->nameKit ); writeArray( "Kit_Names", "Kit", kitFile, temp ); kitFile->endGroup(); kitFile->beginGroup( configKit->nameKit ); kitFile->setValue( "Depth_Prediction", configKit->depthPrediction ); writeArray( "Input", "In", kitFile, configKit->input ); writeArray( "Output", "Out", kitFile, configKit->output ); kitFile->endGroup(); delete kitFile; kitFile = 0; } void SettingsMAS::deleteMAKit(ConfigMT4 *configKit) { kitFile = new QSettings( QString("%1%2") .arg( configKit->mt4Path ) .arg( configKit->configFile ), QSettings::IniFormat); kitFile->beginGroup( "Main" ); QStringList temp; readArray( "Kit_Names", "Kit", kitFile, temp ); temp.removeOne( configKit->nameKit ); writeArray( "Kit_Names", "Kit", kitFile, temp ); kitFile->endGroup(); kitFile->beginGroup( configKit->nameKit ); kitFile->remove( "Depth_Prediction" ); kitFile->remove( "Input" ); kitFile->remove( "Output" ); kitFile->endGroup(); delete kitFile; kitFile = 0; configKit->removePath( configKit->kitPath ); } void SettingsMAS::readArray(const QString &arrayName, const QString &valueName, QSettings *setups, QStringList &list) { list.clear(); qint32 size = setups->beginReadArray( arrayName ); for( qint32 i = 0; i < size; i++ ) { setups->setArrayIndex( i ); list.append( setups->value( valueName ).toString() ); } setups->endArray(); } void SettingsMAS::readArray(const QString &arrayName, const QString &valueName, QSettings *setups, QList<qint32> &list) { list.clear(); qint32 size = setups->beginReadArray( arrayName ); for( qint32 i = 0; i < size; i++ ) { setups->setArrayIndex( i ); list.append( setups->value( valueName ).toInt() ); } setups->endArray(); } void SettingsMAS::writeArray(const QString &arrayName, const QString &valueName, QSettings *setups, const QStringList &list) { setups->beginWriteArray( arrayName ); for( qint32 i = 0; i < list.size(); i++) { setups->setArrayIndex( i ); setups->setValue( valueName, list[i] ); } setups->endArray(); } void SettingsMAS::writeArray(const QString &arrayName, const QString &valueName, QSettings *setups, const QList<qint32> &list) { setups->beginWriteArray( arrayName ); for( qint32 i = 0; i < list.size(); i++) { setups->setArrayIndex( i ); setups->setValue( valueName, list[i] ); } setups->endArray(); } void SettingsMAS::loadDefault(ConfigMT4 *configKit) { configKit->input.append( "YEAR" ); configKit->input.append( "MONTH" ); configKit->input.append( "DAY" ); configKit->input.append( "WEEKDAY" ); configKit->input.append("EURUSD.pro1440"); configKit->output.append("EURUSD.pro1440"); configKit->periods.append( 1440 ); } void SettingsMAS::clear() { global->beginGroup( "Global" ); qint32 i = 0; while( global->contains( QString("Saved_Kits_%1").arg( i ) ) ) { global->remove( QString("Saved_Kits_%1").arg( i ) ); i++; } i = 0; while( global->contains( QString("Last_Session_%1").arg( i ) ) ) { global->remove( QString("Last_Session_%1").arg( i ) ); i++; } global->endGroup(); } <commit_msg>- change IO methods for StringList;<commit_after>#include "include/settingsmas.h" #include <QApplication> #include <QSettings> #include <QVariant> #include <QDir> SettingsMAS::SettingsMAS(QObject *parent) : QObject(parent) { global = new QSettings( QApplication::organizationName(), QApplication::applicationName(), this ); } SettingsMAS::~SettingsMAS() { if( global ) delete global; if( kitFile ) delete kitFile; } SettingsMAS &SettingsMAS::Instance() { static SettingsMAS singleInstance; return singleInstance; } void SettingsMAS::load(Settings *settings) { global->beginGroup( "Global" ); readArray( "Saved_Kits", "Kit", global, settings->savedKits ); readArray( "Last_Session", "Session", global, settings->session ); settings->savedKits.removeAll(""); settings->session.removeAll(""); global->endGroup(); global->beginGroup( "Window" ); settings->maxOpenTabs = global->value( "Max_Tabs" ).toInt(); settings->winPosX = global->value( "Pos_X" ).toInt(); settings->winPosY = global->value( "Pos_Y" ).toInt(); settings->winSizeX = global->value( "Size_X" ).toInt(); settings->winSizeY = global->value( "Size_Y" ).toInt(); global->endGroup(); QString mDir = qApp->applicationDirPath(); mDir += "/Market Kits"; if( !QDir().exists(mDir) ) QDir().mkdir(mDir); } void SettingsMAS::save(const Settings *settings) { clear(); global->beginGroup( "Global" ); writeArray( "Saved_Kits", "Kit", global, settings->savedKits ); writeArray( "Last_Session", "Session", global, settings->session ); global->endGroup(); global->beginGroup( "Window" ); global->setValue( "Max_Tabs", settings->maxOpenTabs ); global->setValue( "Pos_X", settings->winPosX ); global->setValue( "Pos_Y", settings->winPosY ); global->setValue( "Size_X", settings->winSizeX ); global->setValue( "Size_Y", settings->winSizeY ); global->endGroup(); } bool SettingsMAS::load(ConfigMT4 *configKit) { if( configKit->nameKit.contains( "New Market Kit" ) ) { loadDefault( configKit ); return true; } QString configFile = QString("%1/%2").arg( configKit->kitPath ) .arg( "config.ini" ); if( !QDir().exists(configFile) ) { return false; } kitFile = new QSettings( configFile, QSettings::IniFormat); kitFile->beginGroup( "Main" ); configKit->nameKit = kitFile->value( "Kit_Name" ).toString(); configKit->kitPath = kitFile->value( "Kit_Path" ).toString(); configKit->mt4Path = kitFile->value( "Mt4_Path" ).toString(); configKit->mt4Account = kitFile->value( "Mt4_Account" ).toInt(); configKit->server = kitFile->value( "Mt4_Server" ).toString(); configKit->historyPath = kitFile->value( "History_Path" ).toString(); readArray( "Servers", "Srv", kitFile, configKit->servers ); readArray( "Symbols", "Smb", kitFile, configKit->symbols ); kitFile->endGroup(); kitFile->beginGroup( "Model_Parameters" ); readArray( "Periods", "Tf", kitFile, configKit->periods ); readArray( "Input", "In", kitFile, configKit->input ); readArray( "Output", "Out", kitFile, configKit->output ); configKit->recurrentModel = kitFile->value( "Recurrent_Model" ).toBool(); configKit->readVolume = kitFile->value( "Read_Volume" ).toBool(); configKit->depthHistory = kitFile->value( "Depth_History" ).toInt(); configKit->depthPrediction = kitFile->value( "Depth_Prediction" ).toInt(); configKit->layersCount = kitFile->value( "LayersNN_Count" ).toInt(); readArray( "LayersNN_Sizes", "Size", kitFile, configKit->layersSize ); configKit->trainingMethod = kitFile->value( "Training_Method" ).toString(); readArray( "Training_Allocation", "Part", kitFile, configKit->divideInstances ); configKit->lastTraining.fromTime_t( kitFile->value( "Last_Training" ).toInt() ); configKit->isReady = kitFile->value( "Is_Ready" ).toBool(); configKit->isTrained = kitFile->value( "Is_Trained" ).toBool(); if( configKit->isTrained ) configKit->isLoaded = true; kitFile->endGroup(); delete kitFile; kitFile = 0; loadMt4Conf( configKit ); return true; } void SettingsMAS::save(const ConfigMT4 *configKit) { kitFile = new QSettings( QString("%1/%2").arg( configKit->kitPath ) .arg( "config.ini" ), QSettings::IniFormat); kitFile->beginGroup( "Main" ); kitFile->setValue( "Kit_Name", configKit->nameKit ); kitFile->setValue( "Kit_Path", configKit->kitPath ); kitFile->setValue( "Mt4_Path", configKit->mt4Path ); kitFile->setValue( "Mt4_Account", configKit->mt4Account ); kitFile->setValue( "Mt4_Server", configKit->server ); kitFile->setValue( "History_Path", configKit->historyPath ); writeArray( "Servers", "Srv", kitFile, configKit->servers ); writeArray( "Symbols", "Smb", kitFile, configKit->symbols ); kitFile->endGroup(); kitFile->beginGroup( "Model_Parameters" ); writeArray( "Periods", "Tf", kitFile, configKit->periods ); writeArray( "Input", "In", kitFile, configKit->input ); writeArray( "Output", "Out", kitFile, configKit->output ); kitFile->setValue( "Recurrent_Model", configKit->recurrentModel ); kitFile->setValue( "Read_Volume", configKit->readVolume ); kitFile->setValue( "Depth_History", configKit->depthHistory ); kitFile->setValue( "Depth_Prediction", configKit->depthPrediction ); kitFile->setValue( "LayersNN_Count", configKit->layersCount ); writeArray( "LayersNN_Sizes", "Size", kitFile, configKit->layersSize ); kitFile->setValue( "Training_Method", configKit->trainingMethod ); writeArray( "Training_Allocation", "Part", kitFile, configKit->divideInstances ); kitFile->setValue( "Last_Training", configKit->lastTraining.toTime_t() ); kitFile->setValue( "Is_Ready", configKit->isReady ); kitFile->setValue( "Is_Trained", configKit->isTrained ); kitFile->endGroup(); delete kitFile; kitFile = 0; saveMt4Conf( configKit ); } void SettingsMAS::loadMt4Conf(ConfigMT4 *configKit) { kitFile = new QSettings( QString("%1%2").arg( configKit->mt4Path ) .arg( configKit->configFile ), QSettings::IniFormat); kitFile->beginGroup( "Main" ); configKit->mt4Account = kitFile->value( "Mt4_Account" ).toInt(); readArray( "Symbols", "Smb", kitFile, configKit->symbols ); kitFile->endGroup(); delete kitFile; kitFile = 0; } void SettingsMAS::saveMt4Conf(const ConfigMT4 *configKit) { kitFile = new QSettings( QString("%1%2").arg( configKit->mt4Path ) .arg( configKit->configFile ), QSettings::IniFormat); kitFile->beginGroup( "Main" ); QStringList temp; readArray( "Kit_Names", "Kit", kitFile, temp ); if( !temp.contains( configKit->nameKit ) ) temp.append( configKit->nameKit ); writeArray( "Kit_Names", "Kit", kitFile, temp ); kitFile->endGroup(); kitFile->beginGroup( configKit->nameKit ); kitFile->setValue( "Depth_Prediction", configKit->depthPrediction ); writeArray( "Input", "In", kitFile, configKit->input ); writeArray( "Output", "Out", kitFile, configKit->output ); kitFile->endGroup(); delete kitFile; kitFile = 0; } void SettingsMAS::deleteMAKit(ConfigMT4 *configKit) { kitFile = new QSettings( QString("%1%2") .arg( configKit->mt4Path ) .arg( configKit->configFile ), QSettings::IniFormat); kitFile->beginGroup( "Main" ); QStringList temp; readArray( "Kit_Names", "Kit", kitFile, temp ); temp.removeOne( configKit->nameKit ); writeArray( "Kit_Names", "Kit", kitFile, temp ); kitFile->endGroup(); kitFile->beginGroup( configKit->nameKit ); kitFile->remove( "Depth_Prediction" ); kitFile->remove( "Input" ); kitFile->remove( "Output" ); kitFile->endGroup(); delete kitFile; kitFile = 0; configKit->removePath( configKit->kitPath ); } void SettingsMAS::readArray(const QString &arrayName, const QString &valueName, QSettings *setups, QStringList &list) { Q_UNUSED(valueName); list.clear(); list = setups->value( arrayName ).toString().split( ";", QString::SkipEmptyParts ); } void SettingsMAS::readArray(const QString &arrayName, const QString &valueName, QSettings *setups, QList<qint32> &list) { list.clear(); qint32 size = setups->beginReadArray( arrayName ); for( qint32 i = 0; i < size; i++ ) { setups->setArrayIndex( i ); list.append( setups->value( valueName ).toInt() ); } setups->endArray(); } void SettingsMAS::writeArray(const QString &arrayName, const QString &valueName, QSettings *setups, const QStringList &list) { Q_UNUSED(valueName); QString tmp = ""; foreach( QString str, list ) { tmp += str; tmp += ";"; } tmp.remove( tmp.size() - 1, 1); setups->setValue( arrayName, tmp ); } void SettingsMAS::writeArray(const QString &arrayName, const QString &valueName, QSettings *setups, const QList<qint32> &list) { setups->beginWriteArray( arrayName ); for( qint32 i = 0; i < list.size(); i++) { setups->setArrayIndex( i ); setups->setValue( valueName, list[i] ); } setups->endArray(); } void SettingsMAS::loadDefault(ConfigMT4 *configKit) { configKit->input.append( "YEAR" ); configKit->input.append( "MONTH" ); configKit->input.append( "DAY" ); configKit->input.append( "WEEKDAY" ); configKit->input.append( "EURUSD.pro1440" ); configKit->output.append( "EURUSD.pro1440" ); configKit->periods.append( 1440 ); } void SettingsMAS::clear() { global->beginGroup( "Global" ); qint32 i = 0; while( global->contains( QString("Saved_Kits_%1").arg( i ) ) ) { global->remove( QString("Saved_Kits_%1").arg( i ) ); i++; } i = 0; while( global->contains( QString("Last_Session_%1").arg( i ) ) ) { global->remove( QString("Last_Session_%1").arg( i ) ); i++; } global->endGroup(); } <|endoftext|>
<commit_before>// MathPresso - Mathematical Expression Parser and JIT Compiler. // Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // [Dependencies] #include "MathPresso.h" #include "MathPresso_AST_p.h" #include "MathPresso_Optimizer_p.h" #include "MathPresso_Util_p.h" namespace MathPresso { Optimizer::Optimizer(WorkContext& ctx) : _ctx(ctx) { } Optimizer::~Optimizer() { } ASTElement* Optimizer::doNode(ASTElement* element) { switch (element->getElementType()) { case MELEMENT_BLOCK: return doBlock(reinterpret_cast<ASTBlock*>(element)); case MELEMENT_OPERATOR: return doOperator(reinterpret_cast<ASTOperator*>(element)); default: return element; } } ASTElement* Optimizer::doBlock(ASTBlock* element) { return element; } ASTElement* Optimizer::doOperator(ASTOperator* element) { ASTElement* left; ASTElement* right; left = element->_left = doNode(element->getLeft()); right = element->_right = doNode(element->getRight()); bool leftConst = left->isConstant(); bool rightConst = right->isConstant(); if (leftConst && rightConst) { // Both are constants, simplify them. mreal_t result = element->evaluate(NULL); ASTConstant* replacement = new ASTConstant(_ctx.genId(), result); replacement->_parent = element->getParent(); delete element; return replacement; } else if (leftConst || rightConst) { // Left or right is constant, we try to find another one in deeper which // could be joined. ASTElement* c; ASTElement* x; if (leftConst) { c = left; x = right; } else { c = right; x = left; } ASTElement* y = findConstNode(x, element->getOperatorType()); if (y != NULL) { ASTOperator* p = reinterpret_cast<ASTOperator*>(y->getParent()); ASTElement* keep; MP_ASSERT(p->getElementType() == MELEMENT_OPERATOR); mreal_t result; // Hardcoded evaluator (we accept only PLUS or MUL operators). switch (element->getOperatorType()) { case MOPERATOR_PLUS: result = c->evaluate(NULL) + y->evaluate(NULL); break; case MOPERATOR_MUL: result = c->evaluate(NULL) * y->evaluate(NULL); break; default: MP_ASSERT_NOT_REACHED(); } if (p->getRight() == y) { keep = p->getLeft(); p->_left = NULL; } else { keep = p->getRight(); p->_right = NULL; } p->getParent()->replaceChild(p, keep); delete p; reinterpret_cast<ASTConstant*>(c)->setValue(result); } } return element; } ASTElement* Optimizer::findConstNode(ASTElement* _element, int op) { if (_element->getElementType() != MELEMENT_OPERATOR) return NULL; ASTOperator* element = reinterpret_cast<ASTOperator*>(_element); int op0 = op; int op1 = element->getOperatorType(); if ((op0 == MOPERATOR_PLUS && op1 == MOPERATOR_PLUS) || (op0 == MOPERATOR_MUL && op1 == MOPERATOR_MUL ) ) { ASTElement* left = element->getLeft(); ASTElement* right = element->getRight(); if (left->isConstant()) return left; if (right->isConstant()) return right; if ((left = findConstNode(left, op)) != NULL) return left; if ((right = findConstNode(right, op)) != NULL) return right; } return NULL; } } // MathPresso namespace <commit_msg>fixed a bug http://code.google.com/p/mathpresso/issues/detail?id=2 mathpresso crashed on parsing expressions like "1 + x + sin(1)"<commit_after>// MathPresso - Mathematical Expression Parser and JIT Compiler. // Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // [Dependencies] #include "MathPresso.h" #include "MathPresso_AST_p.h" #include "MathPresso_Optimizer_p.h" #include "MathPresso_Util_p.h" namespace MathPresso { Optimizer::Optimizer(WorkContext& ctx) : _ctx(ctx) { } Optimizer::~Optimizer() { } ASTElement* Optimizer::doNode(ASTElement* element) { switch (element->getElementType()) { case MELEMENT_BLOCK: return doBlock(reinterpret_cast<ASTBlock*>(element)); case MELEMENT_OPERATOR: return doOperator(reinterpret_cast<ASTOperator*>(element)); default: return element; } } ASTElement* Optimizer::doBlock(ASTBlock* element) { return element; } ASTElement* Optimizer::doOperator(ASTOperator* element) { ASTElement* left; ASTElement* right; left = element->_left = doNode(element->getLeft()); right = element->_right = doNode(element->getRight()); bool leftConst = left->isConstant(); bool rightConst = right->isConstant(); if (leftConst && rightConst) { // Both are constants, simplify them. mreal_t result = element->evaluate(NULL); ASTConstant* replacement = new ASTConstant(_ctx.genId(), result); replacement->_parent = element->getParent(); delete element; return replacement; } else if (leftConst || rightConst) { // Left or right is constant, we try to find another one in deeper which // could be joined. ASTElement* c; ASTElement* x; if (leftConst) { c = left; x = right; } else { c = right; x = left; } ASTElement* y = findConstNode(x, element->getOperatorType()); if (y != NULL) { ASTOperator* p = reinterpret_cast<ASTOperator*>(y->getParent()); ASTElement* keep; MP_ASSERT(p->getElementType() == MELEMENT_OPERATOR); mreal_t result; // Hardcoded evaluator (we accept only PLUS or MUL operators). switch (element->getOperatorType()) { case MOPERATOR_PLUS: result = c->evaluate(NULL) + y->evaluate(NULL); break; case MOPERATOR_MUL: result = c->evaluate(NULL) * y->evaluate(NULL); break; default: MP_ASSERT_NOT_REACHED(); } if (p->getRight() == y) { keep = p->getLeft(); p->_left = NULL; } else { keep = p->getRight(); p->_right = NULL; } p->getParent()->replaceChild(p, keep); delete p; c->getParent()->replaceChild(c, new ASTConstant(c->getElementId(), result)); delete c; } } return element; } ASTElement* Optimizer::findConstNode(ASTElement* _element, int op) { if (_element->getElementType() != MELEMENT_OPERATOR) return NULL; ASTOperator* element = reinterpret_cast<ASTOperator*>(_element); int op0 = op; int op1 = element->getOperatorType(); if ((op0 == MOPERATOR_PLUS && op1 == MOPERATOR_PLUS) || (op0 == MOPERATOR_MUL && op1 == MOPERATOR_MUL ) ) { ASTElement* left = element->getLeft(); ASTElement* right = element->getRight(); if (left->isConstant()) return left; if (right->isConstant()) return right; if ((left = findConstNode(left, op)) != NULL) return left; if ((right = findConstNode(right, op)) != NULL) return right; } return NULL; } } // MathPresso namespace <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/zygote_host_linux.h" #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "base/base_switches.h" #include "base/command_line.h" #include "base/eintr_wrapper.h" #include "base/environment.h" #include "base/linux_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/pickle.h" #include "base/process_util.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "content/browser/content_browser_client.h" #include "content/browser/renderer_host/render_sandbox_host_linux.h" #include "content/common/content_switches.h" #include "content/common/process_watcher.h" #include "content/common/result_codes.h" #include "content/common/unix_domain_socket_posix.h" #include "sandbox/linux/suid/suid_unsafe_environment_variables.h" static void SaveSUIDUnsafeEnvironmentVariables() { // The ELF loader will clear many environment variables so we save them to // different names here so that the SUID sandbox can resolve them for the // renderer. for (unsigned i = 0; kSUIDUnsafeEnvironmentVariables[i]; ++i) { const char* const envvar = kSUIDUnsafeEnvironmentVariables[i]; char* const saved_envvar = SandboxSavedEnvironmentVariable(envvar); if (!saved_envvar) continue; scoped_ptr<base::Environment> env(base::Environment::Create()); std::string value; if (env->GetVar(envvar, &value)) env->SetVar(saved_envvar, value); else env->UnSetVar(saved_envvar); free(saved_envvar); } } ZygoteHost::ZygoteHost() : control_fd_(-1), pid_(-1), init_(false), using_suid_sandbox_(false), have_read_sandbox_status_word_(false), sandbox_status_(0) {} ZygoteHost::~ZygoteHost() { if (init_) close(control_fd_); } // static ZygoteHost* ZygoteHost::GetInstance() { return Singleton<ZygoteHost>::get(); } void ZygoteHost::Init(const std::string& sandbox_cmd) { DCHECK(!init_); init_ = true; FilePath chrome_path; CHECK(PathService::Get(base::FILE_EXE, &chrome_path)); CommandLine cmd_line(chrome_path); cmd_line.AppendSwitchASCII(switches::kProcessType, switches::kZygoteProcess); int fds[2]; #if defined(OS_FREEBSD) || defined(OS_OPENBSD) // The BSDs often don't support SOCK_SEQPACKET yet, so fall back to // SOCK_DGRAM if necessary. if (socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) != 0) CHECK(socketpair(PF_UNIX, SOCK_DGRAM, 0, fds) == 0); #else CHECK(socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) == 0); #endif base::file_handle_mapping_vector fds_to_map; fds_to_map.push_back(std::make_pair(fds[1], 3)); const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); if (browser_command_line.HasSwitch(switches::kZygoteCmdPrefix)) { cmd_line.PrependWrapper( browser_command_line.GetSwitchValueNative(switches::kZygoteCmdPrefix)); } // Append any switches from the browser process that need to be forwarded on // to the zygote/renderers. // Should this list be obtained from browser_render_process_host.cc? static const char* kForwardSwitches[] = { switches::kAllowSandboxDebugging, switches::kLoggingLevel, switches::kEnableLogging, // Support, e.g., --enable-logging=stderr. switches::kV, switches::kVModule, switches::kRegisterPepperPlugins, switches::kDisableSeccompSandbox, switches::kEnableSeccompSandbox, switches::kNaClLinuxHelper, }; cmd_line.CopySwitchesFrom(browser_command_line, kForwardSwitches, arraysize(kForwardSwitches)); content::GetContentClient()->browser()->AppendExtraCommandLineSwitches( &cmd_line, -1); sandbox_binary_ = sandbox_cmd.c_str(); if (!sandbox_cmd.empty()) { struct stat st; if (stat(sandbox_binary_.c_str(), &st) == 0 && access(sandbox_binary_.c_str(), X_OK) == 0 && (st.st_uid == 0) && (st.st_mode & S_ISUID) && (st.st_mode & S_IXOTH)) { using_suid_sandbox_ = true; cmd_line.PrependWrapper(sandbox_binary_); SaveSUIDUnsafeEnvironmentVariables(); } else { LOG(FATAL) << "The SUID sandbox helper binary was found, but is not " "configured correctly. Rather than run without sandboxing " "I'm aborting now. You need to make sure that " << sandbox_binary_ << " is mode 4755 and owned by root."; } } else { LOG(WARNING) << "Running without the SUID sandbox! See " "http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment " "for more information on developing with the sandbox on."; } // Start up the sandbox host process and get the file descriptor for the // renderers to talk to it. const int sfd = RenderSandboxHostLinux::GetInstance()->GetRendererSocket(); fds_to_map.push_back(std::make_pair(sfd, 5)); int dummy_fd = -1; if (using_suid_sandbox_) { dummy_fd = socket(PF_UNIX, SOCK_DGRAM, 0); CHECK(dummy_fd >= 0); fds_to_map.push_back(std::make_pair(dummy_fd, 7)); } base::ProcessHandle process = -1; base::LaunchOptions options; options.fds_to_remap = &fds_to_map; base::LaunchProcess(cmd_line.argv(), options, &process); CHECK(process != -1) << "Failed to launch zygote process"; if (using_suid_sandbox_) { // In the SUID sandbox, the real zygote is forked from the sandbox. // We need to look for it. // But first, wait for the zygote to tell us it's running. // The sending code is in chrome/browser/zygote_main_linux.cc. std::vector<int> fds_vec; const int kExpectedLength = sizeof(kZygoteMagic); char buf[kExpectedLength]; const ssize_t len = UnixDomainSocket::RecvMsg(fds[0], buf, sizeof(buf), &fds_vec); CHECK(len == kExpectedLength) << "Incorrect zygote magic length"; CHECK(0 == strcmp(buf, kZygoteMagic)) << "Incorrect zygote magic"; std::string inode_output; ino_t inode = 0; // Figure out the inode for |dummy_fd|, close |dummy_fd| on our end, // and find the zygote process holding |dummy_fd|. if (base::FileDescriptorGetInode(&inode, dummy_fd)) { close(dummy_fd); std::vector<std::string> get_inode_cmdline; get_inode_cmdline.push_back(sandbox_binary_); get_inode_cmdline.push_back(base::kFindInodeSwitch); get_inode_cmdline.push_back(base::Int64ToString(inode)); CommandLine get_inode_cmd(get_inode_cmdline); if (base::GetAppOutput(get_inode_cmd, &inode_output)) { base::StringToInt(inode_output, &pid_); } } CHECK(pid_ > 0) << "Did not find zygote process (using sandbox binary " << sandbox_binary_ << ")"; if (process != pid_) { // Reap the sandbox. ProcessWatcher::EnsureProcessGetsReaped(process); } } else { // Not using the SUID sandbox. pid_ = process; } close(fds[1]); control_fd_ = fds[0]; Pickle pickle; pickle.WriteInt(kCmdGetSandboxStatus); std::vector<int> empty_fds; if (!UnixDomainSocket::SendMsg(control_fd_, pickle.data(), pickle.size(), empty_fds)) LOG(FATAL) << "Cannot communicate with zygote"; // We don't wait for the reply. We'll read it in ReadReply. } ssize_t ZygoteHost::ReadReply(void* buf, size_t buf_len) { // At startup we send a kCmdGetSandboxStatus request to the zygote, but don't // wait for the reply. Thus, the first time that we read from the zygote, we // get the reply to that request. if (!have_read_sandbox_status_word_) { if (HANDLE_EINTR(read(control_fd_, &sandbox_status_, sizeof(sandbox_status_))) != sizeof(sandbox_status_)) { return -1; } have_read_sandbox_status_word_ = true; } return HANDLE_EINTR(read(control_fd_, buf, buf_len)); } pid_t ZygoteHost::ForkRequest( const std::vector<std::string>& argv, const base::GlobalDescriptors::Mapping& mapping, const std::string& process_type) { DCHECK(init_); Pickle pickle; pickle.WriteInt(kCmdFork); pickle.WriteString(process_type); pickle.WriteInt(argv.size()); for (std::vector<std::string>::const_iterator i = argv.begin(); i != argv.end(); ++i) pickle.WriteString(*i); pickle.WriteInt(mapping.size()); std::vector<int> fds; for (base::GlobalDescriptors::Mapping::const_iterator i = mapping.begin(); i != mapping.end(); ++i) { pickle.WriteUInt32(i->first); fds.push_back(i->second); } pid_t pid; { base::AutoLock lock(control_lock_); if (!UnixDomainSocket::SendMsg(control_fd_, pickle.data(), pickle.size(), fds)) return base::kNullProcessHandle; if (ReadReply(&pid, sizeof(pid)) != sizeof(pid)) return base::kNullProcessHandle; if (pid <= 0) return base::kNullProcessHandle; } const int kRendererScore = 5; AdjustRendererOOMScore(pid, kRendererScore); return pid; } void ZygoteHost::AdjustRendererOOMScore(base::ProcessHandle pid, int score) { // 1) You can't change the oom_adj of a non-dumpable process (EPERM) unless // you're root. Because of this, we can't set the oom_adj from the browser // process. // // 2) We can't set the oom_adj before entering the sandbox because the // zygote is in the sandbox and the zygote is as critical as the browser // process. Its oom_adj value shouldn't be changed. // // 3) A non-dumpable process can't even change its own oom_adj because it's // root owned 0644. The sandboxed processes don't even have /proc, but one // could imagine passing in a descriptor from outside. // // So, in the normal case, we use the SUID binary to change it for us. // However, Fedora (and other SELinux systems) don't like us touching other // process's oom_adj values // (https://bugzilla.redhat.com/show_bug.cgi?id=581256). // // The offical way to get the SELinux mode is selinux_getenforcemode, but I // don't want to add another library to the build as it's sure to cause // problems with other, non-SELinux distros. // // So we just check for /selinux. This isn't foolproof, but it's not bad // and it's easy. static bool selinux; static bool selinux_valid = false; if (!selinux_valid) { selinux = access("/selinux", X_OK) == 0; selinux_valid = true; } if (using_suid_sandbox_ && !selinux) { std::vector<std::string> adj_oom_score_cmdline; adj_oom_score_cmdline.push_back(sandbox_binary_); adj_oom_score_cmdline.push_back(base::kAdjustOOMScoreSwitch); adj_oom_score_cmdline.push_back(base::Int64ToString(pid)); adj_oom_score_cmdline.push_back(base::IntToString(score)); base::ProcessHandle sandbox_helper_process; if (base::LaunchProcess(adj_oom_score_cmdline, base::LaunchOptions(), &sandbox_helper_process)) { ProcessWatcher::EnsureProcessGetsReaped(sandbox_helper_process); } } else if (!using_suid_sandbox_) { if (!base::AdjustOOMScore(pid, score)) PLOG(ERROR) << "Failed to adjust OOM score of renderer with pid " << pid; } } void ZygoteHost::EnsureProcessTerminated(pid_t process) { DCHECK(init_); Pickle pickle; pickle.WriteInt(kCmdReap); pickle.WriteInt(process); if (HANDLE_EINTR(write(control_fd_, pickle.data(), pickle.size())) < 0) PLOG(ERROR) << "write"; } base::TerminationStatus ZygoteHost::GetTerminationStatus( base::ProcessHandle handle, int* exit_code) { DCHECK(init_); Pickle pickle; pickle.WriteInt(kCmdGetTerminationStatus); pickle.WriteInt(handle); // Set this now to handle the early termination cases. if (exit_code) *exit_code = content::RESULT_CODE_NORMAL_EXIT; static const unsigned kMaxMessageLength = 128; char buf[kMaxMessageLength]; ssize_t len; { base::AutoLock lock(control_lock_); if (HANDLE_EINTR(write(control_fd_, pickle.data(), pickle.size())) < 0) PLOG(ERROR) << "write"; len = ReadReply(buf, sizeof(buf)); } if (len == -1) { LOG(WARNING) << "Error reading message from zygote: " << errno; return base::TERMINATION_STATUS_NORMAL_TERMINATION; } else if (len == 0) { LOG(WARNING) << "Socket closed prematurely."; return base::TERMINATION_STATUS_NORMAL_TERMINATION; } Pickle read_pickle(buf, len); int status, tmp_exit_code; void* iter = NULL; if (!read_pickle.ReadInt(&iter, &status) || !read_pickle.ReadInt(&iter, &tmp_exit_code)) { LOG(WARNING) << "Error parsing GetTerminationStatus response from zygote."; return base::TERMINATION_STATUS_NORMAL_TERMINATION; } if (exit_code) *exit_code = tmp_exit_code; return static_cast<base::TerminationStatus>(status); } <commit_msg>Linux: Fix the sandbox error message when the helper binary is missing.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/zygote_host_linux.h" #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "base/base_switches.h" #include "base/command_line.h" #include "base/eintr_wrapper.h" #include "base/environment.h" #include "base/linux_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/pickle.h" #include "base/process_util.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "content/browser/content_browser_client.h" #include "content/browser/renderer_host/render_sandbox_host_linux.h" #include "content/common/content_switches.h" #include "content/common/process_watcher.h" #include "content/common/result_codes.h" #include "content/common/unix_domain_socket_posix.h" #include "sandbox/linux/suid/suid_unsafe_environment_variables.h" static void SaveSUIDUnsafeEnvironmentVariables() { // The ELF loader will clear many environment variables so we save them to // different names here so that the SUID sandbox can resolve them for the // renderer. for (unsigned i = 0; kSUIDUnsafeEnvironmentVariables[i]; ++i) { const char* const envvar = kSUIDUnsafeEnvironmentVariables[i]; char* const saved_envvar = SandboxSavedEnvironmentVariable(envvar); if (!saved_envvar) continue; scoped_ptr<base::Environment> env(base::Environment::Create()); std::string value; if (env->GetVar(envvar, &value)) env->SetVar(saved_envvar, value); else env->UnSetVar(saved_envvar); free(saved_envvar); } } ZygoteHost::ZygoteHost() : control_fd_(-1), pid_(-1), init_(false), using_suid_sandbox_(false), have_read_sandbox_status_word_(false), sandbox_status_(0) {} ZygoteHost::~ZygoteHost() { if (init_) close(control_fd_); } // static ZygoteHost* ZygoteHost::GetInstance() { return Singleton<ZygoteHost>::get(); } void ZygoteHost::Init(const std::string& sandbox_cmd) { DCHECK(!init_); init_ = true; FilePath chrome_path; CHECK(PathService::Get(base::FILE_EXE, &chrome_path)); CommandLine cmd_line(chrome_path); cmd_line.AppendSwitchASCII(switches::kProcessType, switches::kZygoteProcess); int fds[2]; #if defined(OS_FREEBSD) || defined(OS_OPENBSD) // The BSDs often don't support SOCK_SEQPACKET yet, so fall back to // SOCK_DGRAM if necessary. if (socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) != 0) CHECK(socketpair(PF_UNIX, SOCK_DGRAM, 0, fds) == 0); #else CHECK(socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) == 0); #endif base::file_handle_mapping_vector fds_to_map; fds_to_map.push_back(std::make_pair(fds[1], 3)); const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); if (browser_command_line.HasSwitch(switches::kZygoteCmdPrefix)) { cmd_line.PrependWrapper( browser_command_line.GetSwitchValueNative(switches::kZygoteCmdPrefix)); } // Append any switches from the browser process that need to be forwarded on // to the zygote/renderers. // Should this list be obtained from browser_render_process_host.cc? static const char* kForwardSwitches[] = { switches::kAllowSandboxDebugging, switches::kLoggingLevel, switches::kEnableLogging, // Support, e.g., --enable-logging=stderr. switches::kV, switches::kVModule, switches::kRegisterPepperPlugins, switches::kDisableSeccompSandbox, switches::kEnableSeccompSandbox, switches::kNaClLinuxHelper, }; cmd_line.CopySwitchesFrom(browser_command_line, kForwardSwitches, arraysize(kForwardSwitches)); content::GetContentClient()->browser()->AppendExtraCommandLineSwitches( &cmd_line, -1); sandbox_binary_ = sandbox_cmd.c_str(); if (!sandbox_cmd.empty()) { struct stat st; if (stat(sandbox_binary_.c_str(), &st) != 0) { LOG(FATAL) << "The SUID sandbox helper binary is missing: " << sandbox_binary_ << " Aborting now."; } if (access(sandbox_binary_.c_str(), X_OK) == 0 && (st.st_uid == 0) && (st.st_mode & S_ISUID) && (st.st_mode & S_IXOTH)) { using_suid_sandbox_ = true; cmd_line.PrependWrapper(sandbox_binary_); SaveSUIDUnsafeEnvironmentVariables(); } else { LOG(FATAL) << "The SUID sandbox helper binary was found, but is not " "configured correctly. Rather than run without sandboxing " "I'm aborting now. You need to make sure that " << sandbox_binary_ << " is mode 4755 and owned by root."; } } else { LOG(WARNING) << "Running without the SUID sandbox! See " "http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment " "for more information on developing with the sandbox on."; } // Start up the sandbox host process and get the file descriptor for the // renderers to talk to it. const int sfd = RenderSandboxHostLinux::GetInstance()->GetRendererSocket(); fds_to_map.push_back(std::make_pair(sfd, 5)); int dummy_fd = -1; if (using_suid_sandbox_) { dummy_fd = socket(PF_UNIX, SOCK_DGRAM, 0); CHECK(dummy_fd >= 0); fds_to_map.push_back(std::make_pair(dummy_fd, 7)); } base::ProcessHandle process = -1; base::LaunchOptions options; options.fds_to_remap = &fds_to_map; base::LaunchProcess(cmd_line.argv(), options, &process); CHECK(process != -1) << "Failed to launch zygote process"; if (using_suid_sandbox_) { // In the SUID sandbox, the real zygote is forked from the sandbox. // We need to look for it. // But first, wait for the zygote to tell us it's running. // The sending code is in chrome/browser/zygote_main_linux.cc. std::vector<int> fds_vec; const int kExpectedLength = sizeof(kZygoteMagic); char buf[kExpectedLength]; const ssize_t len = UnixDomainSocket::RecvMsg(fds[0], buf, sizeof(buf), &fds_vec); CHECK(len == kExpectedLength) << "Incorrect zygote magic length"; CHECK(0 == strcmp(buf, kZygoteMagic)) << "Incorrect zygote magic"; std::string inode_output; ino_t inode = 0; // Figure out the inode for |dummy_fd|, close |dummy_fd| on our end, // and find the zygote process holding |dummy_fd|. if (base::FileDescriptorGetInode(&inode, dummy_fd)) { close(dummy_fd); std::vector<std::string> get_inode_cmdline; get_inode_cmdline.push_back(sandbox_binary_); get_inode_cmdline.push_back(base::kFindInodeSwitch); get_inode_cmdline.push_back(base::Int64ToString(inode)); CommandLine get_inode_cmd(get_inode_cmdline); if (base::GetAppOutput(get_inode_cmd, &inode_output)) { base::StringToInt(inode_output, &pid_); } } CHECK(pid_ > 0) << "Did not find zygote process (using sandbox binary " << sandbox_binary_ << ")"; if (process != pid_) { // Reap the sandbox. ProcessWatcher::EnsureProcessGetsReaped(process); } } else { // Not using the SUID sandbox. pid_ = process; } close(fds[1]); control_fd_ = fds[0]; Pickle pickle; pickle.WriteInt(kCmdGetSandboxStatus); std::vector<int> empty_fds; if (!UnixDomainSocket::SendMsg(control_fd_, pickle.data(), pickle.size(), empty_fds)) LOG(FATAL) << "Cannot communicate with zygote"; // We don't wait for the reply. We'll read it in ReadReply. } ssize_t ZygoteHost::ReadReply(void* buf, size_t buf_len) { // At startup we send a kCmdGetSandboxStatus request to the zygote, but don't // wait for the reply. Thus, the first time that we read from the zygote, we // get the reply to that request. if (!have_read_sandbox_status_word_) { if (HANDLE_EINTR(read(control_fd_, &sandbox_status_, sizeof(sandbox_status_))) != sizeof(sandbox_status_)) { return -1; } have_read_sandbox_status_word_ = true; } return HANDLE_EINTR(read(control_fd_, buf, buf_len)); } pid_t ZygoteHost::ForkRequest( const std::vector<std::string>& argv, const base::GlobalDescriptors::Mapping& mapping, const std::string& process_type) { DCHECK(init_); Pickle pickle; pickle.WriteInt(kCmdFork); pickle.WriteString(process_type); pickle.WriteInt(argv.size()); for (std::vector<std::string>::const_iterator i = argv.begin(); i != argv.end(); ++i) pickle.WriteString(*i); pickle.WriteInt(mapping.size()); std::vector<int> fds; for (base::GlobalDescriptors::Mapping::const_iterator i = mapping.begin(); i != mapping.end(); ++i) { pickle.WriteUInt32(i->first); fds.push_back(i->second); } pid_t pid; { base::AutoLock lock(control_lock_); if (!UnixDomainSocket::SendMsg(control_fd_, pickle.data(), pickle.size(), fds)) return base::kNullProcessHandle; if (ReadReply(&pid, sizeof(pid)) != sizeof(pid)) return base::kNullProcessHandle; if (pid <= 0) return base::kNullProcessHandle; } const int kRendererScore = 5; AdjustRendererOOMScore(pid, kRendererScore); return pid; } void ZygoteHost::AdjustRendererOOMScore(base::ProcessHandle pid, int score) { // 1) You can't change the oom_adj of a non-dumpable process (EPERM) unless // you're root. Because of this, we can't set the oom_adj from the browser // process. // // 2) We can't set the oom_adj before entering the sandbox because the // zygote is in the sandbox and the zygote is as critical as the browser // process. Its oom_adj value shouldn't be changed. // // 3) A non-dumpable process can't even change its own oom_adj because it's // root owned 0644. The sandboxed processes don't even have /proc, but one // could imagine passing in a descriptor from outside. // // So, in the normal case, we use the SUID binary to change it for us. // However, Fedora (and other SELinux systems) don't like us touching other // process's oom_adj values // (https://bugzilla.redhat.com/show_bug.cgi?id=581256). // // The offical way to get the SELinux mode is selinux_getenforcemode, but I // don't want to add another library to the build as it's sure to cause // problems with other, non-SELinux distros. // // So we just check for /selinux. This isn't foolproof, but it's not bad // and it's easy. static bool selinux; static bool selinux_valid = false; if (!selinux_valid) { selinux = access("/selinux", X_OK) == 0; selinux_valid = true; } if (using_suid_sandbox_ && !selinux) { std::vector<std::string> adj_oom_score_cmdline; adj_oom_score_cmdline.push_back(sandbox_binary_); adj_oom_score_cmdline.push_back(base::kAdjustOOMScoreSwitch); adj_oom_score_cmdline.push_back(base::Int64ToString(pid)); adj_oom_score_cmdline.push_back(base::IntToString(score)); base::ProcessHandle sandbox_helper_process; if (base::LaunchProcess(adj_oom_score_cmdline, base::LaunchOptions(), &sandbox_helper_process)) { ProcessWatcher::EnsureProcessGetsReaped(sandbox_helper_process); } } else if (!using_suid_sandbox_) { if (!base::AdjustOOMScore(pid, score)) PLOG(ERROR) << "Failed to adjust OOM score of renderer with pid " << pid; } } void ZygoteHost::EnsureProcessTerminated(pid_t process) { DCHECK(init_); Pickle pickle; pickle.WriteInt(kCmdReap); pickle.WriteInt(process); if (HANDLE_EINTR(write(control_fd_, pickle.data(), pickle.size())) < 0) PLOG(ERROR) << "write"; } base::TerminationStatus ZygoteHost::GetTerminationStatus( base::ProcessHandle handle, int* exit_code) { DCHECK(init_); Pickle pickle; pickle.WriteInt(kCmdGetTerminationStatus); pickle.WriteInt(handle); // Set this now to handle the early termination cases. if (exit_code) *exit_code = content::RESULT_CODE_NORMAL_EXIT; static const unsigned kMaxMessageLength = 128; char buf[kMaxMessageLength]; ssize_t len; { base::AutoLock lock(control_lock_); if (HANDLE_EINTR(write(control_fd_, pickle.data(), pickle.size())) < 0) PLOG(ERROR) << "write"; len = ReadReply(buf, sizeof(buf)); } if (len == -1) { LOG(WARNING) << "Error reading message from zygote: " << errno; return base::TERMINATION_STATUS_NORMAL_TERMINATION; } else if (len == 0) { LOG(WARNING) << "Socket closed prematurely."; return base::TERMINATION_STATUS_NORMAL_TERMINATION; } Pickle read_pickle(buf, len); int status, tmp_exit_code; void* iter = NULL; if (!read_pickle.ReadInt(&iter, &status) || !read_pickle.ReadInt(&iter, &tmp_exit_code)) { LOG(WARNING) << "Error parsing GetTerminationStatus response from zygote."; return base::TERMINATION_STATUS_NORMAL_TERMINATION; } if (exit_code) *exit_code = tmp_exit_code; return static_cast<base::TerminationStatus>(status); } <|endoftext|>
<commit_before>/* AkonadiRecord.cc KPilot ** ** Copyright (C) 2007 by Bertjan Broeksema <b.broeksema@kdemail.net> ** Copyright (C) 2007 by Jason "vanRijn" Kasper <vr@movingparts.net> */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published by ** the Free Software Foundation; either version 2.1 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ** MA 02110-1301, USA. */ /* ** Bug reports and questions can be sent to kde-pim@kde.org */ #include "akonadirecord.h" #include "options.h" #include "hhrecord.h" class AkonadiRecordPrivate : public QSharedData { public: Akonadi::Item fItem; QString fTempId; QDateTime fLastSyncDateTime; bool fDeleted; }; AkonadiRecord::AkonadiRecord( const Akonadi::Item& item, const QDateTime& lastSync ) : d( new AkonadiRecordPrivate ) { d->fItem = item; d->fLastSyncDateTime = lastSync; d->fDeleted = false; } AkonadiRecord::AkonadiRecord( const QString& id ) : d( new AkonadiRecordPrivate ) { d->fTempId = id; d->fDeleted = true; } AkonadiRecord::~AkonadiRecord() { } const QString AkonadiRecord::id() const { if( d->fTempId.isEmpty() ) { return QString::number( d->fItem.id() ); } else { return d->fTempId; } } Akonadi::Item AkonadiRecord::item() const { FUNCTIONSETUP; return d->fItem; } bool AkonadiRecord::isDeleted() const { FUNCTIONSETUP; return d->fDeleted; } bool AkonadiRecord::isModified() const { FUNCTIONSETUP; if( !d->fLastSyncDateTime.isValid() ) { // Whe the fLastSyncDateTime isn't valid, the record is most probably marked // for deletion and thus modified. return true; } return d->fItem.modificationTime() > d->fLastSyncDateTime; } void AkonadiRecord::setId( const QString &id ) { FUNCTIONSETUP; // Id's < 0 are temporary id's if( id.toLongLong() < 0 ) { d->fTempId = id; } else { d->fTempId = QString(); d->fItem.setId( id.toULongLong() ); } } void AkonadiRecord::setItem( const Akonadi::Item& item ) { FUNCTIONSETUP; d->fItem = item; // Make sure that we return the right id after updating the itemobject. setId( QString::number( item.id() ) ); } void AkonadiRecord::synced() { FUNCTIONSETUP; // Nothing to do here. } <commit_msg>Fix the time skew so that Akonadirecords don't show up as modified when they shouldn't.<commit_after>/* AkonadiRecord.cc KPilot ** ** Copyright (C) 2007 by Bertjan Broeksema <b.broeksema@kdemail.net> ** Copyright (C) 2007 by Jason "vanRijn" Kasper <vr@movingparts.net> */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published by ** the Free Software Foundation; either version 2.1 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ** MA 02110-1301, USA. */ /* ** Bug reports and questions can be sent to kde-pim@kde.org */ #include "akonadirecord.h" #include "options.h" #include "hhrecord.h" class AkonadiRecordPrivate : public QSharedData { public: Akonadi::Item fItem; QString fTempId; QDateTime fLastSyncDateTime; bool fDeleted; }; AkonadiRecord::AkonadiRecord( const Akonadi::Item& item, const QDateTime& lastSync ) : d( new AkonadiRecordPrivate ) { d->fItem = item; d->fLastSyncDateTime = lastSync; // Item times have UTC timeSpec d->fLastSyncDateTime.setTimeSpec( Qt::UTC ); d->fDeleted = false; } AkonadiRecord::AkonadiRecord( const QString& id ) : d( new AkonadiRecordPrivate ) { d->fTempId = id; d->fDeleted = true; } AkonadiRecord::~AkonadiRecord() { } const QString AkonadiRecord::id() const { if( d->fTempId.isEmpty() ) { return QString::number( d->fItem.id() ); } else { return d->fTempId; } } Akonadi::Item AkonadiRecord::item() const { FUNCTIONSETUP; return d->fItem; } bool AkonadiRecord::isDeleted() const { FUNCTIONSETUP; return d->fDeleted; } bool AkonadiRecord::isModified() const { FUNCTIONSETUP; if( !d->fLastSyncDateTime.isValid() ) { // Whe the fLastSyncDateTime isn't valid, the record is most probably marked // for deletion and thus modified. return true; } return d->fItem.modificationTime() > d->fLastSyncDateTime; } void AkonadiRecord::setId( const QString &id ) { FUNCTIONSETUP; // Id's < 0 are temporary id's if( id.toLongLong() < 0 ) { d->fTempId = id; } else { d->fTempId = QString(); d->fItem.setId( id.toULongLong() ); } } void AkonadiRecord::setItem( const Akonadi::Item& item ) { FUNCTIONSETUP; d->fItem = item; // Make sure that we return the right id after updating the itemobject. setId( QString::number( item.id() ) ); } void AkonadiRecord::synced() { FUNCTIONSETUP; // Nothing to do here. } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin developers // Copyright (c) 2017 Empinel/The Ion Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include "amount.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" /** * Main network */ //! Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, const uint64_t nTime, const uint32_t nNonce, const uint32_t nBits, const int32_t nVersion, const CAmount& genesisReward) { std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << nTime << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].nValue = genesisReward; vout[0].scriptPubKey = genesisOutputScript; CTransaction txNew(1, nTime, vin, vout, 0); CBlock genesis; genesis.nTime = nTime; genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; genesis.vtx.push_back(txNew); genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = genesis.BuildMerkleTree(); return genesis; } static CBlock CreateGenesisBlock(uint64_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { const char* pszTimestamp = "Mergecoin"; const CScript genesisOutputScript = CScript() << ParseHex("041aadd6b5f2ee8a8432c72508b439e34c0b5429a6cf92e75d1838cf7d66a862db322ffd2535f576fc40c4720d9256b98aa94fab575d486600e9fa4056358b3c76") << OP_CHECKSIG; return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward); } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xc8; pchMessageStart[1] = 0xe1; pchMessageStart[2] = 0xd5; pchMessageStart[3] = 0xec; vAlertPubKey = ParseHex("041aadd6b5f2ee8a8432c72508b439e34c0b5429a6cf92e75d1838cf7d66a862db322ffd2535f576fc40c4720d9256b98aa94fab575d486600e9fa4056358b3c76"); nDefaultPort = 17700; nRPCPort = 17705; nProofOfWorkLimit = uint256S("000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); nProofOfStakeLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); genesis = CreateGenesisBlock(1490261016, 14726149, 0x1e00ffff, 1, (1 * COIN)); hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000000fff99c6e3fef2f022d735112297c5449c3489c7fa233d6f4236c9282f4")); assert(genesis.hashMerkleRoot == uint256("0x38421312cad95506750557b1cef24bd0aebff2b7e2a33b1f4edad0b27106d476")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,50); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,178); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); vSeeds.push_back(CDNSSeedData("47.89.43.73", "47.89.43.73")); vSeeds.push_back(CDNSSeedData("43.241.232.45", "43.241.232.45")); vSeeds.push_back(CDNSSeedData("47.89.178.249", "47.89.178.249")); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nPoolMaxTransactions = 3; strDarksendPoolDummyAddress = "MqbMeTpdFfxiNcWHn255T2TneJTrUECCBE"; nLastPOWBlock = 20000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x2f; pchMessageStart[1] = 0xca; pchMessageStart[2] = 0x4e; pchMessageStart[3] = 0x3e; vAlertPubKey = ParseHex(""); nDefaultPort = 27170; nRPCPort = 27171; strDataDir = "testnet"; nProofOfWorkLimit = uint256S("000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); nProofOfStakeLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); genesis = CreateGenesisBlock(1490261016, 14726149 , 0x1e00ffff, 1, (1 * COIN)); hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000000fff99c6e3fef2f022d735112297c5449c3489c7fa233d6f4236c9282f4")); assert(genesis.hashMerkleRoot == uint256("0x38421312cad95506750557b1cef24bd0aebff2b7e2a33b1f4edad0b27106d476 ")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,97); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>fix for darksend<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin developers // Copyright (c) 2017 Empinel/The Ion Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include "amount.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" /** * Main network */ //! Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, const uint64_t nTime, const uint32_t nNonce, const uint32_t nBits, const int32_t nVersion, const CAmount& genesisReward) { std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << nTime << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].nValue = genesisReward; vout[0].scriptPubKey = genesisOutputScript; CTransaction txNew(1, nTime, vin, vout, 0); CBlock genesis; genesis.nTime = nTime; genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; genesis.vtx.push_back(txNew); genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = genesis.BuildMerkleTree(); return genesis; } static CBlock CreateGenesisBlock(uint64_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { const char* pszTimestamp = "Mergecoin"; const CScript genesisOutputScript = CScript() << ParseHex("041aadd6b5f2ee8a8432c72508b439e34c0b5429a6cf92e75d1838cf7d66a862db322ffd2535f576fc40c4720d9256b98aa94fab575d486600e9fa4056358b3c76") << OP_CHECKSIG; return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward); } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xc8; pchMessageStart[1] = 0xe1; pchMessageStart[2] = 0xd5; pchMessageStart[3] = 0xec; vAlertPubKey = ParseHex("041aadd6b5f2ee8a8432c72508b439e34c0b5429a6cf92e75d1838cf7d66a862db322ffd2535f576fc40c4720d9256b98aa94fab575d486600e9fa4056358b3c76"); nDefaultPort = 17700; nRPCPort = 17705; nProofOfWorkLimit = uint256S("000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); nProofOfStakeLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); genesis = CreateGenesisBlock(1490261016, 14726149, 0x1e00ffff, 1, (1 * COIN)); hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000000fff99c6e3fef2f022d735112297c5449c3489c7fa233d6f4236c9282f4")); assert(genesis.hashMerkleRoot == uint256("0x38421312cad95506750557b1cef24bd0aebff2b7e2a33b1f4edad0b27106d476")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,50); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,178); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); vSeeds.push_back(CDNSSeedData("47.89.43.73", "47.89.43.73")); vSeeds.push_back(CDNSSeedData("43.241.232.45", "43.241.232.45")); vSeeds.push_back(CDNSSeedData("47.89.178.249", "47.89.178.249")); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nPoolMaxTransactions = 3; strDarksendPoolDummyAddress = "MWfMjRGyVkV2A8JDN7JrxAhkScNDjVRArP"; nLastPOWBlock = 20000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x2f; pchMessageStart[1] = 0xca; pchMessageStart[2] = 0x4e; pchMessageStart[3] = 0x3e; vAlertPubKey = ParseHex(""); nDefaultPort = 27170; nRPCPort = 27171; strDataDir = "testnet"; nProofOfWorkLimit = uint256S("000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); nProofOfStakeLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); genesis = CreateGenesisBlock(1490261016, 14726149 , 0x1e00ffff, 1, (1 * COIN)); hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000000fff99c6e3fef2f022d735112297c5449c3489c7fa233d6f4236c9282f4")); assert(genesis.hashMerkleRoot == uint256("0x38421312cad95506750557b1cef24bd0aebff2b7e2a33b1f4edad0b27106d476 ")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,97); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkExceptionObject.h" #include "otbTerraSarCalibrationImageFilter.h" #include "otbImage.h" #include "otbVectorImage.h" #include "itkExtractImageFilter.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" int otbTerraSarCalibrationImageFilterTest(int argc, char * argv[]) { const char * inputFileName = argv[1]; const char * outputFileName = argv[2]; bool useMetadata = true; if(atoi(argv[3]) == 0) useMetadata = false; typedef otb::Image<double, 2> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; typedef otb::TerraSarCalibrationImageFilter<ImageType, ImageType> FilterType; typedef FilterType::DoubleVectorType DoubleVectorType; typedef FilterType::DoubleVectorVectorType DoubleVectorVectorType; typedef itk::ExtractImageFilter<ImageType, ImageType> ExtractorType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); FilterType::Pointer filter = FilterType::New(); ExtractorType::Pointer extractor = ExtractorType::New(); reader->SetFileName(inputFileName); writer->SetFileName(outputFileName); reader->UpdateOutputInformation(); filter->SetInput(reader->GetOutput()); if( !useMetadata ) { std::cout<<"pas de meeeeeeeeeeeeeeetadata"<<std::endl; DoubleVectorType coefs; coefs.push_back(1.); coefs.push_back(0.5); coefs.push_back(1.); coefs.push_back(0.1); DoubleVectorVectorType coefVect(1, coefs); coefs.clear(); coefs.push_back(10.); coefs.push_back(5); coefs.push_back(10); coefs.push_back(1); coefVect.push_back( coefs ); coefs.clear(); coefs.push_back(100); coefs.push_back(50); coefs.push_back(100); coefs.push_back(10); coefVect.push_back( coefs ); filter->SetNoisePolynomialCoefficientsList(coefVect); filter->SetCalFactor( 10 ); filter->SetNoiseRangeValidityMin( 0 ); filter->SetNoiseRangeValidityMax( 1 ); filter->SetNoiseRangeValidityRef( 0.5 ); filter->SetLocalIncidentAngle( 15 ); std::vector<double> timeUtc; timeUtc.push_back(1.); timeUtc.push_back(2.); timeUtc.push_back(3.); filter->SetTimeUTC(timeUtc); filter->SetPRF(50); writer->SetInput(filter->GetOutput()); } else { std::cout<<"meeeeeeeeeeeeeeeeeeeeeeetadata"<<std::endl; // Generate an extract from the large input ImageType::RegionType region; ImageType::IndexType id; id[0] = 50; id[1] = 100; ImageType::SizeType size; size[0] = 150; size[1] = 100; region.SetIndex(id); region.SetSize(size); extractor->SetExtractionRegion(region); extractor->SetInput(filter->GetOutput()); writer->SetInput(filter/*extractor*/->GetOutput()); } filter->SetUseFastCalibrationMethod( false ); writer->Update(); return EXIT_SUCCESS; } <commit_msg>ENH : deleting cout comments<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkExceptionObject.h" #include "otbTerraSarCalibrationImageFilter.h" #include "otbImage.h" #include "otbVectorImage.h" #include "itkExtractImageFilter.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" int otbTerraSarCalibrationImageFilterTest(int argc, char * argv[]) { const char * inputFileName = argv[1]; const char * outputFileName = argv[2]; bool useMetadata = true; if(atoi(argv[3]) == 0) useMetadata = false; typedef otb::Image<double, 2> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; typedef otb::TerraSarCalibrationImageFilter<ImageType, ImageType> FilterType; typedef FilterType::DoubleVectorType DoubleVectorType; typedef FilterType::DoubleVectorVectorType DoubleVectorVectorType; typedef itk::ExtractImageFilter<ImageType, ImageType> ExtractorType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); FilterType::Pointer filter = FilterType::New(); ExtractorType::Pointer extractor = ExtractorType::New(); reader->SetFileName(inputFileName); writer->SetFileName(outputFileName); reader->UpdateOutputInformation(); filter->SetInput(reader->GetOutput()); if( !useMetadata ) { DoubleVectorType coefs; coefs.push_back(1.); coefs.push_back(0.5); coefs.push_back(1.); coefs.push_back(0.1); DoubleVectorVectorType coefVect(1, coefs); coefs.clear(); coefs.push_back(10.); coefs.push_back(5); coefs.push_back(10); coefs.push_back(1); coefVect.push_back( coefs ); coefs.clear(); coefs.push_back(100); coefs.push_back(50); coefs.push_back(100); coefs.push_back(10); coefVect.push_back( coefs ); filter->SetNoisePolynomialCoefficientsList(coefVect); filter->SetCalFactor( 10 ); filter->SetNoiseRangeValidityMin( 0 ); filter->SetNoiseRangeValidityMax( 1 ); filter->SetNoiseRangeValidityRef( 0.5 ); filter->SetLocalIncidentAngle( 15 ); std::vector<double> timeUtc; timeUtc.push_back(1.); timeUtc.push_back(2.); timeUtc.push_back(3.); filter->SetTimeUTC(timeUtc); filter->SetPRF(50); writer->SetInput(filter->GetOutput()); } else { // Generate an extract from the large input ImageType::RegionType region; ImageType::IndexType id; id[0] = 50; id[1] = 100; ImageType::SizeType size; size[0] = 150; size[1] = 100; region.SetIndex(id); region.SetSize(size); extractor->SetExtractionRegion(region); extractor->SetInput(filter->GetOutput()); writer->SetInput(extractor->GetOutput()); } filter->SetUseFastCalibrationMethod( false ); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Original Code: Copyright (c) 2009-2014 The Bitcoin Core Developers // Modified Code: Copyright (c) 2014 Project Bitmark -> and now zmark // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0x46A83599, 0x48DC48A9, 0x5CDE19F5, 0xCC447A0B, 0x46A83593 // networks fixed seed nodes }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xf9; pchMessageStart[1] = 0xbe; pchMessageStart[2] = 0xb4; pchMessageStart[3] = 0xd9; vAlertPubKey = ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"); nDefaultPort = 8388; nRPCPort = 8387; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 21); nSubsidyHalvingInterval = 788000; // Build the genesis block. const char* pszTimestamp = "Insight for the benefit of all."; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 20 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04f88a76429dad346a10ecb5d36fcbf50bc2e009870e20c1a6df8db743e0b994afc1f91e079be8acc380b0ee7765519906e3d781519e9db48259f64160104939d8") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; // OLD LINE: genesis.nTime = 1405274442; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nTime = 1405274410; genesis.nNonce = 624724; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x6be0214f333f8e533c5723ec780cf370718d30326db67ff690a78bbfeba510ea")); // todo add more dns seeders vSeeds.push_back(CDNSSeedData("zmark.org", "seed.zmark.org")); base58Prefixes[PUBKEY_ADDRESS] = list_of(143); // z base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(271); // Z base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. // Testnet Genesis has a lower difficulty pchMessageStart[0] = 0x0b; pchMessageStart[1] = 0x11; pchMessageStart[2] = 0x09; pchMessageStart[3] = 0x07; vAlertPubKey = ParseHex("04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"); nDefaultPort = 8388; nRPCPort = 8387; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); strDataDir = "testnet3"; genesis.nTime = 1405274409; genesis.nNonce = 675600; genesis.nBits = bnProofOfWorkLimit.GetCompact(); hashGenesisBlock = genesis.GetHash(); //assert(hashGenesisBlock == uint256("0x23e5abab7d3ce67fbb64f467b3b02f25a35b563d428c75086c38eb72b76e3896")); vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("zmark.co", "test.zmark.co")); base58Prefixes[PUBKEY_ADDRESS] = list_of(130); // u base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(185); // U base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1405274400; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>fixed dns of seed<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Original Code: Copyright (c) 2009-2014 The Bitcoin Core Developers // Modified Code: Copyright (c) 2014 Project Bitmark -> and now zmark // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0x46A83599, 0x48DC48A9, 0x5CDE19F5, 0xCC447A0B, 0x46A83593 // networks fixed seed nodes }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xf9; pchMessageStart[1] = 0xbe; pchMessageStart[2] = 0xb4; pchMessageStart[3] = 0xd9; vAlertPubKey = ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"); nDefaultPort = 8388; nRPCPort = 8387; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 21); nSubsidyHalvingInterval = 788000; // Build the genesis block. const char* pszTimestamp = "Insight for the benefit of all."; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 20 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04f88a76429dad346a10ecb5d36fcbf50bc2e009870e20c1a6df8db743e0b994afc1f91e079be8acc380b0ee7765519906e3d781519e9db48259f64160104939d8") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; // OLD LINE: genesis.nTime = 1405274442; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nTime = 1405274410; genesis.nNonce = 624724; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x6be0214f333f8e533c5723ec780cf370718d30326db67ff690a78bbfeba510ea")); // todo add more dns seeders vSeeds.push_back(CDNSSeedData("seed.zmark.org")); base58Prefixes[PUBKEY_ADDRESS] = list_of(143); // z base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(271); // Z base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. // Testnet Genesis has a lower difficulty pchMessageStart[0] = 0x0b; pchMessageStart[1] = 0x11; pchMessageStart[2] = 0x09; pchMessageStart[3] = 0x07; vAlertPubKey = ParseHex("04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"); nDefaultPort = 8388; nRPCPort = 8387; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); strDataDir = "testnet3"; genesis.nTime = 1405274409; genesis.nNonce = 675600; genesis.nBits = bnProofOfWorkLimit.GetCompact(); hashGenesisBlock = genesis.GetHash(); //assert(hashGenesisBlock == uint256("0x23e5abab7d3ce67fbb64f467b3b02f25a35b563d428c75086c38eb72b76e3896")); vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("seed.zmark.co")); base58Prefixes[PUBKEY_ADDRESS] = list_of(130); // u base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(185); // U base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1405274400; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include "scrypt.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0xA2F39055, 0x5EF2E56F, 0x57D54ADA, 0x50F812B0, 0x256187D5 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfd; pchMessageStart[1] = 0xa4; pchMessageStart[2] = 0xdc; pchMessageStart[3] = 0x6c; vAlertPubKey = ParseHex("04d1832d7d0c59634d67d3023379403014c2878d0c2372d175219063a48fa06e6d429e09f36d3196ec544c2cfdd12d6fe510a399595f75ebb6da238eb5f70f2072"); nDefaultPort = 12340; nRPCPort = 12341; bnProofOfWorkLimit[ALGO_SHA256D] = CBigNum(~uint256(0) >> 32); // 1.00000000 bnProofOfWorkLimit[ALGO_SCRYPT] = CBigNum(~uint256(0) >> 20); bnProofOfWorkLimit[ALGO_GROESTL] = CBigNum(~uint256(0) >> 23); // 0.00195311 bnProofOfWorkLimit[ALGO_SKEIN] = CBigNum(~uint256(0) >> 23); // 0.00195311 bnProofOfWorkLimit[ALGO_QUBIT] = CBigNum(~uint256(0) >> 22); // 0.00097655 // Build the genesis block. const char* pszTimestamp = "Visir 10. oktober 2008 Gjaldeyrishoft sett a Islendinga"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 1 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04a5814813115273a109cff99907ba4a05d951873dae7acb6c973d0c9e7c88911a3dbc9aa600deac241b91707e7b4ffb30ad91c8e56e695a1ddf318592988afe0a") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1390598806; genesis.nBits = Params().ProofOfWorkLimit(ALGO_SCRYPT).GetCompact(); //genesis.nBits = 0x1e0fffff; genesis.nNonce = 538548; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x2a8e100939494904af825b488596ddd536b3a96226ad02e0f7ab7ae472b27a8e")); assert(genesis.hashMerkleRoot == uint256("0x8957e5e8d2f0e90c42e739ec62fcc5dd21064852da64b6528ebd46567f222169")); vSeeds.push_back(CDNSSeedData("luxembourgh", "s1.auroraseed.net")); vSeeds.push_back(CDNSSeedData("united-states-west", "aurseed1.criptoe.com")); vSeeds.push_back(CDNSSeedData("united-states-east", "s1.auroraseed.com")); vSeeds.push_back(CDNSSeedData("iceland", "s1.auroraseed.org")); vSeeds.push_back(CDNSSeedData("the-netherlands", "s1.auroraseed.eu")); base58Prefixes[PUBKEY_ADDRESS] = list_of(23); base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(176); base58Prefixes[SECRET_KEY_OLD] = list_of(158); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // Testnet class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfd; pchMessageStart[1] = 0xa4; pchMessageStart[2] = 0xdc; pchMessageStart[3] = 0x6d; // the "d" seperates test net from main net nDefaultPort = 4321; nRPCPort = 14321; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1448114586; genesis.nNonce = 123378; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x1e47fdcb0dd34a6b28c47ef90768bea62694bb3fe712d2d2687c7c20df634131")); // If genesis block hash does not match, then generate new genesis hash. if (hashGenesisBlock != uint256("0x1e47fdcb0dd34a6b28c47ef90768bea62694bb3fe712d2d2687c7c20df634131")) { printf("Searching for testnet genesis block...\n"); // This will figure out a valid hash and Nonce if you're creating a different genesis block: //uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256(); uint256 thash; uint256 bestfound; //static char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; scrypt_1024_1_1_256(BEGIN(genesis.nVersion), BEGIN(bestfound)); while(true) { scrypt_1024_1_1_256(BEGIN(genesis.nVersion), BEGIN(thash)); //thash = scrypt_blockhash(BEGIN(block.nVersion)); if (thash <= hashTarget) break; //if ((genesis.nNonce & 0xFFF) == 0) if (thash <= bestfound) { bestfound = thash; printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++genesis.nNonce; if (genesis.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++genesis.nTime; } } printf("block.nTime = %u \n", genesis.nTime); printf("block.nNonce = %u \n", genesis.nNonce); printf("block.GetHash = %s\n", genesis.GetHash().ToString().c_str()); } vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("testnet-united-states-east", "testnet1.auroraseed.com")); vSeeds.push_back(CDNSSeedData("testnet-united-states-west", "testnet2.criptoe.com")); base58Prefixes[PUBKEY_ADDRESS] = list_of(111); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // Regression test class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; //nSubsidyHalvingInterval = 150; // bnProofOfWorkLimit = CBigNum(); genesis.nTime = 1296688602; genesis.nBits = 0x207fffff; genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 19444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>Revert previous change and return the minimum values for the algos to normal.<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include "scrypt.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0xA2F39055, 0x5EF2E56F, 0x57D54ADA, 0x50F812B0, 0x256187D5 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfd; pchMessageStart[1] = 0xa4; pchMessageStart[2] = 0xdc; pchMessageStart[3] = 0x6c; vAlertPubKey = ParseHex("04d1832d7d0c59634d67d3023379403014c2878d0c2372d175219063a48fa06e6d429e09f36d3196ec544c2cfdd12d6fe510a399595f75ebb6da238eb5f70f2072"); nDefaultPort = 12340; nRPCPort = 12341; bnProofOfWorkLimit[ALGO_SHA256D] = CBigNum(~uint256(0) >> 20); // 1.00000000 bnProofOfWorkLimit[ALGO_SCRYPT] = CBigNum(~uint256(0) >> 20); bnProofOfWorkLimit[ALGO_GROESTL] = CBigNum(~uint256(0) >> 20); // 0.00195311 bnProofOfWorkLimit[ALGO_SKEIN] = CBigNum(~uint256(0) >> 20); // 0.00195311 bnProofOfWorkLimit[ALGO_QUBIT] = CBigNum(~uint256(0) >> 20); // 0.00097655 // Build the genesis block. const char* pszTimestamp = "Visir 10. oktober 2008 Gjaldeyrishoft sett a Islendinga"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 1 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04a5814813115273a109cff99907ba4a05d951873dae7acb6c973d0c9e7c88911a3dbc9aa600deac241b91707e7b4ffb30ad91c8e56e695a1ddf318592988afe0a") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1390598806; genesis.nBits = Params().ProofOfWorkLimit(ALGO_SCRYPT).GetCompact(); //genesis.nBits = 0x1e0fffff; genesis.nNonce = 538548; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x2a8e100939494904af825b488596ddd536b3a96226ad02e0f7ab7ae472b27a8e")); assert(genesis.hashMerkleRoot == uint256("0x8957e5e8d2f0e90c42e739ec62fcc5dd21064852da64b6528ebd46567f222169")); vSeeds.push_back(CDNSSeedData("luxembourgh", "s1.auroraseed.net")); vSeeds.push_back(CDNSSeedData("united-states-west", "aurseed1.criptoe.com")); vSeeds.push_back(CDNSSeedData("united-states-east", "s1.auroraseed.com")); vSeeds.push_back(CDNSSeedData("iceland", "s1.auroraseed.org")); vSeeds.push_back(CDNSSeedData("the-netherlands", "s1.auroraseed.eu")); base58Prefixes[PUBKEY_ADDRESS] = list_of(23); base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(176); base58Prefixes[SECRET_KEY_OLD] = list_of(151); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // Testnet class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfd; pchMessageStart[1] = 0xa4; pchMessageStart[2] = 0xdc; pchMessageStart[3] = 0x6d; // the "d" seperates test net from main net nDefaultPort = 4321; nRPCPort = 14321; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1448114586; genesis.nNonce = 123378; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x1e47fdcb0dd34a6b28c47ef90768bea62694bb3fe712d2d2687c7c20df634131")); // If genesis block hash does not match, then generate new genesis hash. if (hashGenesisBlock != uint256("0x1e47fdcb0dd34a6b28c47ef90768bea62694bb3fe712d2d2687c7c20df634131")) { printf("Searching for testnet genesis block...\n"); // This will figure out a valid hash and Nonce if you're creating a different genesis block: //uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256(); uint256 thash; uint256 bestfound; //static char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; scrypt_1024_1_1_256(BEGIN(genesis.nVersion), BEGIN(bestfound)); while(true) { scrypt_1024_1_1_256(BEGIN(genesis.nVersion), BEGIN(thash)); //thash = scrypt_blockhash(BEGIN(block.nVersion)); if (thash <= hashTarget) break; //if ((genesis.nNonce & 0xFFF) == 0) if (thash <= bestfound) { bestfound = thash; printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++genesis.nNonce; if (genesis.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++genesis.nTime; } } printf("block.nTime = %u \n", genesis.nTime); printf("block.nNonce = %u \n", genesis.nNonce); printf("block.GetHash = %s\n", genesis.GetHash().ToString().c_str()); } vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("testnet-united-states-east", "testnet1.auroraseed.com")); vSeeds.push_back(CDNSSeedData("testnet-united-states-west", "testnet2.criptoe.com")); base58Prefixes[PUBKEY_ADDRESS] = list_of(111); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // Regression test class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; //nSubsidyHalvingInterval = 150; // bnProofOfWorkLimit = CBigNum(); genesis.nTime = 1296688602; genesis.nBits = 0x207fffff; genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 19444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0x3210ce66, 0x3213747b, 0x1717ba83, 0x3210ce66, 0x3213747b, 0x1715cc22, 0xbc8e2769, 0x36f8e397, 0x2a793a5b, 0x3251c027, 0x05fe6003, 0xaf73c92c, 0xd035bf02, 0xc06f4182, 0xa2f32110, }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xbf; pchMessageStart[1] = 0x0c; pchMessageStart[2] = 0x6b; pchMessageStart[3] = 0xbd; vAlertPubKey = ParseHex("048240a8748a80a286b270ba126705ced4f2ce5a7847b3610ea3c06513150dade2a8512ed5ea86320824683fc0818f0ac019214973e677acd1244f6d0571fc5103"); nDefaultPort = 9999; nRPCPort = 9998; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Dash starting difficulty is 1 / 2^12 nSubsidyHalvingInterval = 210000; // Genesis block const char* pszTimestamp = "Wired 09/Jan/2014 The Grand Experiment Goes Live: Overstock.com Is Now Accepting Bitcoins"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 50 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1390095618; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 28917698; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000ffd590b1485b3caadc19b22e6379c733355108f107a430458cdf3407ab6")); assert(genesis.hashMerkleRoot == uint256("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7")); vSeeds.push_back(CDNSSeedData("dashpay.io", "dnsseed.dashpay.io")); vSeeds.push_back(CDNSSeedData("dash.qa", "dnsseed.dash.qa")); vSeeds.push_back(CDNSSeedData("masternode.io", "dnsseed.masternode.io")); base58Prefixes[PUBKEY_ADDRESS] = list_of( 76); // Dash addresses start with 'X' base58Prefixes[SCRIPT_ADDRESS] = list_of( 16); // Dash script addresses start with '7' base58Prefixes[SECRET_KEY] = list_of(204); // Dash private keys start with '7' or 'X' base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0xF8); // Dash BIP32 pubkeys start with 'drkv' base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0xCC); // Dash BIP32 prvkeys start with 'drkp' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000005); // Dash BIP44 coin type is '5' // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xce; pchMessageStart[1] = 0xe2; pchMessageStart[2] = 0xca; pchMessageStart[3] = 0xff; vAlertPubKey = ParseHex("04517d8a699cb43d3938d7b24faaff7cda448ca4ea267723ba614784de661949bf632d6304316b244646dea079735b9a6fc4af804efb4752075b9fe2245e14e412"); nDefaultPort = 19999; nRPCPort = 19998; strDataDir = "testnet3"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1390666206; genesis.nNonce = 3861367235; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c")); vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("dashpay.io", "testnet-seed.dashpay.io")); vSeeds.push_back(CDNSSeedData("dash.qa", "testnet-seed.dash.qa")); vSeeds.push_back(CDNSSeedData("masternode.io", "test.dnsseed.masternode.io")); base58Prefixes[PUBKEY_ADDRESS] = list_of(139); // Testnet dash addresses start with 'x' or 'y' base58Prefixes[SCRIPT_ADDRESS] = list_of( 19); // Testnet dash script addresses start with '8' or '9' base58Prefixes[SECRET_KEY] = list_of(239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults) base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x3a)(0x80)(0x61)(0xa0); // Testnet dash BIP32 pubkeys start with 'DRKV' base58Prefixes[EXT_SECRET_KEY] = list_of(0x3a)(0x80)(0x58)(0x37); // Testnet dash BIP32 prvkeys start with 'DRKP' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000001); // Testnet dash BIP44 coin type is '5' (All coin's testnet default) } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0xc1; pchMessageStart[2] = 0xb7; pchMessageStart[3] = 0xdc; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1417713337; genesis.nBits = 0x207fffff; genesis.nNonce = 1096447; nDefaultPort = 19994; strDataDir = "regtest"; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>changed seeders<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0x3210ce66, 0x3213747b, 0x1717ba83, 0x3210ce66, 0x3213747b, 0x1715cc22, 0xbc8e2769, 0x36f8e397, 0x2a793a5b, 0x3251c027, 0x05fe6003, 0xaf73c92c, 0xd035bf02, 0xc06f4182, 0xa2f32110, }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xbf; pchMessageStart[1] = 0x0c; pchMessageStart[2] = 0x6b; pchMessageStart[3] = 0xbd; vAlertPubKey = ParseHex("048240a8748a80a286b270ba126705ced4f2ce5a7847b3610ea3c06513150dade2a8512ed5ea86320824683fc0818f0ac019214973e677acd1244f6d0571fc5103"); nDefaultPort = 9999; nRPCPort = 9998; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Dash starting difficulty is 1 / 2^12 nSubsidyHalvingInterval = 210000; // Genesis block const char* pszTimestamp = "Wired 09/Jan/2014 The Grand Experiment Goes Live: Overstock.com Is Now Accepting Bitcoins"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 50 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1390095618; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 28917698; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000ffd590b1485b3caadc19b22e6379c733355108f107a430458cdf3407ab6")); assert(genesis.hashMerkleRoot == uint256("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7")); vSeeds.push_back(CDNSSeedData("masternode.io", "dnsseed.masternode.io")); vSeeds.push_back(CDNSSeedData("darkcoin.qa", "dnsseed.darkcoin.qa")); vSeeds.push_back(CDNSSeedData("darkcoin.io", "dnsseed.darkcoin.io")); base58Prefixes[PUBKEY_ADDRESS] = list_of( 76); // Dash addresses start with 'X' base58Prefixes[SCRIPT_ADDRESS] = list_of( 16); // Dash script addresses start with '7' base58Prefixes[SECRET_KEY] = list_of(204); // Dash private keys start with '7' or 'X' base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0xF8); // Dash BIP32 pubkeys start with 'drkv' base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0xCC); // Dash BIP32 prvkeys start with 'drkp' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000005); // Dash BIP44 coin type is '5' // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xce; pchMessageStart[1] = 0xe2; pchMessageStart[2] = 0xca; pchMessageStart[3] = 0xff; vAlertPubKey = ParseHex("04517d8a699cb43d3938d7b24faaff7cda448ca4ea267723ba614784de661949bf632d6304316b244646dea079735b9a6fc4af804efb4752075b9fe2245e14e412"); nDefaultPort = 19999; nRPCPort = 19998; strDataDir = "testnet3"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1390666206; genesis.nNonce = 3861367235; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c")); vFixedSeeds.clear(); vSeeds.clear(); /*vSeeds.push_back(CDNSSeedData("dashpay.io", "testnet-seed.dashpay.io")); vSeeds.push_back(CDNSSeedData("dash.qa", "testnet-seed.dash.qa")); *///legacy seeders vSeeds.push_back(CDNSSeedData("darkcoin.qa", "testnet-seed.darkcoin.qa")); vSeeds.push_back(CDNSSeedData("masternode.io", "test.dnsseed.masternode.io")); vSeeds.push_back(CDNSSeedData("darkcoin.io", "testnet-seed.darkcoin.io")); base58Prefixes[PUBKEY_ADDRESS] = list_of(139); // Testnet dash addresses start with 'x' or 'y' base58Prefixes[SCRIPT_ADDRESS] = list_of( 19); // Testnet dash script addresses start with '8' or '9' base58Prefixes[SECRET_KEY] = list_of(239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults) base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x3a)(0x80)(0x61)(0xa0); // Testnet dash BIP32 pubkeys start with 'DRKV' base58Prefixes[EXT_SECRET_KEY] = list_of(0x3a)(0x80)(0x58)(0x37); // Testnet dash BIP32 prvkeys start with 'DRKP' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000001); // Testnet dash BIP44 coin type is '5' (All coin's testnet default) } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0xc1; pchMessageStart[2] = 0xb7; pchMessageStart[3] = 0xdc; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1417713337; genesis.nBits = 0x207fffff; genesis.nNonce = 1096447; nDefaultPort = 19994; strDataDir = "regtest"; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>#include <QtGui/QCursor> #include <QtGui/QStyleOptionGraphicsItem> #include <qmath.h> #include "rotater.h" using namespace qReal::interpreters::robots; using namespace details::d2Model; using namespace graphicsUtils; Rotater::Rotater() : AbstractItem() { setFlags(ItemIsSelectable | ItemIsMovable); setAcceptHoverEvents(true); setAcceptDrops(true); setCursor(QCursor(Qt::PointingHandCursor)); setZValue(2); mPen.setColor(Qt::blue); mPen.setWidth(3); mBrush.setStyle(Qt::NoBrush); } void Rotater::setMasterItem(RotateItem *masterItem) { mMaster = masterItem; mLength = 30; //mMaster->horizontalRadius();//asd QRectF const rect = mMaster->rect(); mMaster->setFlag(ItemClipsToShape, false); setParentItem(mMaster); // TODO: Dispose of hardcoding mX1 = rect.width(); mY1 = rect.height()/2; mX2 = mX1 + mLength; mY2 = mY1; } void Rotater::drawItem(QPainter *painter, const QStyleOptionGraphicsItem *style, QWidget *widget) { Q_UNUSED(style) Q_UNUSED(widget) painter->setOpacity(0.5); const int addLength = mLength / 3; qreal angle = addAngle; // must be equal mLength qreal checkLength = sqrt((mX2 - mX1) * (mX2 - mX1) + (mY2 - mY1) * (mY2 - mY1)); qreal x0 = ((checkLength - addLength) * mX2 + addLength * mX1) / checkLength; qreal y0 = ((checkLength - addLength) * mY2 + addLength * mY1) / checkLength; QPointF first = QTransform().translate(mX2 - x0, mY2 - y0).rotate(- angle).translate(- mX2 + x0, - mY2 + y0).rotate(angle).map(QPointF(x0, y0)); QPointF second = QTransform().translate(mX2 - x0, mY2 - y0).rotate(angle).translate(- mX2 + x0, - mY2 + y0).rotate(- angle).map(QPointF(x0, y0)); mLineImpl.drawItem(painter, mX1, mY1, mX2, mY2); mLineImpl.drawItem(painter, mX2, mY2, first.x(), first.y()); mLineImpl.drawItem(painter, mX2, mY2, second.x(), second.y()); } void Rotater::setPenBrushForExtraxtion(QPainter* painter, const QStyleOptionGraphicsItem* option) { Q_UNUSED(option) QPen pen(Qt::red); pen.setWidth(2); painter->setPen(pen); } void Rotater::drawExtractionForItem(QPainter* painter) { int driftForRotater = drift; if (drift > mMaster->horizontalRadius()) { driftForRotater = drift / 2; } mLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, driftForRotater); drawFieldForResizeItem(painter); } void Rotater::drawFieldForResizeItem(QPainter* painter) { int resizeDriftForRotater = resizeDrift; if (drift > mMaster->horizontalRadius()) { resizeDriftForRotater = resizeDrift / 2; } painter->drawEllipse(QPointF(mX2, mY2), resizeDriftForRotater, resizeDriftForRotater); } QRectF Rotater::boundingRect() const { return mLineImpl.boundingRect(mX1, mY1, mX2, mY2, mPen.width(), drift); } void Rotater::calcResizeItem(QGraphicsSceneMouseEvent *event) { // Cosine theorem qreal const x1 = event->pos().x(); qreal const y1 = event->pos().y(); qreal const x2 = event->lastPos().x(); qreal const y2 = event->lastPos().y(); qreal len = sqrt((x1*x1+y1*y1)*(x2*x2+y2*y2)); // Rotation sign is the sign of the vector product qreal const vectorProduct = x1*y2-x2*y1; int const sign = vectorProduct < 0 ? -1 : 1; qreal const eps = 10e-8; qreal const dalpha = len < eps ? 0 : acos((x1*x2+y1*y2)/len); mMaster->rotate(mMaster->rotation() - sign*dalpha*180/M_PI); } void Rotater::resizeItem(QGraphicsSceneMouseEvent *event) { if (mDragState == BottomRight) { AbstractItem::resizeItem(event); } } void Rotater::mousePressEvent(QGraphicsSceneMouseEvent * event) { AbstractItem::mousePressEvent(event); mMaster->setSelected(true); setFlag(ItemIsMovable, false); } void Rotater::mouseMoveEvent(QGraphicsSceneMouseEvent * event) { AbstractItem::mouseMoveEvent(event); mMaster->setSelected(true); setFlag(ItemIsMovable, false); } void Rotater::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { AbstractItem::mouseReleaseEvent(event); setFlag(ItemIsMovable, false); } <commit_msg>Fixed sensor dragging when selected<commit_after>#include <QtGui/QCursor> #include <QtGui/QStyleOptionGraphicsItem> #include <qmath.h> #include "rotater.h" using namespace qReal::interpreters::robots; using namespace details::d2Model; using namespace graphicsUtils; Rotater::Rotater() : AbstractItem() { setFlags(ItemIsSelectable | ItemIsMovable); setAcceptHoverEvents(true); setAcceptDrops(true); setCursor(QCursor(Qt::PointingHandCursor)); setZValue(2); mPen.setColor(Qt::blue); mPen.setWidth(3); mBrush.setStyle(Qt::NoBrush); } void Rotater::setMasterItem(RotateItem *masterItem) { mMaster = masterItem; mLength = 30; //mMaster->horizontalRadius();//asd QRectF const rect = mMaster->rect(); mMaster->setFlag(ItemClipsToShape, false); setParentItem(mMaster); // TODO: Dispose of hardcoding mX1 = rect.width(); mY1 = rect.height()/2; mX2 = mX1 + mLength; mY2 = mY1; } void Rotater::drawItem(QPainter *painter, const QStyleOptionGraphicsItem *style, QWidget *widget) { Q_UNUSED(style) Q_UNUSED(widget) painter->setOpacity(0.5); const int addLength = mLength / 3; qreal angle = addAngle; // must be equal mLength qreal checkLength = sqrt((mX2 - mX1) * (mX2 - mX1) + (mY2 - mY1) * (mY2 - mY1)); qreal x0 = ((checkLength - addLength) * mX2 + addLength * mX1) / checkLength; qreal y0 = ((checkLength - addLength) * mY2 + addLength * mY1) / checkLength; QPointF first = QTransform().translate(mX2 - x0, mY2 - y0).rotate(- angle).translate(- mX2 + x0, - mY2 + y0).rotate(angle).map(QPointF(x0, y0)); QPointF second = QTransform().translate(mX2 - x0, mY2 - y0).rotate(angle).translate(- mX2 + x0, - mY2 + y0).rotate(- angle).map(QPointF(x0, y0)); mLineImpl.drawItem(painter, mX1, mY1, mX2, mY2); mLineImpl.drawItem(painter, mX2, mY2, first.x(), first.y()); mLineImpl.drawItem(painter, mX2, mY2, second.x(), second.y()); } void Rotater::setPenBrushForExtraxtion(QPainter* painter, const QStyleOptionGraphicsItem* option) { Q_UNUSED(option) QPen pen(Qt::red); pen.setWidth(2); painter->setPen(pen); } void Rotater::drawExtractionForItem(QPainter* painter) { int driftForRotater = drift; if (drift > mMaster->horizontalRadius()) { driftForRotater = drift / 2; } mLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, driftForRotater); drawFieldForResizeItem(painter); } void Rotater::drawFieldForResizeItem(QPainter* painter) { int resizeDriftForRotater = resizeDrift; if (drift > mMaster->horizontalRadius()) { resizeDriftForRotater = resizeDrift / 2; } painter->drawEllipse(QPointF(mX2, mY2), resizeDriftForRotater, resizeDriftForRotater); } QRectF Rotater::boundingRect() const { return mLineImpl.boundingRect(mX1, mY1, mX2, mY2, mPen.width(), drift); } void Rotater::calcResizeItem(QGraphicsSceneMouseEvent *event) { // Cosine theorem qreal const x1 = event->pos().x(); qreal const y1 = event->pos().y(); qreal const x2 = event->lastPos().x(); qreal const y2 = event->lastPos().y(); qreal len = sqrt((x1*x1+y1*y1)*(x2*x2+y2*y2)); // Rotation sign is the sign of the vector product qreal const vectorProduct = x1*y2-x2*y1; int const sign = vectorProduct < 0 ? -1 : 1; qreal const eps = 10e-8; qreal const dalpha = len < eps ? 0 : acos((x1*x2+y1*y2)/len); mMaster->rotate(mMaster->rotation() - sign*dalpha*180/M_PI); } void Rotater::resizeItem(QGraphicsSceneMouseEvent *event) { if (mDragState == BottomRight) { setFlag(ItemIsMovable, false); AbstractItem::resizeItem(event); } } void Rotater::mousePressEvent(QGraphicsSceneMouseEvent * event) { AbstractItem::mousePressEvent(event); mMaster->setSelected(true); } void Rotater::mouseMoveEvent(QGraphicsSceneMouseEvent * event) { AbstractItem::mouseMoveEvent(event); mMaster->setSelected(true); } void Rotater::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { AbstractItem::mouseReleaseEvent(event); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief application endpoint server feature /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "ApplicationEndpointServer.h" #include <openssl/err.h> #include "Basics/delete_object.h" #include "Basics/ssl-helper.h" #include "Basics/RandomGenerator.h" #include "Dispatcher/ApplicationDispatcher.h" #include "HttpServer/HttpHandlerFactory.h" #include "HttpServer/HttpServer.h" #include "HttpServer/HttpsServer.h" #include "Logger/Logger.h" #include "Rest/OperationMode.h" #include "Scheduler/ApplicationScheduler.h" using namespace triagens::basics; using namespace triagens::rest; using namespace std; // ----------------------------------------------------------------------------- // --SECTION-- private classes // ----------------------------------------------------------------------------- namespace { class BIOGuard { public: BIOGuard(BIO *bio) : _bio(bio) { } ~BIOGuard() { BIO_free(_bio); } public: BIO *_bio; }; } // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Scheduler /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// ApplicationEndpointServer::ApplicationEndpointServer (ApplicationServer* applicationServer, ApplicationScheduler* applicationScheduler, ApplicationDispatcher* applicationDispatcher, std::string const& authenticationRealm, HttpHandlerFactory::auth_fptr checkAuthentication) : ApplicationFeature("EndpointServer"), _applicationServer(applicationServer), _applicationScheduler(applicationScheduler), _applicationDispatcher(applicationDispatcher), _authenticationRealm(authenticationRealm), _checkAuthentication(checkAuthentication), _handlerFactory(0), _servers(), _endpointList(), _httpPort(), _endpoints(), _disableAuthentication(false), _keepAliveTimeout(300.0), _backlogSize(10), _httpsKeyfile(), _cafile(), _sslProtocol(HttpsServer::TLS_V1), _sslCache(false), _sslOptions((uint64_t) (SSL_OP_TLS_ROLLBACK_BUG | SSL_OP_CIPHER_SERVER_PREFERENCE)), _sslCipherList(""), _sslContext(0), _rctx() { } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// ApplicationEndpointServer::~ApplicationEndpointServer () { // .......................................................................... // Where ever possible we should EXPLICITLY write down the type used in // a templated class/method etc. This makes it a lot easier to debug the // code. Granted however, that explicitly writing down the type for an // overloaded class operator is a little unwieldy. // .......................................................................... for_each(_servers.begin(), _servers.end(), triagens::basics::DeleteObjectAny()); _servers.clear(); if (_handlerFactory != 0) { delete _handlerFactory; } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Scheduler /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief builds the endpoint servers //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::buildServers () { assert(_handlerFactory != 0); assert(_applicationScheduler->scheduler() != 0); EndpointServer* server; // turn off authentication if (_disableAuthentication) { _handlerFactory->setRequireAuthentication(false); LOGGER_INFO("Authentication is turned off"); } // unencrypted endpoints if (_endpointList.count(Endpoint::PROTOCOL_HTTP, Endpoint::ENCRYPTION_NONE) > 0) { // http endpoints server = new HttpServer(_applicationScheduler->scheduler(), _applicationDispatcher->dispatcher(), _keepAliveTimeout, _handlerFactory); server->setEndpointList(&_endpointList); _servers.push_back(server); } // ssl endpoints if (_endpointList.count(Endpoint::PROTOCOL_HTTP, Endpoint::ENCRYPTION_SSL) > 0) { // check the ssl context if (_sslContext == 0) { LOGGER_INFO("please use the --server.keyfile option"); LOGGER_FATAL_AND_EXIT("no ssl context is known, cannot create https server"); } // https server = new HttpsServer(_applicationScheduler->scheduler(), _applicationDispatcher->dispatcher(), _keepAliveTimeout, _handlerFactory, _sslContext); server->setEndpointList(&_endpointList); _servers.push_back(server); } return true; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- ApplicationFeature methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ApplicationServer /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::setupOptions (map<string, ProgramOptionsDescription>& options) { // issue #175: add deprecated hidden option for downwards compatibility options[ApplicationServer::OPTIONS_HIDDEN] ("server.http-port", &_httpPort, "http port for client requests (deprecated)") ; options[ApplicationServer::OPTIONS_SERVER] ("server.endpoint", &_endpoints, "endpoint for client requests") ; options[ApplicationServer::OPTIONS_SERVER + ":help-admin"] ("server.disable-authentication", &_disableAuthentication, "disable authentication for ALL client requests") ("server.keep-alive-timeout", &_keepAliveTimeout, "keep-alive timeout in seconds") ("server.backlog-size", &_backlogSize, "listen backlog size") ; options[ApplicationServer::OPTIONS_SERVER + ":help-ssl"] ("server.keyfile", &_httpsKeyfile, "keyfile for SSL connections") ("server.cafile", &_cafile, "file containing the CA certificates of clients") ("server.ssl-protocol", &_sslProtocol, "1 = SSLv2, 2 = SSLv23, 3 = SSLv3, 4 = TLSv1") ("server.ssl-cache", &_sslCache, "use SSL session caching") ("server.ssl-options", &_sslOptions, "ssl options, see OpenSSL documentation") ("server.ssl-cipher-list", &_sslCipherList, "ssl cipher list, see OpenSSL documentation") ; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::parsePhase2 (ProgramOptions& options) { // create the ssl context (if possible) bool ok = createSslContext(); if (! ok) { return false; } if (_backlogSize <= 0 || _backlogSize > SOMAXCONN) { LOGGER_FATAL_AND_EXIT("invalid value for --server.backlog-size. maximum allowed value is " << SOMAXCONN); } if (_httpPort != "") { // issue #175: add hidden option --server.http-port for downwards-compatibility string httpEndpoint("tcp://" + _httpPort); _endpoints.push_back(httpEndpoint); } OperationMode::server_operation_mode_e mode = OperationMode::determineMode(options); if (_endpoints.empty() && mode == OperationMode::MODE_SERVER) { LOGGER_INFO("please use the '--server.endpoint' option"); LOGGER_FATAL_AND_EXIT("no endpoint has been specified, giving up"); } // add & validate endpoints for (vector<string>::const_iterator i = _endpoints.begin(); i != _endpoints.end(); ++i) { Endpoint* endpoint = Endpoint::serverFactory(*i, _backlogSize); if (endpoint == 0) { LOGGER_FATAL_AND_EXIT("invalid endpoint '" << *i << "'"); } assert(endpoint); bool ok = _endpointList.addEndpoint(endpoint->getProtocol(), endpoint->getEncryption(), endpoint); if (! ok) { LOGGER_FATAL_AND_EXIT("invalid endpoint '" << *i << "'"); } } // and return return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::prepare () { // dump used endpoints for user information _endpointList.dump(); _handlerFactory = new HttpHandlerFactory(_authenticationRealm, _checkAuthentication); return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::prepare2 () { // scheduler might be created after prepare(), so we need to use prepare2()!! Scheduler* scheduler = _applicationScheduler->scheduler(); if (scheduler == 0) { LOGGER_FATAL_AND_EXIT("no scheduler is known, cannot create http server"); return false; } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::open () { for (vector<EndpointServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { EndpointServer* server = *i; server->startListening(); } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::close () { // close all open connections for (vector<EndpointServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { EndpointServer* server = *i; server->shutdownHandlers(); } // close all listen sockets for (vector<EndpointServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { EndpointServer* server = *i; server->stopListening(); } } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::stop () { for (vector<EndpointServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { EndpointServer* server = *i; server->stop(); } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup HttpServer /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief creates an ssl context //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::createSslContext () { // check keyfile if (_httpsKeyfile.empty()) { return true; } // validate protocol if (_sslProtocol <= HttpsServer::SSL_UNKNOWN || _sslProtocol >= HttpsServer::SSL_LAST) { LOGGER_ERROR("invalid SSL protocol version specified."); LOGGER_INFO("please use a valid value for --server.ssl-protocol."); return false; } LOGGER_DEBUG("using SSL protocol version '" << HttpsServer::protocolName((HttpsServer::protocol_e) _sslProtocol) << "'"); // create context _sslContext = HttpsServer::sslContext(HttpsServer::protocol_e(_sslProtocol), _httpsKeyfile); if (_sslContext == 0) { LOGGER_ERROR("failed to create SSL context, cannot create a HTTPS server"); return false; } // set cache mode SSL_CTX_set_session_cache_mode(_sslContext, _sslCache ? SSL_SESS_CACHE_SERVER : SSL_SESS_CACHE_OFF); if (_sslCache) { LOGGER_TRACE("using SSL session caching"); } // set options SSL_CTX_set_options(_sslContext, _sslOptions); LOGGER_INFO("using SSL options: " << _sslOptions); if (_sslCipherList.size() > 0) { LOGGER_INFO("using SSL cipher-list '" << _sslCipherList << "'"); if (SSL_CTX_set_cipher_list(_sslContext, _sslCipherList.c_str()) != 1) { LOGGER_ERROR("ssl error: " << lastSSLError()); LOGGER_FATAL_AND_EXIT("cannot set SSL cipher list '" << _sslCipherList << "'"); } } // set ssl context Random::UniformCharacter r("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); _rctx = r.random(SSL_MAX_SSL_SESSION_ID_LENGTH); int res = SSL_CTX_set_session_id_context(_sslContext, (unsigned char const*) _rctx.c_str(), _rctx.size()); if (res != 1) { LOGGER_ERROR("ssl error: " << lastSSLError()); LOGGER_FATAL_AND_EXIT("cannot set SSL session id context '" << _rctx << "'"); } // check CA if (! _cafile.empty()) { LOGGER_TRACE("trying to load CA certificates from '" << _cafile << "'"); int res = SSL_CTX_load_verify_locations(_sslContext, _cafile.c_str(), 0); if (res == 0) { LOGGER_ERROR("ssl error: " << lastSSLError()); LOGGER_FATAL_AND_EXIT("cannot load CA certificates from '" << _cafile << "'"); } STACK_OF(X509_NAME) * certNames; certNames = SSL_load_client_CA_file(_cafile.c_str()); if (certNames == 0) { LOGGER_ERROR("ssl error: " << lastSSLError()); LOGGER_FATAL_AND_EXIT("cannot load CA certificates from '" << _cafile << "'"); } if (TRI_IsTraceLogging(__FILE__)) { for (int i = 0; i < sk_X509_NAME_num(certNames); ++i) { X509_NAME* cert = sk_X509_NAME_value(certNames, i); if (cert) { BIOGuard bout(BIO_new(BIO_s_mem())); X509_NAME_print_ex(bout._bio, cert, 0, (XN_FLAG_SEP_COMMA_PLUS | XN_FLAG_DN_REV | ASN1_STRFLGS_UTF8_CONVERT) & ~ASN1_STRFLGS_ESC_MSB); #ifdef TRI_ENABLE_LOGGER char* r; long len = BIO_get_mem_data(bout._bio, &r); LOGGER_TRACE("name: " << string(r, len)); #endif } } } SSL_CTX_set_client_CA_list(_sslContext, certNames); } return true; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <commit_msg>issue #120: added examples for endpoint syntax in `arangod --help`<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief application endpoint server feature /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "ApplicationEndpointServer.h" #include <openssl/err.h> #include "Basics/delete_object.h" #include "Basics/ssl-helper.h" #include "Basics/RandomGenerator.h" #include "Dispatcher/ApplicationDispatcher.h" #include "HttpServer/HttpHandlerFactory.h" #include "HttpServer/HttpServer.h" #include "HttpServer/HttpsServer.h" #include "Logger/Logger.h" #include "Rest/OperationMode.h" #include "Scheduler/ApplicationScheduler.h" using namespace triagens::basics; using namespace triagens::rest; using namespace std; // ----------------------------------------------------------------------------- // --SECTION-- private classes // ----------------------------------------------------------------------------- namespace { class BIOGuard { public: BIOGuard(BIO *bio) : _bio(bio) { } ~BIOGuard() { BIO_free(_bio); } public: BIO *_bio; }; } // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Scheduler /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// ApplicationEndpointServer::ApplicationEndpointServer (ApplicationServer* applicationServer, ApplicationScheduler* applicationScheduler, ApplicationDispatcher* applicationDispatcher, std::string const& authenticationRealm, HttpHandlerFactory::auth_fptr checkAuthentication) : ApplicationFeature("EndpointServer"), _applicationServer(applicationServer), _applicationScheduler(applicationScheduler), _applicationDispatcher(applicationDispatcher), _authenticationRealm(authenticationRealm), _checkAuthentication(checkAuthentication), _handlerFactory(0), _servers(), _endpointList(), _httpPort(), _endpoints(), _disableAuthentication(false), _keepAliveTimeout(300.0), _backlogSize(10), _httpsKeyfile(), _cafile(), _sslProtocol(HttpsServer::TLS_V1), _sslCache(false), _sslOptions((uint64_t) (SSL_OP_TLS_ROLLBACK_BUG | SSL_OP_CIPHER_SERVER_PREFERENCE)), _sslCipherList(""), _sslContext(0), _rctx() { } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// ApplicationEndpointServer::~ApplicationEndpointServer () { // .......................................................................... // Where ever possible we should EXPLICITLY write down the type used in // a templated class/method etc. This makes it a lot easier to debug the // code. Granted however, that explicitly writing down the type for an // overloaded class operator is a little unwieldy. // .......................................................................... for_each(_servers.begin(), _servers.end(), triagens::basics::DeleteObjectAny()); _servers.clear(); if (_handlerFactory != 0) { delete _handlerFactory; } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Scheduler /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief builds the endpoint servers //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::buildServers () { assert(_handlerFactory != 0); assert(_applicationScheduler->scheduler() != 0); EndpointServer* server; // turn off authentication if (_disableAuthentication) { _handlerFactory->setRequireAuthentication(false); LOGGER_INFO("Authentication is turned off"); } // unencrypted endpoints if (_endpointList.count(Endpoint::PROTOCOL_HTTP, Endpoint::ENCRYPTION_NONE) > 0) { // http endpoints server = new HttpServer(_applicationScheduler->scheduler(), _applicationDispatcher->dispatcher(), _keepAliveTimeout, _handlerFactory); server->setEndpointList(&_endpointList); _servers.push_back(server); } // ssl endpoints if (_endpointList.count(Endpoint::PROTOCOL_HTTP, Endpoint::ENCRYPTION_SSL) > 0) { // check the ssl context if (_sslContext == 0) { LOGGER_INFO("please use the --server.keyfile option"); LOGGER_FATAL_AND_EXIT("no ssl context is known, cannot create https server"); } // https server = new HttpsServer(_applicationScheduler->scheduler(), _applicationDispatcher->dispatcher(), _keepAliveTimeout, _handlerFactory, _sslContext); server->setEndpointList(&_endpointList); _servers.push_back(server); } return true; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- ApplicationFeature methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ApplicationServer /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::setupOptions (map<string, ProgramOptionsDescription>& options) { // issue #175: add deprecated hidden option for downwards compatibility options[ApplicationServer::OPTIONS_HIDDEN] ("server.http-port", &_httpPort, "http port for client requests (deprecated)") ; options[ApplicationServer::OPTIONS_SERVER] ("server.endpoint", &_endpoints, "endpoint for client requests (e.g. \"tcp://127.0.0.1:8529\", or \"ssl://192.168.1.1:8529\")") ; options[ApplicationServer::OPTIONS_SERVER + ":help-admin"] ("server.disable-authentication", &_disableAuthentication, "disable authentication for ALL client requests") ("server.keep-alive-timeout", &_keepAliveTimeout, "keep-alive timeout in seconds") ("server.backlog-size", &_backlogSize, "listen backlog size") ; options[ApplicationServer::OPTIONS_SERVER + ":help-ssl"] ("server.keyfile", &_httpsKeyfile, "keyfile for SSL connections") ("server.cafile", &_cafile, "file containing the CA certificates of clients") ("server.ssl-protocol", &_sslProtocol, "1 = SSLv2, 2 = SSLv23, 3 = SSLv3, 4 = TLSv1") ("server.ssl-cache", &_sslCache, "use SSL session caching") ("server.ssl-options", &_sslOptions, "ssl options, see OpenSSL documentation") ("server.ssl-cipher-list", &_sslCipherList, "ssl cipher list, see OpenSSL documentation") ; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::parsePhase2 (ProgramOptions& options) { // create the ssl context (if possible) bool ok = createSslContext(); if (! ok) { return false; } if (_backlogSize <= 0 || _backlogSize > SOMAXCONN) { LOGGER_FATAL_AND_EXIT("invalid value for --server.backlog-size. maximum allowed value is " << SOMAXCONN); } if (_httpPort != "") { // issue #175: add hidden option --server.http-port for downwards-compatibility string httpEndpoint("tcp://" + _httpPort); _endpoints.push_back(httpEndpoint); } OperationMode::server_operation_mode_e mode = OperationMode::determineMode(options); if (_endpoints.empty() && mode == OperationMode::MODE_SERVER) { LOGGER_INFO("please use the '--server.endpoint' option"); LOGGER_FATAL_AND_EXIT("no endpoint has been specified, giving up"); } // add & validate endpoints for (vector<string>::const_iterator i = _endpoints.begin(); i != _endpoints.end(); ++i) { Endpoint* endpoint = Endpoint::serverFactory(*i, _backlogSize); if (endpoint == 0) { LOGGER_FATAL_AND_EXIT("invalid endpoint '" << *i << "'"); } assert(endpoint); bool ok = _endpointList.addEndpoint(endpoint->getProtocol(), endpoint->getEncryption(), endpoint); if (! ok) { LOGGER_FATAL_AND_EXIT("invalid endpoint '" << *i << "'"); } } // and return return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::prepare () { // dump used endpoints for user information _endpointList.dump(); _handlerFactory = new HttpHandlerFactory(_authenticationRealm, _checkAuthentication); return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::prepare2 () { // scheduler might be created after prepare(), so we need to use prepare2()!! Scheduler* scheduler = _applicationScheduler->scheduler(); if (scheduler == 0) { LOGGER_FATAL_AND_EXIT("no scheduler is known, cannot create http server"); return false; } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::open () { for (vector<EndpointServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { EndpointServer* server = *i; server->startListening(); } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::close () { // close all open connections for (vector<EndpointServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { EndpointServer* server = *i; server->shutdownHandlers(); } // close all listen sockets for (vector<EndpointServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { EndpointServer* server = *i; server->stopListening(); } } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::stop () { for (vector<EndpointServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { EndpointServer* server = *i; server->stop(); } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup HttpServer /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief creates an ssl context //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::createSslContext () { // check keyfile if (_httpsKeyfile.empty()) { return true; } // validate protocol if (_sslProtocol <= HttpsServer::SSL_UNKNOWN || _sslProtocol >= HttpsServer::SSL_LAST) { LOGGER_ERROR("invalid SSL protocol version specified."); LOGGER_INFO("please use a valid value for --server.ssl-protocol."); return false; } LOGGER_DEBUG("using SSL protocol version '" << HttpsServer::protocolName((HttpsServer::protocol_e) _sslProtocol) << "'"); // create context _sslContext = HttpsServer::sslContext(HttpsServer::protocol_e(_sslProtocol), _httpsKeyfile); if (_sslContext == 0) { LOGGER_ERROR("failed to create SSL context, cannot create a HTTPS server"); return false; } // set cache mode SSL_CTX_set_session_cache_mode(_sslContext, _sslCache ? SSL_SESS_CACHE_SERVER : SSL_SESS_CACHE_OFF); if (_sslCache) { LOGGER_TRACE("using SSL session caching"); } // set options SSL_CTX_set_options(_sslContext, _sslOptions); LOGGER_INFO("using SSL options: " << _sslOptions); if (_sslCipherList.size() > 0) { LOGGER_INFO("using SSL cipher-list '" << _sslCipherList << "'"); if (SSL_CTX_set_cipher_list(_sslContext, _sslCipherList.c_str()) != 1) { LOGGER_ERROR("ssl error: " << lastSSLError()); LOGGER_FATAL_AND_EXIT("cannot set SSL cipher list '" << _sslCipherList << "'"); } } // set ssl context Random::UniformCharacter r("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); _rctx = r.random(SSL_MAX_SSL_SESSION_ID_LENGTH); int res = SSL_CTX_set_session_id_context(_sslContext, (unsigned char const*) _rctx.c_str(), _rctx.size()); if (res != 1) { LOGGER_ERROR("ssl error: " << lastSSLError()); LOGGER_FATAL_AND_EXIT("cannot set SSL session id context '" << _rctx << "'"); } // check CA if (! _cafile.empty()) { LOGGER_TRACE("trying to load CA certificates from '" << _cafile << "'"); int res = SSL_CTX_load_verify_locations(_sslContext, _cafile.c_str(), 0); if (res == 0) { LOGGER_ERROR("ssl error: " << lastSSLError()); LOGGER_FATAL_AND_EXIT("cannot load CA certificates from '" << _cafile << "'"); } STACK_OF(X509_NAME) * certNames; certNames = SSL_load_client_CA_file(_cafile.c_str()); if (certNames == 0) { LOGGER_ERROR("ssl error: " << lastSSLError()); LOGGER_FATAL_AND_EXIT("cannot load CA certificates from '" << _cafile << "'"); } if (TRI_IsTraceLogging(__FILE__)) { for (int i = 0; i < sk_X509_NAME_num(certNames); ++i) { X509_NAME* cert = sk_X509_NAME_value(certNames, i); if (cert) { BIOGuard bout(BIO_new(BIO_s_mem())); X509_NAME_print_ex(bout._bio, cert, 0, (XN_FLAG_SEP_COMMA_PLUS | XN_FLAG_DN_REV | ASN1_STRFLGS_UTF8_CONVERT) & ~ASN1_STRFLGS_ESC_MSB); #ifdef TRI_ENABLE_LOGGER char* r; long len = BIO_get_mem_data(bout._bio, &r); LOGGER_TRACE("name: " << string(r, len)); #endif } } } SSL_CTX_set_client_CA_list(_sslContext, certNames); } return true; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")) (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763")) (193000, uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317")) ; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) ; bool CheckBlock(int nHeight, const uint256& hash) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Checkpoint at first 25-btc-reward block (210,000)<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")) (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763")) (193000, uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317")) (210000, uint256("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e")) ; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) ; bool CheckBlock(int nHeight, const uint256& hash) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")) (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763")) (193000, uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317")) (210000, uint256("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e")) (216116, uint256("0x00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e")) (225430, uint256("0x00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932")) (250000, uint256("0x000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214")) ; static const CCheckpointData data = { &mapCheckpoints, 1375533383, // * UNIX timestamp of last checkpoint block 21491097, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 60000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1338180505, 16341, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!GetBoolArg("-checkpoints", true)) return true; return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { return 0; if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { return NULL; if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Revert "Revert "Revert "Disable checkpoints"""<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")) (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763")) (193000, uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317")) (210000, uint256("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e")) (216116, uint256("0x00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e")) (225430, uint256("0x00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932")) (250000, uint256("0x000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214")) ; static const CCheckpointData data = { &mapCheckpoints, 1375533383, // * UNIX timestamp of last checkpoint block 21491097, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 60000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1338180505, 16341, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 1500, uint256("0x841a2965955dd288cfa707a755d05a54e45f8bd476835ec9af4402a2b59a2967")) ( 4032, uint256("0x9ce90e427198fc0ef05e5905ce3503725b80e26afd35a987965fd7e3d9cf0846")) ( 8064, uint256("0xeb984353fc5190f210651f150c40b8a4bab9eeeff0b729fcb3987da694430d70")) ( 16128, uint256("0x602edf1859b7f9a6af809f1d9b0e6cb66fdc1d4d9dcd7a4bec03e12a1ccd153d")) ( 23420, uint256("0xd80fdf9ca81afd0bd2b2a90ac3a9fe547da58f2530ec874e978fce0b5101b507")) ( 50000, uint256("0x69dc37eb029b68f075a5012dcc0419c127672adb4f3a32882b2b3e71d07a20a6")) ( 80000, uint256("0x4fcb7c02f676a300503f49c764a89955a8f920b46a8cbecb4867182ecdb2e90a")) (120000, uint256("0xbd9d26924f05f6daa7f0155f32828ec89e8e29cee9e7121b026a7a3552ac6131")) (161500, uint256("0xdbe89880474f4bb4f75c227c77ba1cdc024991123b28b8418dbbf7798471ff43")) (179620, uint256("0x2ad9c65c990ac00426d18e446e0fd7be2ffa69e9a7dcb28358a50b2b78b9f709")) (240000, uint256("0x7140d1c4b4c2157ca217ee7636f24c9c73db39c4590c4e6eab2e3ea1555088aa")) (383640, uint256("0x2b6809f094a9215bafc65eb3f110a35127a34be94b7d0590a096c3f126c6f364")) (409004, uint256("0x487518d663d9f1fa08611d9395ad74d982b667fbdc0e77e9cf39b4f1355908a3")) (456000, uint256("0xbf34f71cc6366cd487930d06be22f897e34ca6a40501ac7d401be32456372004")) (541794, uint256("0x1cbccbe6920e7c258bbce1f26211084efb19764aa3224bec3f4320d77d6a2fd2")) ; static const CCheckpointData data = { &mapCheckpoints, 1396366781, // * UNIX timestamp of last checkpoint block 3854671, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 12000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 546, uint256("0xa0fea99a6897f531600c8ae53367b126824fd6a847b2b2b73817a95b8e27e602")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1365458829, 547, 576 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Litecoin: Checkpoint at block 585010<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 1500, uint256("0x841a2965955dd288cfa707a755d05a54e45f8bd476835ec9af4402a2b59a2967")) ( 4032, uint256("0x9ce90e427198fc0ef05e5905ce3503725b80e26afd35a987965fd7e3d9cf0846")) ( 8064, uint256("0xeb984353fc5190f210651f150c40b8a4bab9eeeff0b729fcb3987da694430d70")) ( 16128, uint256("0x602edf1859b7f9a6af809f1d9b0e6cb66fdc1d4d9dcd7a4bec03e12a1ccd153d")) ( 23420, uint256("0xd80fdf9ca81afd0bd2b2a90ac3a9fe547da58f2530ec874e978fce0b5101b507")) ( 50000, uint256("0x69dc37eb029b68f075a5012dcc0419c127672adb4f3a32882b2b3e71d07a20a6")) ( 80000, uint256("0x4fcb7c02f676a300503f49c764a89955a8f920b46a8cbecb4867182ecdb2e90a")) (120000, uint256("0xbd9d26924f05f6daa7f0155f32828ec89e8e29cee9e7121b026a7a3552ac6131")) (161500, uint256("0xdbe89880474f4bb4f75c227c77ba1cdc024991123b28b8418dbbf7798471ff43")) (179620, uint256("0x2ad9c65c990ac00426d18e446e0fd7be2ffa69e9a7dcb28358a50b2b78b9f709")) (240000, uint256("0x7140d1c4b4c2157ca217ee7636f24c9c73db39c4590c4e6eab2e3ea1555088aa")) (383640, uint256("0x2b6809f094a9215bafc65eb3f110a35127a34be94b7d0590a096c3f126c6f364")) (409004, uint256("0x487518d663d9f1fa08611d9395ad74d982b667fbdc0e77e9cf39b4f1355908a3")) (456000, uint256("0xbf34f71cc6366cd487930d06be22f897e34ca6a40501ac7d401be32456372004")) (541794, uint256("0x1cbccbe6920e7c258bbce1f26211084efb19764aa3224bec3f4320d77d6a2fd2")) (585010, uint256("0xea9ea06840de20a18a66acb07c9102ee6374ad2cbafc71794e576354fea5df2d")) ; static const CCheckpointData data = { &mapCheckpoints, 1402691751, // * UNIX timestamp of last checkpoint block 4404988, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 10000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 546, uint256("0xa0fea99a6897f531600c8ae53367b126824fd6a847b2b2b73817a95b8e27e602")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1365458829, 547, 576 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014 Kryptohash developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "main.h" #include "uint256.h" #include <stdint.h> #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> namespace Checkpoints { typedef std::map<int64_t, uint320> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double SIGCHECK_VERIFICATION_FACTOR = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64_t nTimeLastCheckpoint; int64_t nTransactionsLastCheckpoint; double fTransactionsPerDay; }; bool fEnabled = true; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of (99, uint320("00000018CE97B434F8396CB989C61190BB72B8CD2A7352C48C91AEDB2E0F8AFCE8CDB7A59334E95B")) (5000, uint320("0000000BC13E7BCFC9CFB664D4EA05D6732F5FB49DED407DA33E45FE351A5BD3A81F003BFC2096AC")) (5098, uint320("0000000853574F2FEEEE8EE642C72D8E1A40DBDFAFD01CC1B8F23EE6EBC565B16EDFF9E336B0DA0F")) ; static const CCheckpointData data = { &mapCheckpoints, 0x14A1D085120, // * UNIX timestamp of last checkpoint block 12084, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 60000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint320(0)) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 0x1488DDBA3EE, 0, 300.0 }; static MapCheckpoints mapCheckpointsRegtest = boost::assign::map_list_of ( 0, uint320(0)) ; static const CCheckpointData dataRegtest = { &mapCheckpointsRegtest, 0, 0, 0 }; const CCheckpointData &Checkpoints() { if (Params().NetworkID() == CChainParams::TESTNET) { return dataTestnet; } else if (Params().NetworkID() == CChainParams::MAIN) { return data; } else { return dataRegtest; } } bool CheckBlock(int64_t nHeight, const uint320& hash) { if (!fEnabled) { return true; } const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) { return true; } return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) { if (pindex == NULL) { return 0.0; } int64_t nNow = time(NULL); double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0; double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkpoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int64_t GetTotalBlocksEstimate() { if (!fEnabled) { return 0; } const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint320, CBlockIndex*>& mapBlockIndex) { if (!fEnabled) { return NULL; } const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint320& hash = i.second; std::map<uint320, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) { return t->second; } } return NULL; } } namespace PIDCheckpoints { typedef std::map<int64_t, CPID> MapPIDCheckpoints; struct CPIDCheckpointData { const MapPIDCheckpoints *mapPIDCheckpoints; int64_t nTimeLastCheckpoint; }; bool fEnabled = true; static MapPIDCheckpoints mapPIDCheckpoints = boost::assign::map_list_of (0, CPID(180.0f, 1.0f, 0.05f, 0.1f)) ; static const CPIDCheckpointData data = { &mapPIDCheckpoints, 0x148d455b42a // * timestamp of last PID checkpoint }; static MapPIDCheckpoints mapPIDCheckpointsTestnet = boost::assign::map_list_of (0, CPID(180.0f, 1.0f, 0.05f, 0.1f)) ; static const CPIDCheckpointData dataTestnet = { &mapPIDCheckpointsTestnet, 0x148d455b42a }; static MapPIDCheckpoints mapPIDCheckpointsRegtest = boost::assign::map_list_of (0, CPID(180.0f, 1.0f, 0.05f, 0.1f)) ; static const CPIDCheckpointData dataRegtest = { &mapPIDCheckpointsRegtest, 0 }; const CPIDCheckpointData &PIDCheckpoints() { if (Params().NetworkID() == CChainParams::TESTNET) { return dataTestnet; } else if (Params().NetworkID() == CChainParams::MAIN) { return data; } else { return dataRegtest; } } int64_t PIDGetHeightLastCheckpoint() { if (!fEnabled) { return 0; } const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints; return PIDcheckpoints.rbegin()->first; } int64_t PIDGetTimeLastCheckpoint() { if (!fEnabled) { return 0; } const int64_t PIDcheckpointTime = PIDCheckpoints().nTimeLastCheckpoint; return PIDcheckpointTime; } const CPID* GetPIDCheckpoint(int64_t height) { if (!fEnabled) { return NULL; } const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints; BOOST_REVERSE_FOREACH(const MapPIDCheckpoints::value_type& i, PIDcheckpoints) { if (i.first <= height) { const CPID& PIDChkpoint = i.second; return &PIDChkpoint; } } return NULL; } } <commit_msg>New checkpoint at 5600<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014 Kryptohash developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "main.h" #include "uint256.h" #include <stdint.h> #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> namespace Checkpoints { typedef std::map<int64_t, uint320> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double SIGCHECK_VERIFICATION_FACTOR = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64_t nTimeLastCheckpoint; int64_t nTransactionsLastCheckpoint; double fTransactionsPerDay; }; bool fEnabled = true; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of (99, uint320("00000018CE97B434F8396CB989C61190BB72B8CD2A7352C48C91AEDB2E0F8AFCE8CDB7A59334E95B")) (5000, uint320("0000000BC13E7BCFC9CFB664D4EA05D6732F5FB49DED407DA33E45FE351A5BD3A81F003BFC2096AC")) (5098, uint320("0000000853574F2FEEEE8EE642C72D8E1A40DBDFAFD01CC1B8F23EE6EBC565B16EDFF9E336B0DA0F")) (5600, uint320("000000012A064B7393C4A6C6CCD71B52640804A5DD8ABE76FDE35AD12EF00D7FE3DCE691938535DD")) ; static const CCheckpointData data = { &mapCheckpoints, 0x14A283B4E58, // * UNIX timestamp of last checkpoint block 13736, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 60000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint320(0)) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 0x1488DDBA3EE, 0, 300.0 }; static MapCheckpoints mapCheckpointsRegtest = boost::assign::map_list_of ( 0, uint320(0)) ; static const CCheckpointData dataRegtest = { &mapCheckpointsRegtest, 0, 0, 0 }; const CCheckpointData &Checkpoints() { if (Params().NetworkID() == CChainParams::TESTNET) { return dataTestnet; } else if (Params().NetworkID() == CChainParams::MAIN) { return data; } else { return dataRegtest; } } bool CheckBlock(int64_t nHeight, const uint320& hash) { if (!fEnabled) { return true; } const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) { return true; } return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) { if (pindex == NULL) { return 0.0; } int64_t nNow = time(NULL); double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0; double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkpoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int64_t GetTotalBlocksEstimate() { if (!fEnabled) { return 0; } const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint320, CBlockIndex*>& mapBlockIndex) { if (!fEnabled) { return NULL; } const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint320& hash = i.second; std::map<uint320, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) { return t->second; } } return NULL; } } namespace PIDCheckpoints { typedef std::map<int64_t, CPID> MapPIDCheckpoints; struct CPIDCheckpointData { const MapPIDCheckpoints *mapPIDCheckpoints; int64_t nTimeLastCheckpoint; }; bool fEnabled = true; static MapPIDCheckpoints mapPIDCheckpoints = boost::assign::map_list_of (0, CPID(180.0f, 1.0f, 0.05f, 0.1f)) (5600, CPID(180.0f, 1.0f, 0.05f, 0.1f, 0.0f, 0.0f, 0.0f, 0, 5599, 180.0f, 0x2507ffff)) ; static const CPIDCheckpointData data = { &mapPIDCheckpoints, 0x148d455b42a // * timestamp of last PID checkpoint }; static MapPIDCheckpoints mapPIDCheckpointsTestnet = boost::assign::map_list_of (0, CPID(180.0f, 1.0f, 0.05f, 0.1f)) ; static const CPIDCheckpointData dataTestnet = { &mapPIDCheckpointsTestnet, 0x148d455b42a }; static MapPIDCheckpoints mapPIDCheckpointsRegtest = boost::assign::map_list_of (0, CPID(180.0f, 1.0f, 0.05f, 0.1f)) ; static const CPIDCheckpointData dataRegtest = { &mapPIDCheckpointsRegtest, 0 }; const CPIDCheckpointData &PIDCheckpoints() { if (Params().NetworkID() == CChainParams::TESTNET) { return dataTestnet; } else if (Params().NetworkID() == CChainParams::MAIN) { return data; } else { return dataRegtest; } } int64_t PIDGetHeightLastCheckpoint() { if (!fEnabled) { return 0; } const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints; return PIDcheckpoints.rbegin()->first; } int64_t PIDGetTimeLastCheckpoint() { if (!fEnabled) { return 0; } const int64_t PIDcheckpointTime = PIDCheckpoints().nTimeLastCheckpoint; return PIDcheckpointTime; } const CPID* GetPIDCheckpoint(int64_t height) { if (!fEnabled) { return NULL; } const MapPIDCheckpoints& PIDcheckpoints = *PIDCheckpoints().mapPIDCheckpoints; BOOST_REVERSE_FOREACH(const MapPIDCheckpoints::value_type& i, PIDcheckpoints) { if (i.first <= height) { const CPID& PIDChkpoint = i.second; return &PIDChkpoint; } } return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2014 NobleCoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xdbf8ee8b91b5f03d7786cb1d58f2588538b2d48d8c23a7913db5aac7bb58c481")) ( 100, uint256("0x000cedc00442c5ecb96ec2f3d81e5513c59ec31f82cdfda95d939fab5f1a7696")) ( 150, uint256("0xc977085510cb7256d7a7b96acfe851ee34f7dba91170b102ff80e0526ec2441a")) ( 10000, uint256("0x621cb4ceab38c59da38cfe59c5e9547f0bbf324c374de8111fc6a15f31a39452")) ( 50000, uint256("0xe8358688715339d51e0450bd1e9e3749bd940b31d4fc90b9eaf4530b2c8ffb9b")) ( 100000, uint256("0xdaa983f98f6cf60f98dcd3151fe82b16f7825fecc657f0c29e13ac62d0351e81")) ( 140000, uint256("0x8b525c5c5ac84021d5aae16b8d85a3977a91461c157733423de756fe32ce1637")) ( 170000, uint256("0x8fd23e16bc80406154df4cf083ba35fe53d876a3ead261af86f8cfbaef344919")) ( 219718, uint256("0x0e1dd6ee774d8f30594fa40ce550e4a938449726b1d326471d7ea47c73d6c4e0")) ( 280000, uint256("0x68146cdfca86f2c644fbdcae80a24e4fe3c2adbe922730eb8a0cb0440c12bc86")) ; bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); if (i == mapCheckpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { if (fTestNet) return 0; return mapCheckpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Update checkpoints.cpp<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2014 NobleCoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xdbf8ee8b91b5f03d7786cb1d58f2588538b2d48d8c23a7913db5aac7bb58c481")) ( 100, uint256("0x000cedc00442c5ecb96ec2f3d81e5513c59ec31f82cdfda95d939fab5f1a7696")) ( 150, uint256("0xc977085510cb7256d7a7b96acfe851ee34f7dba91170b102ff80e0526ec2441a")) ( 10000, uint256("0x621cb4ceab38c59da38cfe59c5e9547f0bbf324c374de8111fc6a15f31a39452")) ( 50000, uint256("0xe8358688715339d51e0450bd1e9e3749bd940b31d4fc90b9eaf4530b2c8ffb9b")) ( 100000, uint256("0xdaa983f98f6cf60f98dcd3151fe82b16f7825fecc657f0c29e13ac62d0351e81")) ( 140000, uint256("0x8b525c5c5ac84021d5aae16b8d85a3977a91461c157733423de756fe32ce1637")) ( 170000, uint256("0x8fd23e16bc80406154df4cf083ba35fe53d876a3ead261af86f8cfbaef344919")) ( 219718, uint256("0x0e1dd6ee774d8f30594fa40ce550e4a938449726b1d326471d7ea47c73d6c4e0")) ( 280000, uint256("0x68146cdfca86f2c644fbdcae80a24e4fe3c2adbe922730eb8a0cb0440c12bc86")) ( 385291, uint256("0xfa5776daa57c46853089411e501bb455d893de2ea79dff1f96e85d1b0907a2dc")) ; bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); if (i == mapCheckpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { if (fTestNet) return 0; return mapCheckpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>// OpenLieroX // Input box // Created 30/3/03 // Jason Boettcher #include "defs.h" #include "LieroX.h" #include "Menu.h" /////////////////// // Draw the frame into a buffer void CFrame::PreDraw(void) { // Create the buffer, if needed if (!bmpBuffer) { SDL_PixelFormat *fmt = SDL_GetVideoSurface()->format; if (fmt) bmpBuffer = SDL_CreateRGBSurface(SDL_SWSURFACE,iWidth,iHeight,fmt->BitsPerPixel,fmt->Rmask,fmt->Gmask,fmt->Bmask,fmt->Amask); else bmpBuffer = NULL; if (!bmpBuffer) return; } // Set the whole buffer transparent SDL_SetColorKey(bmpBuffer, SDL_SRCCOLORKEY, SDL_MapRGB(bmpBuffer->format,255,0,255)); DrawRectFill(bmpBuffer,0,0,iWidth,iHeight,MakeColour(255,0,255)); // // 1. Draw the lines // int line_left,line_right,line_top,line_bottom; line_left = iRound; line_right = iWidth - iRound; line_top = iRound; line_bottom = iHeight - iRound; Uint32 cur_col = iDarkColour; Uint8 dark_r,dark_g,dark_b; SDL_GetRGB(iDarkColour,bmpBuffer->format,&dark_r,&dark_g,&dark_b); Uint8 light_r,light_g,light_b; SDL_GetRGB(iLightColour,bmpBuffer->format,&light_r,&light_g,&light_b); int rstep,gstep,bstep; if (iBorder) { rstep = (light_r-dark_r)/iBorder; gstep = (light_g-dark_g)/iBorder; bstep = (light_b-dark_b)/iBorder; } // Top line for (int j=0; j<iBorder; j++) { DrawHLine(bmpBuffer,line_left,line_right,iY+j,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } cur_col = iDarkColour; // Bottom line for (j=0; j<iBorder; j++) { DrawHLine(bmpBuffer,line_left,line_right,iY+iHeight-j,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } cur_col = iDarkColour; // Left line for (j=0; j<iBorder; j++) { DrawVLine(bmpBuffer,line_top,line_bottom,iX+j,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } cur_col = iDarkColour; // Right line for (j=0; j<iBorder; j++) { DrawVLine(bmpBuffer,line_top,line_bottom,iX+iWidth-j,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } // // 2. Draw the round borders // int x,y; float fStart = GetMilliSeconds(); // Top left // (1,3/2*PI) float step = 1/(PI*iRound*(iBorder+0.0000001)); for (float i=1.00;i<1.5;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = (iRound-j)*sin(PI*i)-1; y = (iRound-j)*cos(PI*i)-1; PutPixel(bmpBuffer,x+iRound,y+iRound,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } } // Top right // (PI/2,PI) for (i=0.50;i<1;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = (iRound-j)*sin(PI*i)+1; y = (iRound-j)*cos(PI*i)-1; PutPixel(bmpBuffer,x+iWidth-iRound,y+iRound,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } } // Bottom left // (3/2*PI,2PI) for (i=1.50;i<2;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = (iRound-j)*sin(PI*i)-1; y = (iRound-j)*cos(PI*i)+1; PutPixel(bmpBuffer,x+iRound,y+iHeight-iRound,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } } // Bottom right // (0,PI) for (i=-0.01;i<0.5;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = (iRound-j)*sin(PI*i)+1; y = (iRound-j)*cos(PI*i)+1; PutPixel(bmpBuffer,x+iWidth-iRound,y+iHeight-iRound,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } } float fLength = (GetMilliSeconds()-fStart)*1000; } ///////////////// // Draw the frame void CFrame::Draw(SDL_Surface *bmpDest) { if (bmpBuffer) DrawImage(bmpDest,bmpBuffer,iX,iY); } ///////////////// // Free the widget void CFrame::Destroy(void) { if(bmpBuffer) { SDL_FreeSurface(bmpBuffer); bmpBuffer = NULL; } }<commit_msg>small fixes of non ANSI standard code<commit_after>// OpenLieroX // Input box // Created 30/3/03 // Jason Boettcher #include "defs.h" #include "LieroX.h" #include "Menu.h" /////////////////// // Draw the frame into a buffer void CFrame::PreDraw(void) { // Create the buffer, if needed if (!bmpBuffer) { SDL_PixelFormat *fmt = SDL_GetVideoSurface()->format; if (fmt) bmpBuffer = SDL_CreateRGBSurface(SDL_SWSURFACE,iWidth,iHeight,fmt->BitsPerPixel,fmt->Rmask,fmt->Gmask,fmt->Bmask,fmt->Amask); else bmpBuffer = NULL; if (!bmpBuffer) return; } // Set the whole buffer transparent SDL_SetColorKey(bmpBuffer, SDL_SRCCOLORKEY, SDL_MapRGB(bmpBuffer->format,255,0,255)); DrawRectFill(bmpBuffer,0,0,iWidth,iHeight,MakeColour(255,0,255)); // // 1. Draw the lines // int line_left,line_right,line_top,line_bottom; line_left = iRound; line_right = iWidth - iRound; line_top = iRound; line_bottom = iHeight - iRound; Uint32 cur_col = iDarkColour; Uint8 dark_r,dark_g,dark_b; SDL_GetRGB(iDarkColour,bmpBuffer->format,&dark_r,&dark_g,&dark_b); Uint8 light_r,light_g,light_b; SDL_GetRGB(iLightColour,bmpBuffer->format,&light_r,&light_g,&light_b); int rstep,gstep,bstep; if (iBorder) { rstep = (light_r-dark_r)/iBorder; gstep = (light_g-dark_g)/iBorder; bstep = (light_b-dark_b)/iBorder; } // Top line int j; for (j=0; j<iBorder; j++) { DrawHLine(bmpBuffer,line_left,line_right,iY+j,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } cur_col = iDarkColour; // Bottom line for (j=0; j<iBorder; j++) { DrawHLine(bmpBuffer,line_left,line_right,iY+iHeight-j,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } cur_col = iDarkColour; // Left line for (j=0; j<iBorder; j++) { DrawVLine(bmpBuffer,line_top,line_bottom,iX+j,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } cur_col = iDarkColour; // Right line for (j=0; j<iBorder; j++) { DrawVLine(bmpBuffer,line_top,line_bottom,iX+iWidth-j,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } // // 2. Draw the round borders // int x,y; float fStart = GetMilliSeconds(); // Top left // (1,3/2*PI) float step = 1/(PI*iRound*(iBorder+0.0000001)); float i; for (i=1.00;i<1.5;i+=step) { cur_col = iDarkColour; for (j=0; j<(int)iBorder; j++) { x = (int)((iRound-j)*sin(PI*i)-1); y = (int)((iRound-j)*cos(PI*i)-1); PutPixel(bmpBuffer,x+iRound,y+iRound,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } } // Top right // (PI/2,PI) for (i=0.50;i<1;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = (int)((iRound-j)*sin(PI*i)+1); y = (int)((iRound-j)*cos(PI*i)-1); PutPixel(bmpBuffer,x+iWidth-iRound,y+iRound,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } } // Bottom left // (3/2*PI,2PI) for (i=1.50;i<2;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = (int)((iRound-j)*sin(PI*i)-1); y = (int)((iRound-j)*cos(PI*i)+1); PutPixel(bmpBuffer,x+iRound,y+iHeight-iRound,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } } // Bottom right // (0,PI) for (i=-0.01;i<0.5;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = (int)((iRound-j)*sin(PI*i)+1); y = (int)((iRound-j)*cos(PI*i)+1); PutPixel(bmpBuffer,x+iWidth-iRound,y+iHeight-iRound,cur_col); cur_col = MakeColour(dark_r+rstep*(j+1),dark_g+gstep*(j+1),dark_b+bstep*(j+1)); } } float fLength = (GetMilliSeconds()-fStart)*1000; } ///////////////// // Draw the frame void CFrame::Draw(SDL_Surface *bmpDest) { if (bmpBuffer) DrawImage(bmpDest,bmpBuffer,iX,iY); } ///////////////// // Free the widget void CFrame::Destroy(void) { if(bmpBuffer) { SDL_FreeSurface(bmpBuffer); bmpBuffer = NULL; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbDEMToImageGenerator_hxx #define otbDEMToImageGenerator_hxx #include "otbDEMToImageGenerator.h" #include "otbMacro.h" #include "itkProgressReporter.h" namespace otb { template <class TDEMImage> DEMToImageGenerator<TDEMImage>::DEMToImageGenerator() { m_OutputSpacing[0] = 0.0001; m_OutputSpacing[1] = -0.0001; m_OutputSize[0] = 1; m_OutputSize[1] = 1; m_OutputOrigin[0] = 0; m_OutputOrigin[1] = 0; m_DefaultUnknownValue = itk::NumericTraits<PixelType>::ZeroValue(); m_AboveEllipsoid = false; m_Transform = GenericRSTransformType::New(); } // GenerateOutputInformation method template <class TDEMImage> void DEMToImageGenerator<TDEMImage>::GenerateOutputInformation() { DEMImageType* output; output = this->GetOutput(0); IndexType start; start[0] = 0; start[1] = 0; // Specify region parameters OutputImageRegionType largestPossibleRegion; largestPossibleRegion.SetSize(m_OutputSize); largestPossibleRegion.SetIndex(start); output->SetLargestPossibleRegion(largestPossibleRegion); output->SetSignedSpacing(m_OutputSpacing); output->SetOrigin(m_OutputOrigin); // Add the metadata set by the user to the output output->m_Imd.Add(MDGeom::ProjectionProj, m_Transform->GetInputProjectionRef()); if (m_Transform->GetInputImageMetadata() != nullptr) output->m_Imd.Merge(*m_Transform->GetInputImageMetadata()); } // InstantiateTransform method template <class TDEMImage> void DEMToImageGenerator<TDEMImage>::InstantiateTransform() { m_Transform->InstantiateTransform(); } template <class TDEMImage> void DEMToImageGenerator<TDEMImage>::BeforeThreadedGenerateData() { InstantiateTransform(); DEMImagePointerType DEMImage = this->GetOutput(); // allocate the output buffer DEMImage->SetBufferedRegion(DEMImage->GetRequestedRegion()); DEMImage->Allocate(); DEMImage->FillBuffer(0); } template <class TDEMImage> void DEMToImageGenerator<TDEMImage>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId) { DEMImagePointerType DEMImage = this->GetOutput(); // Create an iterator that will walk the output region ImageIteratorType outIt = ImageIteratorType(DEMImage, outputRegionForThread); // support progress methods/callbacks itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); // Walk the output image, evaluating the height at each pixel IndexType currentindex; PointType phyPoint; double height; PointType geoPoint; for (outIt.GoToBegin(); !outIt.IsAtEnd(); ++outIt) { currentindex = outIt.GetIndex(); DEMImage->TransformIndexToPhysicalPoint(currentindex, phyPoint); if (m_Transform.IsNotNull()) { geoPoint = m_Transform->TransformPoint(phyPoint); if (m_AboveEllipsoid) { height = DEMHandler::GetInstance().GetHeightAboveEllipsoid(geoPoint); // Altitude // calculation } else { height = DEMHandler::GetInstance().GetHeightAboveMSL(geoPoint); // Altitude // calculation } } else { if (m_AboveEllipsoid) { height = DEMHandler::GetInstance().GetHeightAboveEllipsoid(phyPoint); // Altitude // calculation } else { height = DEMHandler::GetInstance().GetHeightAboveMSL(phyPoint); // Altitude // calculation } } /* otbMsgDevMacro(<< "Index : (" << currentindex[0]<< "," << currentindex[1] << ") -> PhyPoint : (" << phyPoint[0] << "," << phyPoint[1] << ") -> GeoPoint: (" << geoPoint[0] << "," << geoPoint[1] << ") -> height" << height); */ // otbMsgDevMacro(<< "height" << height); // DEM sets a default value (-32768) at point where it doesn't have altitude information. // OSSIM has chosen to change this default value in OSSIM_DBL_NAN (-4.5036e15). if (!vnl_math_isnan(height)) { // Fill the image DEMImage->SetPixel(currentindex, static_cast<PixelType>(height)); } else { // Back to the MNT default value DEMImage->SetPixel(currentindex, m_DefaultUnknownValue); } progress.CompletedPixel(); } } template <class TDEMImage> void DEMToImageGenerator<TDEMImage>::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Output Spacing:" << m_OutputSpacing[0] << "," << m_OutputSpacing[1] << std::endl; os << indent << "Output Origin:" << m_OutputOrigin[0] << "," << m_OutputOrigin[1] << std::endl; os << indent << "Output Size:" << m_OutputSize[0] << "," << m_OutputSize[1] << std::endl; } } // namespace otb #endif <commit_msg>FIX: Set ProjectionProj as std::string before storing as boost::any<commit_after>/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbDEMToImageGenerator_hxx #define otbDEMToImageGenerator_hxx #include "otbDEMToImageGenerator.h" #include "otbMacro.h" #include "itkProgressReporter.h" namespace otb { template <class TDEMImage> DEMToImageGenerator<TDEMImage>::DEMToImageGenerator() { m_OutputSpacing[0] = 0.0001; m_OutputSpacing[1] = -0.0001; m_OutputSize[0] = 1; m_OutputSize[1] = 1; m_OutputOrigin[0] = 0; m_OutputOrigin[1] = 0; m_DefaultUnknownValue = itk::NumericTraits<PixelType>::ZeroValue(); m_AboveEllipsoid = false; m_Transform = GenericRSTransformType::New(); } // GenerateOutputInformation method template <class TDEMImage> void DEMToImageGenerator<TDEMImage>::GenerateOutputInformation() { DEMImageType* output = this->GetOutput(0); IndexType start; start[0] = 0; start[1] = 0; // Specify region parameters OutputImageRegionType largestPossibleRegion; largestPossibleRegion.SetSize(m_OutputSize); largestPossibleRegion.SetIndex(start); output->SetLargestPossibleRegion(largestPossibleRegion); output->SetSignedSpacing(m_OutputSpacing); output->SetOrigin(m_OutputOrigin); // Add the metadata set by the user to the output output->m_Imd.Add(MDGeom::ProjectionProj, std::string(m_Transform->GetInputProjectionRef())); if (m_Transform->GetInputImageMetadata() != nullptr) output->m_Imd.Merge(*m_Transform->GetInputImageMetadata()); } // InstantiateTransform method template <class TDEMImage> void DEMToImageGenerator<TDEMImage>::InstantiateTransform() { m_Transform->InstantiateTransform(); } template <class TDEMImage> void DEMToImageGenerator<TDEMImage>::BeforeThreadedGenerateData() { InstantiateTransform(); DEMImagePointerType DEMImage = this->GetOutput(); // allocate the output buffer DEMImage->SetBufferedRegion(DEMImage->GetRequestedRegion()); DEMImage->Allocate(); DEMImage->FillBuffer(0); } template <class TDEMImage> void DEMToImageGenerator<TDEMImage>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId) { DEMImagePointerType DEMImage = this->GetOutput(); // Create an iterator that will walk the output region ImageIteratorType outIt = ImageIteratorType(DEMImage, outputRegionForThread); // support progress methods/callbacks itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); // Walk the output image, evaluating the height at each pixel IndexType currentindex; PointType phyPoint; double height; PointType geoPoint; for (outIt.GoToBegin(); !outIt.IsAtEnd(); ++outIt) { currentindex = outIt.GetIndex(); DEMImage->TransformIndexToPhysicalPoint(currentindex, phyPoint); if (m_Transform.IsNotNull()) { geoPoint = m_Transform->TransformPoint(phyPoint); if (m_AboveEllipsoid) { height = DEMHandler::GetInstance().GetHeightAboveEllipsoid(geoPoint); // Altitude // calculation } else { height = DEMHandler::GetInstance().GetHeightAboveMSL(geoPoint); // Altitude // calculation } } else { if (m_AboveEllipsoid) { height = DEMHandler::GetInstance().GetHeightAboveEllipsoid(phyPoint); // Altitude // calculation } else { height = DEMHandler::GetInstance().GetHeightAboveMSL(phyPoint); // Altitude // calculation } } /* otbMsgDevMacro(<< "Index : (" << currentindex[0]<< "," << currentindex[1] << ") -> PhyPoint : (" << phyPoint[0] << "," << phyPoint[1] << ") -> GeoPoint: (" << geoPoint[0] << "," << geoPoint[1] << ") -> height" << height); */ // otbMsgDevMacro(<< "height" << height); // DEM sets a default value (-32768) at point where it doesn't have altitude information. // OSSIM has chosen to change this default value in OSSIM_DBL_NAN (-4.5036e15). if (!vnl_math_isnan(height)) { // Fill the image DEMImage->SetPixel(currentindex, static_cast<PixelType>(height)); } else { // Back to the MNT default value DEMImage->SetPixel(currentindex, m_DefaultUnknownValue); } progress.CompletedPixel(); } } template <class TDEMImage> void DEMToImageGenerator<TDEMImage>::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Output Spacing:" << m_OutputSpacing[0] << "," << m_OutputSpacing[1] << std::endl; os << indent << "Output Origin:" << m_OutputOrigin[0] << "," << m_OutputOrigin[1] << std::endl; os << indent << "Output Size:" << m_OutputSize[0] << "," << m_OutputSize[1] << std::endl; } } // namespace otb #endif <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ // // This example illustrates how to read a DICOM series into a volume // and then save this volume into another DICOM series using the // exact same name. // It makes use of the GDCM library // #include "itkImageSeriesReader.h" #include "itkImageSeriesWriter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkGDCMImageIO.h" #include "itkGDCMSeriesFileNames.h" int itkGDCMSeriesReadImageWriteTest( int argc, char* argv[] ) { if( argc < 3 ) { std::cerr << "Usage: " << argv[0] << " DicomDirectory outputFile OutputDicomDirectory" << std::endl; return EXIT_FAILURE; } typedef itk::Image<unsigned short,3> ImageType; typedef itk::ImageSeriesReader< ImageType > ReaderType; typedef itk::GDCMImageIO ImageIOType; typedef itk::GDCMSeriesFileNames SeriesFileNames; ImageIOType::Pointer gdcmIO = ImageIOType::New(); SeriesFileNames::Pointer it = SeriesFileNames::New(); // Get the DICOM filenames from the directory // First add a restriction *before* selecting the input directory // since SetInputDirectory has a side effect of executing gdcm::SerieHelper *sh = it->GetSeriesHelper( ); sh->AddRestriction(0x0010, 0x0010, "Wes Turner", gdcm::GDCM_EQUAL); sh->AddRestriction(0x0020, 0x0013, "75", gdcm::GDCM_GREATEROREQUAL); sh->AddRestriction(0x0020, 0x0013, "77", gdcm::GDCM_LESSOREQUAL); it->SetInputDirectory( argv[1] ); ReaderType::Pointer reader = ReaderType::New(); const ReaderType::FileNamesContainer & filenames = it->GetInputFileNames(); unsigned int numberOfFilenames = filenames.size(); std::cout << numberOfFilenames << std::endl; for(unsigned int fni = 0; fni<numberOfFilenames; fni++) { std::cout << "filename # " << fni << " = "; std::cout << filenames[fni] << std::endl; } reader->SetFileNames( filenames ); reader->SetImageIO( gdcmIO ); try { reader->Update(); } catch (itk::ExceptionObject &excp) { std::cerr << "Exception thrown while writing the image" << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput( reader->GetOutput() ); try { writer->Update(); } catch (itk::ExceptionObject &excp) { std::cerr << "Exception thrown while writing the image" << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } // Writing image afer downscaling to 8bits (unsigned char) typedef itk::Image< unsigned short, 3> Image3DType; typedef itk::Image< unsigned char, 3> RescaleImageType; typedef itk::Image< unsigned char, 2> OutputImageType; typedef itk::RescaleIntensityImageFilter< Image3DType, RescaleImageType > RescaleFilterType; RescaleFilterType::Pointer rescaler = RescaleFilterType::New(); rescaler->SetInput( reader->GetOutput() ); rescaler->SetOutputMinimum( 0 ); rescaler->SetOutputMaximum( 255 ); typedef itk::ImageSeriesWriter< RescaleImageType, OutputImageType > SeriesWriterRescaleType; SeriesWriterRescaleType::Pointer swriter2 = SeriesWriterRescaleType::New(); it->SetOutputDirectory( argv[3] ); swriter2->SetInput( rescaler->GetOutput() ); swriter2->SetImageIO( gdcmIO ); swriter2->SetFileNames( it->GetOutputFileNames() ); swriter2->SetMetaDataDictionaryArray( reader->GetMetaDataDictionaryArray() ); try { swriter2->Update(); } catch (itk::ExceptionObject & e) { std::cerr << "exception in file writer " << std::endl; std::cerr << e << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>BUG: Set output type to unsigned char when writing uchar in GDCMIO test.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ // // This example illustrates how to read a DICOM series into a volume // and then save this volume into another DICOM series using the // exact same name. // It makes use of the GDCM library // #include "itkImageSeriesReader.h" #include "itkImageSeriesWriter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkGDCMImageIO.h" #include "itkGDCMSeriesFileNames.h" int itkGDCMSeriesReadImageWriteTest( int argc, char* argv[] ) { if( argc < 3 ) { std::cerr << "Usage: " << argv[0] << " DicomDirectory outputFile OutputDicomDirectory" << std::endl; return EXIT_FAILURE; } typedef itk::Image<unsigned short,3> ImageType; typedef itk::ImageSeriesReader< ImageType > ReaderType; typedef itk::GDCMImageIO ImageIOType; typedef itk::GDCMSeriesFileNames SeriesFileNames; ImageIOType::Pointer gdcmIO = ImageIOType::New(); SeriesFileNames::Pointer it = SeriesFileNames::New(); // Get the DICOM filenames from the directory // First add a restriction *before* selecting the input directory // since SetInputDirectory has a side effect of executing gdcm::SerieHelper *sh = it->GetSeriesHelper( ); sh->AddRestriction(0x0010, 0x0010, "Wes Turner", gdcm::GDCM_EQUAL); sh->AddRestriction(0x0020, 0x0013, "75", gdcm::GDCM_GREATEROREQUAL); sh->AddRestriction(0x0020, 0x0013, "77", gdcm::GDCM_LESSOREQUAL); it->SetInputDirectory( argv[1] ); ReaderType::Pointer reader = ReaderType::New(); const ReaderType::FileNamesContainer & filenames = it->GetInputFileNames(); unsigned int numberOfFilenames = filenames.size(); std::cout << numberOfFilenames << std::endl; for(unsigned int fni = 0; fni<numberOfFilenames; fni++) { std::cout << "filename # " << fni << " = "; std::cout << filenames[fni] << std::endl; } reader->SetFileNames( filenames ); reader->SetImageIO( gdcmIO ); try { reader->Update(); } catch (itk::ExceptionObject &excp) { std::cerr << "Exception thrown while writing the image" << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput( reader->GetOutput() ); try { writer->Update(); } catch (itk::ExceptionObject &excp) { std::cerr << "Exception thrown while writing the image" << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } // Writing image afer downscaling to 8bits (unsigned char) typedef itk::Image< unsigned short, 3> Image3DType; typedef itk::Image< unsigned char, 3> RescaleImageType; typedef itk::Image< unsigned char, 2> OutputImageType; typedef itk::RescaleIntensityImageFilter< Image3DType, RescaleImageType > RescaleFilterType; RescaleFilterType::Pointer rescaler = RescaleFilterType::New(); rescaler->SetInput( reader->GetOutput() ); rescaler->SetOutputMinimum( 0 ); rescaler->SetOutputMaximum( 255 ); typedef itk::ImageSeriesWriter< RescaleImageType, OutputImageType > SeriesWriterRescaleType; SeriesWriterRescaleType::Pointer swriter2 = SeriesWriterRescaleType::New(); it->SetOutputDirectory( argv[3] ); swriter2->SetInput( rescaler->GetOutput() ); swriter2->SetImageIO( gdcmIO ); gdcmIO->SetInternalComponentType( itk::ImageIOBase::UCHAR ); swriter2->SetFileNames( it->GetOutputFileNames() ); swriter2->SetMetaDataDictionaryArray( reader->GetMetaDataDictionaryArray() ); try { swriter2->Update(); } catch (itk::ExceptionObject & e) { std::cerr << "exception in file writer " << std::endl; std::cerr << e << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: options.cxx,v $ * $Revision: 1.17 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_idlc.hxx" #include <stdio.h> #include /*MSVC trouble: <cstring>*/ <string.h> #include <idlc/options.hxx> using namespace rtl; Options::Options(): m_stdin(false) { } Options::~Options() { } sal_Bool Options::initOptions(int ac, char* av[], sal_Bool bCmdFile) throw( IllegalArgument ) { sal_Bool ret = sal_True; sal_uInt16 j=0; if (!bCmdFile) { bCmdFile = sal_True; m_program = av[0]; if (ac < 2) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } j = 1; } else { j = 0; } char *s=NULL; for (; j < ac; j++) { if (av[j][0] == '-') { switch (av[j][1]) { case 'O': if (av[j][2] == '\0') { if (j < ac - 1 && av[j+1][0] != '-') { j++; s = av[j]; } else { OString tmp("'-O', please check"); if (j <= ac - 1) { tmp += " your input '" + OString(av[j+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[j] + 2; } m_options["-O"] = OString(s); break; case 'I': { if (av[j][2] == '\0') { if (j < ac - 1 && av[j+1][0] != '-') { j++; s = av[j]; } else { OString tmp("'-I', please check"); if (j <= ac - 1) { tmp += " your input '" + OString(av[j+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[j] + 2; } OString inc(s); if ( inc.indexOf(';') > 0 ) { OString tmp(s); sal_Int32 nIndex = 0; inc = OString(); do inc = inc + " -I\"" + tmp.getToken( 0, ';', nIndex ) +"\""; while( nIndex != -1 ); } else inc = OString("-I\"") + s + "\""; if (m_options.count("-I") > 0) { OString tmp(m_options["-I"]); tmp = tmp + " " + inc; m_options["-I"] = tmp; } else { m_options["-I"] = inc; } } break; case 'D': if (av[j][2] == '\0') { if (j < ac - 1 && av[j+1][0] != '-') { j++; s = av[j]; } else { OString tmp("'-D', please check"); if (j <= ac - 1) { tmp += " your input '" + OString(av[j+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[j]; } if (m_options.count("-D") > 0) { OString tmp(m_options["-D"]); tmp = tmp + " " + s; m_options["-D"] = tmp; } else m_options["-D"] = OString(s); break; case 'C': if (av[j][2] != '\0') { throw IllegalArgument(OString(av[j]) + ", please check your input"); } if (m_options.count("-C") == 0) m_options["-C"] = OString(av[j]); break; case 'c': if (av[j][2] == 'i' && av[j][3] == 'd' && av[j][4] == '\0') { if (m_options.count("-cid") == 0) m_options["-cid"] = OString(av[j]); } else throw IllegalArgument(OString(av[j]) + ", please check your input"); break; case 'w': if (av[j][2] == 'e' && av[j][3] == '\0') { if (m_options.count("-we") == 0) m_options["-we"] = OString(av[j]); } else { if (av[j][2] == '\0') { if (m_options.count("-w") == 0) m_options["-w"] = OString(av[j]); } else throw IllegalArgument(OString(av[j]) + ", please check your input"); } break; case 'h': case '?': if (av[j][2] != '\0') { throw IllegalArgument(OString(av[j]) + ", please check your input"); } else { fprintf(stdout, "%s", prepareHelp().getStr()); exit(0); } case 's': if (/*MSVC trouble: std::*/strcmp(&av[j][2], "tdin") == 0) { m_stdin = true; break; } // fall through default: throw IllegalArgument("the option is unknown" + OString(av[j])); } } else { if (av[j][0] == '@') { FILE* cmdFile = fopen(av[j]+1, "r"); if( cmdFile == NULL ) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } else { int rargc=0; char* rargv[512]; char buffer[512]=""; int i=0; int found = 0; char c; while ( fscanf(cmdFile, "%c", &c) != EOF ) { if (c=='\"') { if (found) { found=0; } else { found=1; continue; } } else { if (c!=13 && c!=10) { if (found || c!=' ') { buffer[i++]=c; continue; } } if (i==0) continue; } buffer[i]='\0'; found=0; i=0; rargv[rargc]= strdup(buffer); rargc++; buffer[0]='\0'; } if (buffer[0] != '\0') { buffer[i]='\0'; rargv[rargc]= strdup(buffer); rargc++; } fclose(cmdFile); ret = initOptions(rargc, rargv, bCmdFile); long ii = 0; for (ii=0; ii < rargc; ii++) { free(rargv[ii]); } } } else { OString name(av[j]); name = name.toAsciiLowerCase(); if ( name.lastIndexOf(".idl") != (name.getLength() - 4) ) { throw IllegalArgument("'" + OString(av[j]) + "' is not a valid input file, only '*.idl' files will be accepted"); } m_inputFiles.push_back(av[j]); } } } return ret; } OString Options::prepareHelp() { OString help("\nusing: "); help += m_program + " [-options] <file_1> ... <file_n> | @<filename> | -stdin\n"; help += " <file_n> = file_n specifies one or more idl files.\n"; help += " Only files with the extension '.idl' are valid.\n"; help += " @<filename> = filename specifies the name of a command file.\n"; help += " -stdin = read idl file from standard input.\n"; help += " Options:\n"; help += " -O<path> = path specifies the output directory.\n"; help += " The generated output is a registry file with\n"; help += " the same name as the idl input file (or 'stdin'\n"; help += " for -stdin).\n"; help += " -I<path> = path specifies a directory where include\n"; help += " files will be searched by the preprocessor.\n"; help += " Multiple directories can be combined with ';'.\n"; help += " -D<name> = name defines a macro for the preprocessor.\n"; help += " -C = generate complete type information, including\n"; help += " documentation.\n"; help += " -cid = check if identifiers fulfill the UNO naming\n"; help += " requirements.\n"; help += " -w = display warning messages.\n"; help += " -we = treat warnings as errors.\n"; help += " -h|-? = print this help message and exit.\n"; help += prepareVersion(); return help; } OString Options::prepareVersion() { OString version("\nSun Microsystems (R) "); version += m_program + " Version 1.1\n\n"; return version; } const OString& Options::getProgramName() const { return m_program; } sal_uInt16 Options::getNumberOfOptions() const { return (sal_uInt16)(m_options.size()); } sal_Bool Options::isValid(const OString& option) { return (m_options.count(option) > 0); } const OString Options::getOption(const OString& option) throw( IllegalArgument ) { if (m_options.count(option) > 0) { return m_options[option]; } else { throw IllegalArgument("Option is not valid or currently not set."); } } const OptionMap& Options::getOptions() { return m_options; } <commit_msg>INTEGRATION: CWS jsc21 (1.17.4); FILE MERGED 2008/06/20 11:12:53 jsc 1.17.4.1: #i86349# remove unused methods<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: options.cxx,v $ * $Revision: 1.18 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_idlc.hxx" #include <stdio.h> #include /*MSVC trouble: <cstring>*/ <string.h> #include <idlc/options.hxx> using namespace rtl; Options::Options(): m_stdin(false) { } Options::~Options() { } sal_Bool Options::initOptions(int ac, char* av[], sal_Bool bCmdFile) throw( IllegalArgument ) { sal_Bool ret = sal_True; sal_uInt16 j=0; if (!bCmdFile) { bCmdFile = sal_True; m_program = av[0]; if (ac < 2) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } j = 1; } else { j = 0; } char *s=NULL; for (; j < ac; j++) { if (av[j][0] == '-') { switch (av[j][1]) { case 'O': if (av[j][2] == '\0') { if (j < ac - 1 && av[j+1][0] != '-') { j++; s = av[j]; } else { OString tmp("'-O', please check"); if (j <= ac - 1) { tmp += " your input '" + OString(av[j+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[j] + 2; } m_options["-O"] = OString(s); break; case 'I': { if (av[j][2] == '\0') { if (j < ac - 1 && av[j+1][0] != '-') { j++; s = av[j]; } else { OString tmp("'-I', please check"); if (j <= ac - 1) { tmp += " your input '" + OString(av[j+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[j] + 2; } OString inc(s); if ( inc.indexOf(';') > 0 ) { OString tmp(s); sal_Int32 nIndex = 0; inc = OString(); do inc = inc + " -I\"" + tmp.getToken( 0, ';', nIndex ) +"\""; while( nIndex != -1 ); } else inc = OString("-I\"") + s + "\""; if (m_options.count("-I") > 0) { OString tmp(m_options["-I"]); tmp = tmp + " " + inc; m_options["-I"] = tmp; } else { m_options["-I"] = inc; } } break; case 'D': if (av[j][2] == '\0') { if (j < ac - 1 && av[j+1][0] != '-') { j++; s = av[j]; } else { OString tmp("'-D', please check"); if (j <= ac - 1) { tmp += " your input '" + OString(av[j+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[j]; } if (m_options.count("-D") > 0) { OString tmp(m_options["-D"]); tmp = tmp + " " + s; m_options["-D"] = tmp; } else m_options["-D"] = OString(s); break; case 'C': if (av[j][2] != '\0') { throw IllegalArgument(OString(av[j]) + ", please check your input"); } if (m_options.count("-C") == 0) m_options["-C"] = OString(av[j]); break; case 'c': if (av[j][2] == 'i' && av[j][3] == 'd' && av[j][4] == '\0') { if (m_options.count("-cid") == 0) m_options["-cid"] = OString(av[j]); } else throw IllegalArgument(OString(av[j]) + ", please check your input"); break; case 'w': if (av[j][2] == 'e' && av[j][3] == '\0') { if (m_options.count("-we") == 0) m_options["-we"] = OString(av[j]); } else { if (av[j][2] == '\0') { if (m_options.count("-w") == 0) m_options["-w"] = OString(av[j]); } else throw IllegalArgument(OString(av[j]) + ", please check your input"); } break; case 'h': case '?': if (av[j][2] != '\0') { throw IllegalArgument(OString(av[j]) + ", please check your input"); } else { fprintf(stdout, "%s", prepareHelp().getStr()); exit(0); } case 's': if (/*MSVC trouble: std::*/strcmp(&av[j][2], "tdin") == 0) { m_stdin = true; break; } // fall through default: throw IllegalArgument("the option is unknown" + OString(av[j])); } } else { if (av[j][0] == '@') { FILE* cmdFile = fopen(av[j]+1, "r"); if( cmdFile == NULL ) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } else { int rargc=0; char* rargv[512]; char buffer[512]=""; int i=0; int found = 0; char c; while ( fscanf(cmdFile, "%c", &c) != EOF ) { if (c=='\"') { if (found) { found=0; } else { found=1; continue; } } else { if (c!=13 && c!=10) { if (found || c!=' ') { buffer[i++]=c; continue; } } if (i==0) continue; } buffer[i]='\0'; found=0; i=0; rargv[rargc]= strdup(buffer); rargc++; buffer[0]='\0'; } if (buffer[0] != '\0') { buffer[i]='\0'; rargv[rargc]= strdup(buffer); rargc++; } fclose(cmdFile); ret = initOptions(rargc, rargv, bCmdFile); long ii = 0; for (ii=0; ii < rargc; ii++) { free(rargv[ii]); } } } else { OString name(av[j]); name = name.toAsciiLowerCase(); if ( name.lastIndexOf(".idl") != (name.getLength() - 4) ) { throw IllegalArgument("'" + OString(av[j]) + "' is not a valid input file, only '*.idl' files will be accepted"); } m_inputFiles.push_back(av[j]); } } } return ret; } OString Options::prepareHelp() { OString help("\nusing: "); help += m_program + " [-options] <file_1> ... <file_n> | @<filename> | -stdin\n"; help += " <file_n> = file_n specifies one or more idl files.\n"; help += " Only files with the extension '.idl' are valid.\n"; help += " @<filename> = filename specifies the name of a command file.\n"; help += " -stdin = read idl file from standard input.\n"; help += " Options:\n"; help += " -O<path> = path specifies the output directory.\n"; help += " The generated output is a registry file with\n"; help += " the same name as the idl input file (or 'stdin'\n"; help += " for -stdin).\n"; help += " -I<path> = path specifies a directory where include\n"; help += " files will be searched by the preprocessor.\n"; help += " Multiple directories can be combined with ';'.\n"; help += " -D<name> = name defines a macro for the preprocessor.\n"; help += " -C = generate complete type information, including\n"; help += " documentation.\n"; help += " -cid = check if identifiers fulfill the UNO naming\n"; help += " requirements.\n"; help += " -w = display warning messages.\n"; help += " -we = treat warnings as errors.\n"; help += " -h|-? = print this help message and exit.\n"; help += prepareVersion(); return help; } OString Options::prepareVersion() { OString version("\nSun Microsystems (R) "); version += m_program + " Version 1.1\n\n"; return version; } const OString& Options::getProgramName() const { return m_program; } sal_Bool Options::isValid(const OString& option) { return (m_options.count(option) > 0); } const OString Options::getOption(const OString& option) throw( IllegalArgument ) { if (m_options.count(option) > 0) { return m_options[option]; } else { throw IllegalArgument("Option is not valid or currently not set."); } } <|endoftext|>
<commit_before>#include "webcam.hpp" using namespace cv; using namespace std; int main (int argc, char** argv) { CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); //imshow("webcam", image); // thresholds on dark regions Mat gray, blurred_gray, threshold_gray; cvtColor(image, gray, CV_BGR2GRAY); blur(gray, blurred_gray, Size(width/10,height/20)); equalizeHist(blurred_gray, blurred_gray); bitwise_not(blurred_gray, blurred_gray); threshold(blurred_gray, threshold_gray, 210, 1, THRESH_BINARY); imshow("threshold", threshold_gray); Mat mask = threshold_gray.mul(gray); imshow("mask", mask); Moments lol = moments(mask, 1); circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); imshow("leimage", image); keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" using namespace cv; using namespace std; int main (int argc, char** argv) { CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); //imshow("webcam", image); // thresholds on dark regions Mat gray, blurred_gray, threshold_gray; cvtColor(image, gray, CV_BGR2GRAY); blur(gray, blurred_gray, Size(width/10,height/20)); equalizeHist(blurred_gray, blurred_gray); bitwise_not(blurred_gray, blurred_gray); threshold(blurred_gray, threshold_gray, 210, 1, THRESH_BINARY); imshow("threshold", threshold_gray); Mat mask = threshold_gray.mul(gray); bitwise_not(mask, mask); imshow("mask", mask); Moments lol = moments(mask, 1); circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); imshow("leimage", image); keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2015 Belledonne Communications SARL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "configdumper.hh" #include "module.hh" using namespace std; ostream &ConfigDumper::dump(ostream &ostr) const{ return dump_recursive(ostr, mRoot, 0); } ostream& ConfigDumper::dump_recursive(std::ostream &ostr, const GenericEntry *entry, unsigned int level) const { const GenericStruct *cs = dynamic_cast<const GenericStruct*>(entry); const ConfigValue* value = dynamic_cast<const ConfigValue*>(entry); if( cs && shouldDumpModule(cs->getName()) ){ dumpModuleHead(ostr, cs, level); for( auto it = cs->getChildren().begin(); it != cs->getChildren().end(); ++it ){ GenericEntry* child = *it; dump_recursive(ostr, child, level+1); } } else if( value ){ dumpModuleValue(ostr, value, level); } return ostr; } #define MODULE_PREFIX_LEN 8 /* strlen("module::") */ bool ConfigDumper::shouldDumpModule(const string& moduleName) const { // When the dumpExperimental is activated, we should dump everything if( mDumpExperimental ) return true; string name = moduleName; if( name.find("module::") != name.npos ){ name = moduleName.substr(MODULE_PREFIX_LEN); } auto moduleInfos = ModuleFactory::get()->moduleInfos(); auto it = std::find_if(moduleInfos.begin(), moduleInfos.end(), [name](ModuleInfoBase* i){ return i->getModuleName() == name; }); ModuleInfoBase* moduleInfo = (it != moduleInfos.end()) ? *it : nullptr; if( moduleInfo != nullptr ){ return moduleInfo->type() == ModuleTypeProduction; } else { return true; } } /* FILE CONFIG DUMPER */ ostream & FileConfigDumper::printHelp(ostream &os, const string &help, const string &comment_prefix) const { const char *p=help.c_str(); const char *begin=p; const char *origin=help.c_str(); for(;*p!=0;++p){ if ((p-begin>60 && *p==' ') || *p=='\n'){ os<<comment_prefix<<" "<<help.substr(begin-origin,p-begin)<<endl; p++; begin=p; } } os<<comment_prefix<<" "<<help.substr(begin-origin,p-origin)<<endl; return os; } ostream & FileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const { if (val && !val->getExportToConfigFile()) return ostr; if( !val->isDeprecated() ){ printHelp(ostr,val->getHelp(),"#"); ostr<<"# Default value: "<<val->getDefault()<<endl; if (mDumpDefault) { ostr<<val->getName()<<"="<<val->getDefault()<<endl; } else { ostr<<val->getName()<<"="<<val->get()<<endl; } ostr << endl; } return ostr; } ostream & FileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *moduleHead, int level) const { if (moduleHead && !moduleHead->getExportToConfigFile()) return ostr; ostr<<"##"<<endl; printHelp(ostr,moduleHead->getHelp(),"##"); ostr<<"##"<<endl; if (level>0){ ostr<<"["<<moduleHead->getName()<<"]"<<endl; } else ostr<<endl; ostr << endl << endl << endl; return ostr; } /* TexFileComfigDumper */ static void escaper(string &str, char c, const string &replaced) { size_t i=0; while(string::npos != (i=str.find_first_of(c, i))) { str.erase(i, 1); str.insert(i, replaced); i+=replaced.length(); } } static void string_escaper(string& str, const string &s, const string &replace){ size_t i=0; while(string::npos != (i=str.find(s, i))) { str.erase(i, s.length()); str.insert(i, replace); i+=replace.length(); } } string TexFileConfigDumper::escape(const string &strc) const{ std::string str(strc); escaper(str, '_', "\\_"); escaper(str, '<', "\\textless{}"); escaper(str, '>', "\\textgreater{}"); return str; } ostream& TexFileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const { if (cs->getParent()) { string pn=escape(cs->getPrettyName()); ostr<<"\\section{"<< pn << "}" << endl << endl; ostr<<"\\label{" << cs->getName() << "}" << endl; ostr<<"\\subsection{Description}"<< endl <<endl; ostr<<escape(cs->getHelp())<< endl <<endl; ostr<<"\\subsection{Parameters}"<< endl <<endl; } return ostr; } ostream& TexFileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const { if( !val->isDeprecated() ){ ostr<<"\\subsubsection{"<<escape(val->getName())<<"}"<<endl; ostr<<escape(val->getHelp())<<endl; ostr<<"The default value is ``"<<escape(val->getDefault())<<"''."<<endl; ostr<<endl; } return ostr; } /* Dokuwiki */ ostream& DokuwikiConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const { if(!val->isDeprecated()){ // dokuwiki handles line breaks with double backspaces string help = val->getHelp(); escaper(help, '\n', "\\\\ "); escaper(help, '`', "'' "); string_escaper(help, ". ", ".\\\\ "); ostr << "|" << "**" << val->getName() << "**" << " | " << help << " | " << "''" << val->getDefault() << "''" << " | " << val->getTypeName() << " | " << endl; } return ostr; } ostream& DokuwikiConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const { // we have a generic struc: we're on top level: get module name and description ostr << "====" << cs->getPrettyName() << "====" << endl; ostr << endl << cs->getHelp() << endl; ostr << endl << "Configuration options:" << endl; ostr << "^ Name ^ Description ^ Default value ^ Type ^" << endl; return ostr; } /* MIB */ ostream &MibDumper::dump(ostream & ostr)const { const time_t t = getCurrentTime(); char mbstr[100]; strftime(mbstr, sizeof(mbstr), "%Y%m%d0000Z", localtime(&t)); ostr << "FLEXISIP-MIB DEFINITIONS ::= BEGIN" << endl << "IMPORTS" << endl << " OBJECT-TYPE, Integer32, MODULE-IDENTITY, enterprises," << endl << " Counter64,NOTIFICATION-TYPE FROM SNMPv2-SMI" << endl << " MODULE-COMPLIANCE, OBJECT-GROUP FROM SNMPv2-CONF;" << endl << endl << "flexisipMIB MODULE-IDENTITY" << endl << " LAST-UPDATED \"" << mbstr <<"\"" << endl << " ORGANIZATION \"belledonne-communications\"" << endl << " CONTACT-INFO \"postal: 34 Avenue de L'europe 38 100 Grenoble France" << endl << " email: contact@belledonne-communications.com\"" << endl << " DESCRIPTION \"A Flexisip management tree.\"" << endl << " REVISION \"" <<mbstr <<"\""<<endl << " DESCRIPTION \"" PACKAGE_VERSION << "\"" << endl << "::={ enterprises "<< company_id << " }" << endl << endl; dump2(ostr,mRoot,0); ostr << "END" << endl; return ostr; } ostream &MibDumper::dump2(ostream & ostr, GenericEntry *entry, int level)const{ GenericStruct *cs=dynamic_cast<GenericStruct*>(entry); ConfigValue *cVal; StatCounter64 *sVal; NotificationEntry *ne; string spacing=""; while (level > 0) { spacing += " "; --level; } if (cs && shouldDumpModule(cs->getName())){ cs->mibFragment(ostr, spacing); for(auto it=cs->getChildren().begin();it!=cs->getChildren().end();++it){ if (!cs->isDeprecated()){ dump2(ostr,*it,level+1); ostr<<endl; } } }else if ((cVal=dynamic_cast<ConfigValue*>(entry))!=NULL){ cVal->mibFragment(ostr, spacing); }else if ((sVal=dynamic_cast<StatCounter64*>(entry))!=NULL){ sVal->mibFragment(ostr, spacing); }else if ((ne=dynamic_cast<NotificationEntry*>(entry))!=NULL){ ne->mibFragment(ostr,spacing); } return ostr; } <commit_msg>C++0x<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2015 Belledonne Communications SARL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "configdumper.hh" #include "module.hh" using namespace std; ostream &ConfigDumper::dump(ostream &ostr) const{ return dump_recursive(ostr, mRoot, 0); } ostream& ConfigDumper::dump_recursive(std::ostream &ostr, const GenericEntry *entry, unsigned int level) const { const GenericStruct *cs = dynamic_cast<const GenericStruct*>(entry); const ConfigValue* value = dynamic_cast<const ConfigValue*>(entry); if( cs && shouldDumpModule(cs->getName()) ){ dumpModuleHead(ostr, cs, level); for( auto it = cs->getChildren().begin(); it != cs->getChildren().end(); ++it ){ GenericEntry* child = *it; dump_recursive(ostr, child, level+1); } } else if( value ){ dumpModuleValue(ostr, value, level); } return ostr; } struct matchModuleName { const std::string& mName; matchModuleName(const std::string &name ) : mName(name) {} bool operator()(const ModuleInfoBase* mi) { return (mi->getModuleName() == mName); } }; #define MODULE_PREFIX_LEN 8 /* strlen("module::") */ bool ConfigDumper::shouldDumpModule(const string& moduleName) const { // When the dumpExperimental is activated, we should dump everything if( mDumpExperimental ) return true; string name = moduleName; if( name.find("module::") != name.npos ){ name = moduleName.substr(MODULE_PREFIX_LEN); } auto moduleInfos = ModuleFactory::get()->moduleInfos(); auto it = std::find_if(moduleInfos.begin(), moduleInfos.end(), matchModuleName(name)); ModuleInfoBase* moduleInfo = (it != moduleInfos.end()) ? *it : NULL; if( moduleInfo != NULL ){ return moduleInfo->type() == ModuleTypeProduction; } else { return true; } } /* FILE CONFIG DUMPER */ ostream & FileConfigDumper::printHelp(ostream &os, const string &help, const string &comment_prefix) const { const char *p=help.c_str(); const char *begin=p; const char *origin=help.c_str(); for(;*p!=0;++p){ if ((p-begin>60 && *p==' ') || *p=='\n'){ os<<comment_prefix<<" "<<help.substr(begin-origin,p-begin)<<endl; p++; begin=p; } } os<<comment_prefix<<" "<<help.substr(begin-origin,p-origin)<<endl; return os; } ostream & FileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const { if (val && !val->getExportToConfigFile()) return ostr; if( !val->isDeprecated() ){ printHelp(ostr,val->getHelp(),"#"); ostr<<"# Default value: "<<val->getDefault()<<endl; if (mDumpDefault) { ostr<<val->getName()<<"="<<val->getDefault()<<endl; } else { ostr<<val->getName()<<"="<<val->get()<<endl; } ostr << endl; } return ostr; } ostream & FileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *moduleHead, int level) const { if (moduleHead && !moduleHead->getExportToConfigFile()) return ostr; ostr<<"##"<<endl; printHelp(ostr,moduleHead->getHelp(),"##"); ostr<<"##"<<endl; if (level>0){ ostr<<"["<<moduleHead->getName()<<"]"<<endl; } else ostr<<endl; ostr << endl << endl << endl; return ostr; } /* TexFileComfigDumper */ static void escaper(string &str, char c, const string &replaced) { size_t i=0; while(string::npos != (i=str.find_first_of(c, i))) { str.erase(i, 1); str.insert(i, replaced); i+=replaced.length(); } } static void string_escaper(string& str, const string &s, const string &replace){ size_t i=0; while(string::npos != (i=str.find(s, i))) { str.erase(i, s.length()); str.insert(i, replace); i+=replace.length(); } } string TexFileConfigDumper::escape(const string &strc) const{ std::string str(strc); escaper(str, '_', "\\_"); escaper(str, '<', "\\textless{}"); escaper(str, '>', "\\textgreater{}"); return str; } ostream& TexFileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const { if (cs->getParent()) { string pn=escape(cs->getPrettyName()); ostr<<"\\section{"<< pn << "}" << endl << endl; ostr<<"\\label{" << cs->getName() << "}" << endl; ostr<<"\\subsection{Description}"<< endl <<endl; ostr<<escape(cs->getHelp())<< endl <<endl; ostr<<"\\subsection{Parameters}"<< endl <<endl; } return ostr; } ostream& TexFileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const { if( !val->isDeprecated() ){ ostr<<"\\subsubsection{"<<escape(val->getName())<<"}"<<endl; ostr<<escape(val->getHelp())<<endl; ostr<<"The default value is ``"<<escape(val->getDefault())<<"''."<<endl; ostr<<endl; } return ostr; } /* Dokuwiki */ ostream& DokuwikiConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const { if(!val->isDeprecated()){ // dokuwiki handles line breaks with double backspaces string help = val->getHelp(); escaper(help, '\n', "\\\\ "); escaper(help, '`', "'' "); string_escaper(help, ". ", ".\\\\ "); ostr << "|" << "**" << val->getName() << "**" << " | " << help << " | " << "''" << val->getDefault() << "''" << " | " << val->getTypeName() << " | " << endl; } return ostr; } ostream& DokuwikiConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const { // we have a generic struc: we're on top level: get module name and description ostr << "====" << cs->getPrettyName() << "====" << endl; ostr << endl << cs->getHelp() << endl; ostr << endl << "Configuration options:" << endl; ostr << "^ Name ^ Description ^ Default value ^ Type ^" << endl; return ostr; } /* MIB */ ostream &MibDumper::dump(ostream & ostr)const { const time_t t = getCurrentTime(); char mbstr[100]; strftime(mbstr, sizeof(mbstr), "%Y%m%d0000Z", localtime(&t)); ostr << "FLEXISIP-MIB DEFINITIONS ::= BEGIN" << endl << "IMPORTS" << endl << " OBJECT-TYPE, Integer32, MODULE-IDENTITY, enterprises," << endl << " Counter64,NOTIFICATION-TYPE FROM SNMPv2-SMI" << endl << " MODULE-COMPLIANCE, OBJECT-GROUP FROM SNMPv2-CONF;" << endl << endl << "flexisipMIB MODULE-IDENTITY" << endl << " LAST-UPDATED \"" << mbstr <<"\"" << endl << " ORGANIZATION \"belledonne-communications\"" << endl << " CONTACT-INFO \"postal: 34 Avenue de L'europe 38 100 Grenoble France" << endl << " email: contact@belledonne-communications.com\"" << endl << " DESCRIPTION \"A Flexisip management tree.\"" << endl << " REVISION \"" <<mbstr <<"\""<<endl << " DESCRIPTION \"" PACKAGE_VERSION << "\"" << endl << "::={ enterprises "<< company_id << " }" << endl << endl; dump2(ostr,mRoot,0); ostr << "END" << endl; return ostr; } ostream &MibDumper::dump2(ostream & ostr, GenericEntry *entry, int level)const{ GenericStruct *cs=dynamic_cast<GenericStruct*>(entry); ConfigValue *cVal; StatCounter64 *sVal; NotificationEntry *ne; string spacing=""; while (level > 0) { spacing += " "; --level; } if (cs && shouldDumpModule(cs->getName())){ cs->mibFragment(ostr, spacing); for(auto it=cs->getChildren().begin();it!=cs->getChildren().end();++it){ if (!cs->isDeprecated()){ dump2(ostr,*it,level+1); ostr<<endl; } } }else if ((cVal=dynamic_cast<ConfigValue*>(entry))!=NULL){ cVal->mibFragment(ostr, spacing); }else if ((sVal=dynamic_cast<StatCounter64*>(entry))!=NULL){ sVal->mibFragment(ostr, spacing); }else if ((ne=dynamic_cast<NotificationEntry*>(entry))!=NULL){ ne->mibFragment(ostr,spacing); } return ostr; } <|endoftext|>
<commit_before>#include "SkyUtils.h" #include "../Math/Constants.h" #include "components/debug/Debug.h" int SkyUtils::getOctantIndex(bool posX, bool posY, bool posZ) { // Use lowest 3 bits to represent 0-7. const char xBit = posX ? 0 : (1 << 0); const char yBit = posY ? 0 : (1 << 1); const char zBit = posZ ? 0 : (1 << 2); return xBit | yBit | zBit; } Double3 SkyUtils::getSkyObjectDirection(Radians angleX, Radians angleY) { // @todo: some sine and cosine functions DebugNotImplemented(); return Double3(); } void SkyUtils::getSkyObjectDimensions(int imageWidth, int imageHeight, double *outWidth, double *outHeight) { DebugNotImplemented(); // @todo: use ArenaSkyUtils constexpr values? *outWidth = 0; *outHeight = 0; } int SkyUtils::getStarCountFromDensity(int starDensity) { if (starDensity == 0) { // Classic. return 40; } else if (starDensity == 1) { // Moderate. return 1000; } else if (starDensity == 2) { // High. return 8000; } else { DebugUnhandledReturnMsg(int, std::to_string(starDensity)); } } <commit_msg>Implemented SkyUtils::getSkyObjectDirection().<commit_after>#include <cmath> #include "SkyUtils.h" #include "../Math/Constants.h" #include "components/debug/Debug.h" int SkyUtils::getOctantIndex(bool posX, bool posY, bool posZ) { // Use lowest 3 bits to represent 0-7. const char xBit = posX ? 0 : (1 << 0); const char yBit = posY ? 0 : (1 << 1); const char zBit = posZ ? 0 : (1 << 2); return xBit | yBit | zBit; } VoxelDouble3 SkyUtils::getSkyObjectDirection(Radians angleX, Radians angleY) { return VoxelDouble3( -std::sin(angleX), std::sin(angleY), -std::cos(angleX)).normalized(); } void SkyUtils::getSkyObjectDimensions(int imageWidth, int imageHeight, double *outWidth, double *outHeight) { DebugNotImplemented(); // @todo: use ArenaSkyUtils constexpr values? *outWidth = 0; *outHeight = 0; } int SkyUtils::getStarCountFromDensity(int starDensity) { if (starDensity == 0) { // Classic. return 40; } else if (starDensity == 1) { // Moderate. return 1000; } else if (starDensity == 2) { // High. return 8000; } else { DebugUnhandledReturnMsg(int, std::to_string(starDensity)); } } <|endoftext|>
<commit_before>/* Persons Model Contact Item Represents person's contact item in the model Copyright (C) 2012 Martin Klapetek <martin.klapetek@gmail.com> Copyright (C) 2012 Aleix Pol Gonzalez <aleixpol@blue-systems.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contactitem.h" #include "personpluginmanager.h" #include "basepersonsdatasource.h" #include "base-persons-data-source.h" #include <QAction> #include <KIcon> #include <KDebug> #include <KServiceTypeTrader> #include <kdemacros.h> #include <Nepomuk2/Resource> #include <Nepomuk2/Variant> #include <Nepomuk2/ResourceManager> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Vocabulary/NIE> #include <Soprano/Vocabulary/NAO> #include <Soprano/Model> #include <Soprano/QueryResultIterator> class ContactItemPrivate { public: QUrl uri; QHash<int, QVariant> data; bool isBeingUpdated; ///@returns a list of the roles that we'll expect to be a QVariantList static QSet<int> listRoles() { static QSet<int> s_listRoles; if(s_listRoles.isEmpty()) { //TODO: document this in persons-model.h s_listRoles.insert(PersonsModel::PhotosRole); s_listRoles.insert(PersonsModel::EmailsRole); s_listRoles.insert(PersonsModel::PhonesRole); } return s_listRoles; } }; ContactItem::ContactItem(const QUrl &uri) : d_ptr(new ContactItemPrivate) { // setData(uri, PersonsModel::UriRole); d_ptr->uri = uri; d_ptr->isBeingUpdated = false; } ContactItem::~ContactItem() { delete d_ptr; } void ContactItem::setContactData(int role, const QVariant &v) { Q_D(ContactItem); if (v.isNull()) { //don't insert empty values, in case of list roles this //would insert QVariant(QVariantList(QVariant())), //empty QVariant will be returned from data(...) instead return; } QHash< int, QVariant >::iterator it = d->data.find(role); QVariant value = d->listRoles().contains(role) ? (QVariantList() << v) : v; if (it == d->data.end()) { d->data.insert(role, value); emitDataChanged(); } else if (*it != value) { Q_ASSERT(value.type() == it->type()); *it = value; emitDataChanged(); } } //TODO update so value can be a list. This will then concat onto any existing list. void ContactItem::addContactData(int role, const QVariant &value) { Q_D(ContactItem); if (value.isNull()) { //don't insert empty values, in case of list roles this //would insert QVariant(QVariantList(QVariant())), //empty QVariant will be returned from data(...) instead return; } QHash<int, QVariant>::iterator it = d->data.find(role); if (!d->listRoles().contains(role)) { setContactData(role, value); } else { if (it == d->data.end()) { d->data.insert(role, QVariantList() << value); emitDataChanged(); } else if (*it != value) { Q_ASSERT(it->type() == QVariant::List); QVariantList current = it->toList(); Q_ASSERT(current.isEmpty() || current.first().type()==value.type()); current.append(value); *it = current; emitDataChanged(); } } } void ContactItem::removeData(int role) { Q_D(ContactItem); if (d->data.remove(role)) { emitDataChanged(); } } QUrl ContactItem::uri() const { Q_D(const ContactItem); return d->uri; } QVariant ContactItem::data(int role) const { Q_D(const ContactItem); QHash<int, QVariant>::const_iterator it = d->data.constFind(role); if (it!=d->data.constEnd()) { return *it; } switch(role) { case Qt::DisplayRole: if (!data(PersonsModel::NicknamesRole).isNull()) { return data(PersonsModel::NicknamesRole); } if (!data(PersonsModel::FullNamesRole).isNull()) { return data(PersonsModel::FullNamesRole); } if (!data(PersonsModel::EmailsRole).isNull()) { return data(PersonsModel::EmailsRole); } if (!data(PersonsModel::IMsRole).isNull()) { return data(PersonsModel::IMsRole); } if (!data(PersonsModel::PhonesRole).isNull()) { return data(PersonsModel::PhonesRole); } return QString("Unknown contact"); case Qt::DecorationRole: { const QVariantList photos = d->data.value(PersonsModel::PhotosRole).toList(); return photos.isEmpty() ? KIcon("im-user") : KIcon(photos.first().toUrl().toLocalFile()); } case PersonsModel::UriRole: return d->uri; break; case PersonsModel::PresenceTypeRole: case PersonsModel::PresenceDisplayRole: case PersonsModel::PresenceDecorationRole: return PersonPluginManager::presencePlugin()->dataForContact(data(PersonsModel::IMsRole).toString(), role); } return QStandardItem::data(role); } void ContactItem::loadData() { Q_D(ContactItem); if (d->isBeingUpdated) { kDebug() << "Contact already being updated"; return; } d->data.clear(); PersonsModel *m = qobject_cast<PersonsModel*>(model()); if (m) { d->isBeingUpdated = true; m->updateContact(this); } } void ContactItem::finishLoadingData() { Q_D(ContactItem); d->isBeingUpdated = false; emitDataChanged(); } <commit_msg>Contact node can be updated only if there's valid PersonsModel pointer<commit_after>/* Persons Model Contact Item Represents person's contact item in the model Copyright (C) 2012 Martin Klapetek <martin.klapetek@gmail.com> Copyright (C) 2012 Aleix Pol Gonzalez <aleixpol@blue-systems.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contactitem.h" #include "personpluginmanager.h" #include "basepersonsdatasource.h" #include "base-persons-data-source.h" #include <QAction> #include <KIcon> #include <KDebug> #include <KServiceTypeTrader> #include <kdemacros.h> #include <Nepomuk2/Resource> #include <Nepomuk2/Variant> #include <Nepomuk2/ResourceManager> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Vocabulary/NIE> #include <Soprano/Vocabulary/NAO> #include <Soprano/Model> #include <Soprano/QueryResultIterator> class ContactItemPrivate { public: QUrl uri; QHash<int, QVariant> data; bool isBeingUpdated; ///@returns a list of the roles that we'll expect to be a QVariantList static QSet<int> listRoles() { static QSet<int> s_listRoles; if(s_listRoles.isEmpty()) { //TODO: document this in persons-model.h s_listRoles.insert(PersonsModel::PhotosRole); s_listRoles.insert(PersonsModel::EmailsRole); s_listRoles.insert(PersonsModel::PhonesRole); } return s_listRoles; } }; ContactItem::ContactItem(const QUrl &uri) : d_ptr(new ContactItemPrivate) { // setData(uri, PersonsModel::UriRole); d_ptr->uri = uri; d_ptr->isBeingUpdated = false; } ContactItem::~ContactItem() { delete d_ptr; } void ContactItem::setContactData(int role, const QVariant &v) { Q_D(ContactItem); if (v.isNull()) { //don't insert empty values, in case of list roles this //would insert QVariant(QVariantList(QVariant())), //empty QVariant will be returned from data(...) instead return; } QHash< int, QVariant >::iterator it = d->data.find(role); QVariant value = d->listRoles().contains(role) ? (QVariantList() << v) : v; if (it == d->data.end()) { d->data.insert(role, value); emitDataChanged(); } else if (*it != value) { Q_ASSERT(value.type() == it->type()); *it = value; emitDataChanged(); } } //TODO update so value can be a list. This will then concat onto any existing list. void ContactItem::addContactData(int role, const QVariant &value) { Q_D(ContactItem); if (value.isNull()) { //don't insert empty values, in case of list roles this //would insert QVariant(QVariantList(QVariant())), //empty QVariant will be returned from data(...) instead return; } QHash<int, QVariant>::iterator it = d->data.find(role); if (!d->listRoles().contains(role)) { setContactData(role, value); } else { if (it == d->data.end()) { d->data.insert(role, QVariantList() << value); emitDataChanged(); } else if (*it != value) { Q_ASSERT(it->type() == QVariant::List); QVariantList current = it->toList(); Q_ASSERT(current.isEmpty() || current.first().type()==value.type()); current.append(value); *it = current; emitDataChanged(); } } } void ContactItem::removeData(int role) { Q_D(ContactItem); if (d->data.remove(role)) { emitDataChanged(); } } QUrl ContactItem::uri() const { Q_D(const ContactItem); return d->uri; } QVariant ContactItem::data(int role) const { Q_D(const ContactItem); QHash<int, QVariant>::const_iterator it = d->data.constFind(role); if (it!=d->data.constEnd()) { return *it; } switch(role) { case Qt::DisplayRole: if (!data(PersonsModel::NicknamesRole).isNull()) { return data(PersonsModel::NicknamesRole); } if (!data(PersonsModel::FullNamesRole).isNull()) { return data(PersonsModel::FullNamesRole); } if (!data(PersonsModel::EmailsRole).isNull()) { return data(PersonsModel::EmailsRole); } if (!data(PersonsModel::IMsRole).isNull()) { return data(PersonsModel::IMsRole); } if (!data(PersonsModel::PhonesRole).isNull()) { return data(PersonsModel::PhonesRole); } return QString("Unknown contact"); case Qt::DecorationRole: { const QVariantList photos = d->data.value(PersonsModel::PhotosRole).toList(); return photos.isEmpty() ? KIcon("im-user") : KIcon(photos.first().toUrl().toLocalFile()); } case PersonsModel::UriRole: return d->uri; break; case PersonsModel::PresenceTypeRole: case PersonsModel::PresenceDisplayRole: case PersonsModel::PresenceDecorationRole: return PersonPluginManager::presencePlugin()->dataForContact(data(PersonsModel::IMsRole).toString(), role); } return QStandardItem::data(role); } void ContactItem::loadData() { Q_D(ContactItem); if (d->isBeingUpdated) { kDebug() << "Contact already being updated"; return; } d->data.clear(); PersonsModel *m = qobject_cast<PersonsModel*>(model()); Q_ASSERT(m); //crash if this contact is not part of the model d->isBeingUpdated = true; m->updateContact(this); } void ContactItem::finishLoadingData() { Q_D(ContactItem); d->isBeingUpdated = false; emitDataChanged(); } <|endoftext|>
<commit_before>//_________________________________________________________________________ // Utility Class for transverse energy studies // Task for analysis // - reconstruction and MC output // implementation file // //*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL) //_________________________________________________________________________ //Necessary to read config macros #include <TROOT.h> #include <TSystem.h> #include <TInterpreter.h> #include "TChain.h" #include "TList.h" #include "TFile.h" #include "TH2F.h" #include "THnSparse.h" #include "AliESDEvent.h" #include "AliMCEvent.h" #include "AliESDtrackCuts.h" #include "AliAnalysisTaskTotEt.h" #include "AliAnalysisEtReconstructedPhos.h" #include "AliAnalysisEtReconstructedEmcal.h" #include "AliAnalysisEtMonteCarloPhos.h" #include "AliAnalysisEtMonteCarloEmcal.h" #include "AliAnalysisEmEtMonteCarlo.h" #include "AliAnalysisEmEtReconstructed.h" #include <iostream> #include <AliCentrality.h> using namespace std; ClassImp(AliAnalysisTaskTotEt) //________________________________________________________________________ AliAnalysisTaskTotEt::AliAnalysisTaskTotEt(const char *name, Bool_t isMc) : AliAnalysisTaskTransverseEnergy(name, isMc) ,fRecAnalysis(0) ,fMCAnalysis(0) ,fSparseHistRecVsMc(0) ,fSparseRecVsMc(0) { // Constructor // select if we should use EMCal or PHOS class // PHOS by default, EMCal if name string contains EMC TString t(name); //t.ToUpper(); if (t.Contains("EMC")) { if (t.Contains("Detail")) { fMCAnalysis = new AliAnalysisEmEtMonteCarlo(); fMCAnalysis->SetDataSet(2010); fMCAnalysis->Init(); cout << "Instantiating AliAnalysisEmEtMonteCarlo class..."<< endl; } else if (fMCConfigFile.Length()) { cout<<"Rereading AliAnalysisEtMonteCarloEmcal configuration file..."<<endl; gROOT->LoadMacro(fMCConfigFile); fMCAnalysis = (AliAnalysisEtMonteCarloEmcal *) gInterpreter->ProcessLine("ConfigEtMonteCarlo()"); } if (t.Contains("Detail")) { fRecAnalysis = new AliAnalysisEmEtReconstructed(); fRecAnalysis->SetDataSet(2010); TFile *infile = new TFile("corrections.root"); fRecAnalysis->SetCorrections((AliAnalysisHadEtCorrections *)infile->Get("hadCorrectionEMCAL")); fRecAnalysis->Init(); cout << "Instantiating AliAnalysisEmEtReconstructed class..."<< endl; } else if (fRecoConfigFile.Length()) { cout<<"Rereading AliAnalysisEtReconstructedEmcal configuration file..."<<endl; gROOT->LoadMacro(fRecoConfigFile); fRecAnalysis = (AliAnalysisEtReconstructedEmcal *) gInterpreter->ProcessLine("ConfigEtReconstructed()"); } } else { if (fMCConfigFile.Length()) { cout<<"Rereading AliAnalysisEtMonteCarloPhos configuration file..."<<endl; gROOT->LoadMacro(fMCConfigFile); fMCAnalysis = (AliAnalysisEtMonteCarloPhos *) gInterpreter->ProcessLine("ConfigEtMonteCarlo(false)"); cout << fMCAnalysis << endl; } if (fRecoConfigFile.Length()) { cout<<"Rereading AliAnalysisEtReconstructedPhos configuration file..."<<endl; gROOT->LoadMacro(fRecoConfigFile); fRecAnalysis = (AliAnalysisEtReconstructedPhos *) gInterpreter->ProcessLine("ConfigEtReconstructed(false)"); } } // Define input and output slots here // Input slot #0 works with a TChain DefineInput(0, TChain::Class()); // Output slot #1 writes into a TH1 container DefineOutput(1, TList::Class()); } AliAnalysisTaskTotEt::~AliAnalysisTaskTotEt() {//Destructor // fOutputList->Clear(); delete fRecAnalysis; delete fMCAnalysis; } //________________________________________________________________________ void AliAnalysisTaskTotEt::UserCreateOutputObjects() { // Create histograms // Called once if (fMCAnalysis) fMCAnalysis->CreateHistograms(); fRecAnalysis->CreateHistograms(); fOutputList = new TList; fOutputList->SetOwner(); fRecAnalysis->FillOutputList(fOutputList); if (fMCAnalysis) fMCAnalysis->FillOutputList(fOutputList); fHistEtRecvsEtMC = new TH2F("fHistEtRecvsEtMC", "Reconstructed E_{T} vs MC E_{T}", 1000, 0.000, 100, 1000, 0.0001, 100); fHistEtRecOverEtMC = new TH2F("fHistEtRecOverEtMC", "Reconstructed E_{T} over MC E_{T} vs centrality", 1000, 0.00, 2.0, 11, -0.5, 10.5); fHistDiffEtRecEtMCOverEtMC = new TH2F("fHistDiffEtRecEtMCOverEtMC", "fHistDiffEtRecEtMCOverEtMC", 10000, 0.0, 1000, 1000, -5, 5); fOutputList->Add(fHistEtRecvsEtMC); fOutputList->Add(fHistEtRecOverEtMC); fOutputList->Add(fHistDiffEtRecEtMCOverEtMC); Bool_t selectPrimaries=kTRUE; if (fRecAnalysis->DataSet()==2009) { cout<<"Setting track cuts for the 2009 p+p collisions at 900 GeV"<<endl; fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2009(selectPrimaries); fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts"); fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly"); //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required fEsdtrackCutsITS = AliESDtrackCuts::GetStandardITSPureSATrackCuts2009(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info fEsdtrackCutsITS->SetName("fEsdTrackCutsITS"); } if (fRecAnalysis->DataSet()==2010) { cout<<"Setting track cuts for the 2010 p+p collisions at 7 GeV"<<endl; //cout<<"Warning: Have not set 2010 track cuts yet!!"<<endl; fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries); fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts"); fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly"); //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required fEsdtrackCutsITS = AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info fEsdtrackCutsITS->SetName("fEsdTrackCutsITS"); } fOutputList->Add(fEsdtrackCutsITSTPC); fOutputList->Add(fEsdtrackCutsTPC); fOutputList->Add(fEsdtrackCutsITS); if (fEsdtrackCutsITSTPC && fEsdtrackCutsTPC) { fRecAnalysis->SetITSTrackCuts( GetITSTrackCuts()); if (fMCAnalysis) fMCAnalysis->SetITSTrackCuts( GetITSTrackCuts()); fRecAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts()); if (fMCAnalysis) fMCAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts()); fRecAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts()); if (fMCAnalysis) fMCAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts()); //add ITS stuff! } else { Printf("Error: no track cuts!"); } } //________________________________________________________________________ void AliAnalysisTaskTotEt::UserExec(Option_t *) { // execute method fESDEvent = dynamic_cast<AliESDEvent*>(InputEvent()); if (!fESDEvent) { Printf("ERROR: Could not retrieve event"); return; } //Int_t res = CheckPhysicsSelection(fESDEvent->GetRunNumber()); AliCentrality *cent = GetCentralityObject(); //if (res == 0 && cent) //{ if (IsPhysicsSelected()) { fRecAnalysis->SetCentralityObject(cent); fRecAnalysis->AnalyseEvent(fESDEvent); AliMCEvent* mcEvent = MCEvent(); if (mcEvent) { fMCAnalysis->SetCentralityObject(cent); fMCAnalysis->AnalyseEvent(mcEvent, fESDEvent); //fMCAnalysis->AnalyseEvent(mcEvent); } if(fMCAnalysis) { fHistEtRecvsEtMC->Fill(fRecAnalysis->GetTotNeutralEtAcc(), fMCAnalysis->GetTotNeutralEtAcc()); if(fMCAnalysis->GetTotNeutralEtAcc()) fHistEtRecOverEtMC->Fill(fRecAnalysis->GetTotNeutralEt()/fMCAnalysis->GetTotNeutralEtAcc(), cent->GetCentralityClass10("V0M")); if(fMCAnalysis->GetTotNeutralEtAcc()) fHistDiffEtRecEtMCOverEtMC->Fill(fMCAnalysis->GetTotNeutralEt(), (fRecAnalysis->GetTotNeutralEt()-fMCAnalysis->GetTotNeutralEt())/fMCAnalysis->GetTotNeutralEt()); } } //} // Post output data. PostData(1, fOutputList); } //________________________________________________________________________ void AliAnalysisTaskTotEt::Terminate(Option_t *) { // Draw result to the screen // Called once at the end of the query fOutputList = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutputList) { printf("ERROR: Output list not available\n"); return; } } <commit_msg>Configuring AliAnalysisEmEtMonteCarlo and AliAnalysisEmEtReconstructed with config files instead of manually, fixing memory leaks, updating track cuts used to match proper analysis<commit_after>//_________________________________________________________________________ // Utility Class for transverse energy studies // Task for analysis // - reconstruction and MC output // implementation file // //*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL) //_________________________________________________________________________ //Necessary to read config macros #include <TROOT.h> #include <TSystem.h> #include <TInterpreter.h> #include "TChain.h" #include "TList.h" #include "TFile.h" #include "TH2F.h" #include "THnSparse.h" #include "AliESDEvent.h" #include "AliMCEvent.h" #include "AliESDtrackCuts.h" #include "AliAnalysisTaskTotEt.h" #include "AliAnalysisEtReconstructedPhos.h" #include "AliAnalysisEtReconstructedEmcal.h" #include "AliAnalysisEtMonteCarloPhos.h" #include "AliAnalysisEtMonteCarloEmcal.h" #include "AliAnalysisEmEtMonteCarlo.h" #include "AliAnalysisEmEtReconstructed.h" #include <iostream> #include <AliCentrality.h> using namespace std; ClassImp(AliAnalysisTaskTotEt) //________________________________________________________________________ AliAnalysisTaskTotEt::AliAnalysisTaskTotEt(const char *name, Bool_t isMc) : AliAnalysisTaskTransverseEnergy(name, isMc) ,fRecAnalysis(0) ,fMCAnalysis(0) ,fSparseHistRecVsMc(0) ,fSparseRecVsMc(0) { // Constructor // select if we should use EMCal or PHOS class // PHOS by default, EMCal if name string contains EMC TString t(name); //t.ToUpper(); if (t.Contains("EMC")) { if (t.Contains("Detail")) { cout<<"Rereading AliAnalysisEtMonteCarlo configuration file..."<<endl; gROOT->LoadMacro(fMCConfigFile); fMCAnalysis = (AliAnalysisEmEtMonteCarlo *) gInterpreter->ProcessLine("ConfigEtMonteCarlo(true,true)"); cout << "Instantiating AliAnalysisEmEtMonteCarlo class..."<< endl; } else if (fMCConfigFile.Length()) { cout<<"Rereading AliAnalysisEtMonteCarloEmcal configuration file..."<<endl; gROOT->LoadMacro(fMCConfigFile); fMCAnalysis = (AliAnalysisEtMonteCarloEmcal *) gInterpreter->ProcessLine("ConfigEtMonteCarlo()"); } if (t.Contains("Detail")) { cout<<"Rereading AliAnalysisEmEtReconstructed configuration file..."<<endl; gROOT->LoadMacro(fRecoConfigFile); fRecAnalysis = (AliAnalysisEmEtReconstructed *) gInterpreter->ProcessLine("ConfigEtReconstructed(true,true)"); } else if (fRecoConfigFile.Length()) { cout<<"Rereading AliAnalysisEtReconstructedEmcal configuration file..."<<endl; gROOT->LoadMacro(fRecoConfigFile); fRecAnalysis = (AliAnalysisEtReconstructedEmcal *) gInterpreter->ProcessLine("ConfigEtReconstructed()"); } } else { if (fMCConfigFile.Length()) { cout<<"Rereading AliAnalysisEtMonteCarloPhos configuration file..."<<endl; gROOT->LoadMacro(fMCConfigFile); fMCAnalysis = (AliAnalysisEtMonteCarloPhos *) gInterpreter->ProcessLine("ConfigEtMonteCarlo(false)"); cout << fMCAnalysis << endl; } if (fRecoConfigFile.Length()) { cout<<"Rereading AliAnalysisEtReconstructedPhos configuration file..."<<endl; gROOT->LoadMacro(fRecoConfigFile); fRecAnalysis = (AliAnalysisEtReconstructedPhos *) gInterpreter->ProcessLine("ConfigEtReconstructed(false)"); } } // Define input and output slots here // Input slot #0 works with a TChain DefineInput(0, TChain::Class()); // Output slot #1 writes into a TH1 container DefineOutput(1, TList::Class()); } AliAnalysisTaskTotEt::~AliAnalysisTaskTotEt() {//Destructor // fOutputList->Clear(); delete fRecAnalysis; delete fMCAnalysis; delete fSparseHistRecVsMc; delete fSparseRecVsMc; } //________________________________________________________________________ void AliAnalysisTaskTotEt::UserCreateOutputObjects() { // Create histograms // Called once if (fMCAnalysis) fMCAnalysis->CreateHistograms(); fRecAnalysis->CreateHistograms(); fOutputList = new TList; fOutputList->SetOwner(); fRecAnalysis->FillOutputList(fOutputList); if (fMCAnalysis) fMCAnalysis->FillOutputList(fOutputList); fHistEtRecvsEtMC = new TH2F("fHistEtRecvsEtMC", "Reconstructed E_{T} vs MC E_{T}", 1000, 0.000, 100, 1000, 0.0001, 100); fHistEtRecOverEtMC = new TH2F("fHistEtRecOverEtMC", "Reconstructed E_{T} over MC E_{T} vs centrality", 1000, 0.00, 2.0, 11, -0.5, 10.5); fHistDiffEtRecEtMCOverEtMC = new TH2F("fHistDiffEtRecEtMCOverEtMC", "fHistDiffEtRecEtMCOverEtMC", 10000, 0.0, 1000, 1000, -5, 5); fOutputList->Add(fHistEtRecvsEtMC); fOutputList->Add(fHistEtRecOverEtMC); fOutputList->Add(fHistDiffEtRecEtMCOverEtMC); Bool_t selectPrimaries=kTRUE; if(fRecAnalysis->DataSet()==2010 || fRecAnalysis->DataSet()==20111||fRecAnalysis->DataSet()==2009){ if(fRecAnalysis->DataSet()==2010)cout<<"Setting track cuts for the 2010 p+p collisions at 7 TeV"<<endl; else{ if(fRecAnalysis->DataSet()==2009){cout<<"Setting track cuts for the 2010 p+p collisions at 900 GeV"<<endl;} else{cout<<"Setting track cuts for the 2011 p+p collisions at 2.76 TeV"<<endl;} } //cout<<"Warning: Have not set 2010 track cuts yet!!"<<endl; fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries); fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts"); fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly"); //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required fEsdtrackCutsITS = AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info fEsdtrackCutsITS->SetName("fEsdTrackCutsITS"); } if(fRecAnalysis->DataSet()==20100){ cout<<"Setting track cuts for the 2010 Pb+Pb collisions at 2.76 TeV"<<endl; //cout<<"Warning: Have not set 2010 track cuts yet!!"<<endl; fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries); fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts"); fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly"); //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required fEsdtrackCutsITS = AliESDtrackCuts::GetStandardITSSATrackCutsPbPb2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info // fEsdtrackCutsITS = AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info fEsdtrackCutsITS->SetName("fEsdTrackCutsITS"); } fOutputList->Add(fEsdtrackCutsITSTPC); fOutputList->Add(fEsdtrackCutsTPC); fOutputList->Add(fEsdtrackCutsITS); if (fEsdtrackCutsITSTPC && fEsdtrackCutsTPC) { fRecAnalysis->SetITSTrackCuts( GetITSTrackCuts()); if (fMCAnalysis) fMCAnalysis->SetITSTrackCuts( GetITSTrackCuts()); fRecAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts()); if (fMCAnalysis) fMCAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts()); fRecAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts()); if (fMCAnalysis) fMCAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts()); //add ITS stuff! } else { Printf("Error: no track cuts!"); } } //________________________________________________________________________ void AliAnalysisTaskTotEt::UserExec(Option_t *) { // execute method fESDEvent = dynamic_cast<AliESDEvent*>(InputEvent()); if (!fESDEvent) { Printf("ERROR: Could not retrieve event"); return; } //Int_t res = CheckPhysicsSelection(fESDEvent->GetRunNumber()); AliCentrality *cent = GetCentralityObject(); //if (res == 0 && cent) //{ if (IsPhysicsSelected()) { fRecAnalysis->SetCentralityObject(cent); fRecAnalysis->AnalyseEvent(fESDEvent); AliMCEvent* mcEvent = MCEvent(); if (mcEvent) { fMCAnalysis->SetCentralityObject(cent); fMCAnalysis->AnalyseEvent(mcEvent, fESDEvent); //fMCAnalysis->AnalyseEvent(mcEvent); } if(fMCAnalysis) { fHistEtRecvsEtMC->Fill(fRecAnalysis->GetTotNeutralEtAcc(), fMCAnalysis->GetTotNeutralEtAcc()); if(fMCAnalysis->GetTotNeutralEtAcc()) fHistEtRecOverEtMC->Fill(fRecAnalysis->GetTotNeutralEt()/fMCAnalysis->GetTotNeutralEtAcc(), cent->GetCentralityClass10("V0M")); if(fMCAnalysis->GetTotNeutralEtAcc()) fHistDiffEtRecEtMCOverEtMC->Fill(fMCAnalysis->GetTotNeutralEt(), (fRecAnalysis->GetTotNeutralEt()-fMCAnalysis->GetTotNeutralEt())/fMCAnalysis->GetTotNeutralEt()); } } //} // Post output data. PostData(1, fOutputList); } //________________________________________________________________________ void AliAnalysisTaskTotEt::Terminate(Option_t *) { // Draw result to the screen // Called once at the end of the query fOutputList = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutputList) { printf("ERROR: Output list not available\n"); return; } } <|endoftext|>
<commit_before>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* Posix implementation for gpr threads. */ #include <grpc/support/port_platform.h> #ifdef GPR_POSIX_SYNC #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include <grpc/support/thd.h> #include <grpc/support/useful.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include "src/core/lib/gpr/fork.h" static gpr_mu g_mu; static gpr_cv g_cv; static int g_thread_count; static int g_awaiting_threads; struct thd_arg { void (*body)(void* arg); /* body of a thread */ void* arg; /* argument to a thread */ const char* name; /* name of thread. Can be nullptr. */ }; static void inc_thd_count(); static void dec_thd_count(); /* Body of every thread started via gpr_thd_new. */ static void* thread_body(void* v) { struct thd_arg a = *(struct thd_arg*)v; free(v); if (a.name != nullptr) { #if GPR_APPLE_PTHREAD_NAME /* Apple supports 64 characters, and will truncate if it's longer. */ pthread_setname_np(a.name); #elif GPR_TIZENRT_PTHREAD_NAME pthread_setname_np(pthread_self(), a.name); #elif GPR_LINUX_PTHREAD_NAME /* Linux supports 16 characters max, and will error if it's longer. */ char buf[16]; size_t buf_len = GPR_ARRAY_SIZE(buf) - 1; strncpy(buf, a.name, buf_len); buf[buf_len] = '\0'; pthread_setname_np(pthread_self(), buf); #endif // GPR_APPLE_PTHREAD_NAME } (*a.body)(a.arg); dec_thd_count(); return nullptr; } // TODO(TizenRT) #ifndef GRPC_THD_CLIENT_STACK_SIZE #define GRPC_THD_CLIENT_STACK_SIZE 10240 #endif int gpr_thd_new(gpr_thd_id* t, const char* thd_name, void (*thd_body)(void* arg), void* arg, const gpr_thd_options* options) { int thread_started; pthread_attr_t attr; pthread_t p; /* don't use gpr_malloc as we may cause an infinite recursion with * the profiling code */ struct thd_arg* a = (struct thd_arg*)malloc(sizeof(*a)); GPR_ASSERT(a != nullptr); a->body = thd_body; a->arg = arg; a->name = thd_name; inc_thd_count(); GPR_ASSERT(pthread_attr_init(&attr) == 0); // TODO(TizenRT) #ifndef __TizenRT__ if (gpr_thd_options_is_detached(options)) { GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0); } else { GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) == 0); } #else int r; if ((r = pthread_attr_setstacksize(&attr, GRPC_THD_CLIENT_STACK_SIZE)) != 0) { return -1; } #endif thread_started = (pthread_create(&p, &attr, &thread_body, a) == 0); GPR_ASSERT(pthread_attr_destroy(&attr) == 0); if (!thread_started) { /* don't use gpr_free, as this was allocated using malloc (see above) */ free(a); dec_thd_count(); } *t = (gpr_thd_id)p; return thread_started; } gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)pthread_self(); } void gpr_thd_join(gpr_thd_id t) { pthread_join((pthread_t)t, nullptr); } /***************************************** * Only used when fork support is enabled */ static void inc_thd_count() { if (grpc_fork_support_enabled()) { gpr_mu_lock(&g_mu); g_thread_count++; gpr_mu_unlock(&g_mu); } } static void dec_thd_count() { if (grpc_fork_support_enabled()) { gpr_mu_lock(&g_mu); g_thread_count--; if (g_awaiting_threads && g_thread_count == 0) { gpr_cv_signal(&g_cv); } gpr_mu_unlock(&g_mu); } } void gpr_thd_init() { gpr_mu_init(&g_mu); gpr_cv_init(&g_cv); g_thread_count = 0; g_awaiting_threads = 0; } int gpr_await_threads(gpr_timespec deadline) { gpr_mu_lock(&g_mu); g_awaiting_threads = 1; int res = 0; if (g_thread_count > 0) { res = gpr_cv_wait(&g_cv, &g_mu, deadline); } g_awaiting_threads = 0; gpr_mu_unlock(&g_mu); return res == 0; } #endif /* GPR_POSIX_SYNC */ <commit_msg>external/grpc: Name grpc threads for debugging purposes, and understandability<commit_after>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* Posix implementation for gpr threads. */ #include <grpc/support/port_platform.h> #ifdef GPR_POSIX_SYNC #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include <grpc/support/thd.h> #include <grpc/support/useful.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include "src/core/lib/gpr/fork.h" static gpr_mu g_mu; static gpr_cv g_cv; static int g_thread_count; static int g_awaiting_threads; struct thd_arg { void (*body)(void* arg); /* body of a thread */ void* arg; /* argument to a thread */ const char* name; /* name of thread. Can be nullptr. */ }; static void inc_thd_count(); static void dec_thd_count(); /* Body of every thread started via gpr_thd_new. */ static void* thread_body(void* v) { struct thd_arg a = *(struct thd_arg*)v; free(v); if (a.name != nullptr) { #if GPR_APPLE_PTHREAD_NAME /* Apple supports 64 characters, and will truncate if it's longer. */ pthread_setname_np(a.name); #elif GPR_TIZENRT_PTHREAD_NAME pthread_setname_np(pthread_self(), a.name); #elif GPR_LINUX_PTHREAD_NAME /* Linux supports 16 characters max, and will error if it's longer. */ char buf[16]; size_t buf_len = GPR_ARRAY_SIZE(buf) - 1; strncpy(buf, a.name, buf_len); buf[buf_len] = '\0'; pthread_setname_np(pthread_self(), buf); #endif // GPR_APPLE_PTHREAD_NAME } (*a.body)(a.arg); dec_thd_count(); return nullptr; } // TODO(TizenRT) #ifndef GRPC_THD_CLIENT_STACK_SIZE #define GRPC_THD_CLIENT_STACK_SIZE 10240 #endif int gpr_thd_new(gpr_thd_id* t, const char* thd_name, void (*thd_body)(void* arg), void* arg, const gpr_thd_options* options) { int thread_started; pthread_attr_t attr; pthread_t p; /* don't use gpr_malloc as we may cause an infinite recursion with * the profiling code */ struct thd_arg* a = (struct thd_arg*)malloc(sizeof(*a)); GPR_ASSERT(a != nullptr); a->body = thd_body; a->arg = arg; a->name = thd_name; inc_thd_count(); GPR_ASSERT(pthread_attr_init(&attr) == 0); // TODO(TizenRT) #ifndef __TizenRT__ if (gpr_thd_options_is_detached(options)) { GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0); } else { GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) == 0); } #else int r; if ((r = pthread_attr_setstacksize(&attr, GRPC_THD_CLIENT_STACK_SIZE)) != 0) { return -1; } #endif thread_started = (pthread_create(&p, &attr, &thread_body, a) == 0); GPR_ASSERT(pthread_attr_destroy(&attr) == 0); if (!thread_started) { /* don't use gpr_free, as this was allocated using malloc (see above) */ free(a); dec_thd_count(); } else { pthread_setname_np(thread_started, a->name); } *t = (gpr_thd_id)p; return thread_started; } gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)pthread_self(); } void gpr_thd_join(gpr_thd_id t) { pthread_join((pthread_t)t, nullptr); } /***************************************** * Only used when fork support is enabled */ static void inc_thd_count() { if (grpc_fork_support_enabled()) { gpr_mu_lock(&g_mu); g_thread_count++; gpr_mu_unlock(&g_mu); } } static void dec_thd_count() { if (grpc_fork_support_enabled()) { gpr_mu_lock(&g_mu); g_thread_count--; if (g_awaiting_threads && g_thread_count == 0) { gpr_cv_signal(&g_cv); } gpr_mu_unlock(&g_mu); } } void gpr_thd_init() { gpr_mu_init(&g_mu); gpr_cv_init(&g_cv); g_thread_count = 0; g_awaiting_threads = 0; } int gpr_await_threads(gpr_timespec deadline) { gpr_mu_lock(&g_mu); g_awaiting_threads = 1; int res = 0; if (g_thread_count > 0) { res = gpr_cv_wait(&g_cv, &g_mu, deadline); } g_awaiting_threads = 0; gpr_mu_unlock(&g_mu); return res == 0; } #endif /* GPR_POSIX_SYNC */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: WinImplHelper.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-20 00:14:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _WINIMPLHELPER_HXX_ #define _WINIMPLHELPER_HXX_ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #include <windows.h> #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif //------------------------------------------------------------------------ // deklarations //------------------------------------------------------------------------ bool SAL_CALL IsWindows2000(); bool SAL_CALL IsWindowsXP(); bool SAL_CALL IsWindows98(); bool SAL_CALL IsWindowsME(); // returns true if the platform is // Windows 2000 or above bool SAL_CALL IsWindows2000Platform(); #define IsWin2000 IsWindows2000 // set actions void SAL_CALL ListboxAddItem( HWND hwnd, const ::com::sun::star::uno::Any& aItem, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang::IllegalArgumentException ); void SAL_CALL ListboxAddItems( HWND hwnd, const ::com::sun::star::uno::Any& aItemList, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang:: IllegalArgumentException ); void SAL_CALL ListboxDeleteItem( HWND hwnd, const ::com::sun::star::uno::Any& aPosition, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang::IllegalArgumentException ); void SAL_CALL ListboxDeleteItems( HWND hwnd, const ::com::sun::star::uno::Any& aUnused, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang::IllegalArgumentException ); void SAL_CALL ListboxSetSelectedItem( HWND hwnd, const ::com::sun::star::uno::Any& aPosition, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang::IllegalArgumentException ); // get actions ::com::sun::star::uno::Any SAL_CALL ListboxGetItems( HWND hwnd ); ::com::sun::star::uno::Any SAL_CALL ListboxGetSelectedItem( HWND hwnd ); ::com::sun::star::uno::Any SAL_CALL ListboxGetSelectedItemIndex( HWND hwnd ); // checkbox helper functions ::com::sun::star::uno::Any SAL_CALL CheckboxGetState( HWND hwnd ); void SAL_CALL CheckboxSetState( HWND hwnd, const ::com::sun::star::uno::Any& aState, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang::IllegalArgumentException ); // calculates the length of '\0' separated and '\0\0' // ending strings used in some Win32 functions // e.g. Filter\0*.txt\0\0 // the returned length excludes the last '\0' sal_uInt32 SAL_CALL _wcslenex( const sal_Unicode* pStr ); // converts a soffice label to a windows label // the following rules for character replacements // will be done: // '~' -> '&' // '~~' -> '~' // '&' -> '&&' rtl::OUString SOfficeToWindowsLabel( const rtl::OUString& aSOLabel ); // converts a windows label to a soffice label // the following rules for character replacements // will be done: // '&' -> '~' // '&&' -> '&' // '~' -> '~~' rtl::OUString WindowsToSOfficeLabel( const rtl::OUString& aWinLabel ); #endif <commit_msg>INTEGRATION: CWS sb59 (1.6.30); FILE MERGED 2006/08/10 12:04:54 sb 1.6.30.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: WinImplHelper.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-10-12 10:56:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _WINIMPLHELPER_HXX_ #define _WINIMPLHELPER_HXX_ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #if defined _MSC_VER #pragma warning(push, 1) #endif #include <windows.h> #if defined _MSC_VER #pragma warning(pop) #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif //------------------------------------------------------------------------ // deklarations //------------------------------------------------------------------------ bool SAL_CALL IsWindows2000(); bool SAL_CALL IsWindowsXP(); bool SAL_CALL IsWindows98(); bool SAL_CALL IsWindowsME(); // returns true if the platform is // Windows 2000 or above bool SAL_CALL IsWindows2000Platform(); #define IsWin2000 IsWindows2000 // set actions void SAL_CALL ListboxAddItem( HWND hwnd, const ::com::sun::star::uno::Any& aItem, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang::IllegalArgumentException ); void SAL_CALL ListboxAddItems( HWND hwnd, const ::com::sun::star::uno::Any& aItemList, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang:: IllegalArgumentException ); void SAL_CALL ListboxDeleteItem( HWND hwnd, const ::com::sun::star::uno::Any& aPosition, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang::IllegalArgumentException ); void SAL_CALL ListboxDeleteItems( HWND hwnd, const ::com::sun::star::uno::Any& aUnused, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang::IllegalArgumentException ); void SAL_CALL ListboxSetSelectedItem( HWND hwnd, const ::com::sun::star::uno::Any& aPosition, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang::IllegalArgumentException ); // get actions ::com::sun::star::uno::Any SAL_CALL ListboxGetItems( HWND hwnd ); ::com::sun::star::uno::Any SAL_CALL ListboxGetSelectedItem( HWND hwnd ); ::com::sun::star::uno::Any SAL_CALL ListboxGetSelectedItemIndex( HWND hwnd ); // checkbox helper functions ::com::sun::star::uno::Any SAL_CALL CheckboxGetState( HWND hwnd ); void SAL_CALL CheckboxSetState( HWND hwnd, const ::com::sun::star::uno::Any& aState, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos ) throw( ::com::sun::star::lang::IllegalArgumentException ); // calculates the length of '\0' separated and '\0\0' // ending strings used in some Win32 functions // e.g. Filter\0*.txt\0\0 // the returned length excludes the last '\0' sal_uInt32 SAL_CALL _wcslenex( const sal_Unicode* pStr ); // converts a soffice label to a windows label // the following rules for character replacements // will be done: // '~' -> '&' // '~~' -> '~' // '&' -> '&&' rtl::OUString SOfficeToWindowsLabel( const rtl::OUString& aSOLabel ); // converts a windows label to a soffice label // the following rules for character replacements // will be done: // '&' -> '~' // '&&' -> '&' // '~' -> '~~' rtl::OUString WindowsToSOfficeLabel( const rtl::OUString& aWinLabel ); #endif <|endoftext|>
<commit_before>#ifndef ANN_SCENERY_MANAGER #define ANN_SCENERY_MANAGER #include "systemMacro.h" #include "AnnSubsystem.hpp" #include "OgreSceneManager.h" #include "AnnTypes.h" #include "OgreVRRender.hpp" namespace Annwvyn { class DLL AnnSceneryManager : public AnnSubSystem { public: ///Construct the AnnSceneryManager AnnSceneryManager(OgreVRRender* renderer); ///This subsystem doesn't need to be updated bool needUpdate() { return false; } ///Set the ogre material for the skydome with params /// \param activate if true put a skydome /// \param materialName name of a material known from the Ogre Resource group manager /// \param curvature curvature of the texture /// \param tilling tilling of the texture void setSkyDomeMaterial(bool activate, const char materialName[], float curvature = 2.0f, float tiling = 1.0f); //scene ///Set the ogre material for the skybox with params /// \param activate if true put the skybox on the scene /// \param materialName name of a material declared on the resource manager /// \param distance distance of the sky from the camera /// \param renderedFirst if true, the skybox will be the first thing rendered void setSkyBoxMaterial(bool activate, const char materialName[], float distance = 8000, bool renderedFirst = true); ///Set the viewports background color /// \param v background color void setWorldBackgroundColor(AnnColor color = AnnColor(0, 0.56, 1)); ///Remove the sky dome void removeSkyDome(); ///Remove the sky box void removeSkyBox(); ///Set the ambiant light /// \param v the color of the light void setAmbiantLight(AnnColor color); ///Set the distance of the near clipping plane /// \param distace the distance to the clipping plane void setNearClippingDistance(float distance); private: ///Scene manager created by the VR renderer Ogre::SceneManager* smgr; ///Pointer to the VR renderer OgreVRRender* renderer; }; } #endif<commit_msg>Correct warning double -> float<commit_after>#ifndef ANN_SCENERY_MANAGER #define ANN_SCENERY_MANAGER #include "systemMacro.h" #include "AnnSubsystem.hpp" #include "OgreSceneManager.h" #include "AnnTypes.h" #include "OgreVRRender.hpp" namespace Annwvyn { class DLL AnnSceneryManager : public AnnSubSystem { public: ///Construct the AnnSceneryManager AnnSceneryManager(OgreVRRender* renderer); ///This subsystem doesn't need to be updated bool needUpdate() { return false; } ///Set the ogre material for the skydome with params /// \param activate if true put a skydome /// \param materialName name of a material known from the Ogre Resource group manager /// \param curvature curvature of the texture /// \param tilling tilling of the texture void setSkyDomeMaterial(bool activate, const char materialName[], float curvature = 2.0f, float tiling = 1.0f); //scene ///Set the ogre material for the skybox with params /// \param activate if true put the skybox on the scene /// \param materialName name of a material declared on the resource manager /// \param distance distance of the sky from the camera /// \param renderedFirst if true, the skybox will be the first thing rendered void setSkyBoxMaterial(bool activate, const char materialName[], float distance = 8000, bool renderedFirst = true); ///Set the viewports background color /// \param v background color void setWorldBackgroundColor(AnnColor color = AnnColor(0, 0.56f, 1)); ///Remove the sky dome void removeSkyDome(); ///Remove the sky box void removeSkyBox(); ///Set the ambiant light /// \param v the color of the light void setAmbiantLight(AnnColor color); ///Set the distance of the near clipping plane /// \param distace the distance to the clipping plane void setNearClippingDistance(float distance); private: ///Scene manager created by the VR renderer Ogre::SceneManager* smgr; ///Pointer to the VR renderer OgreVRRender* renderer; }; } #endif<|endoftext|>
<commit_before>#ifndef __LOG_VISOR_HPP__ #define __LOG_VISOR_HPP__ #include <stdarg.h> #include <string.h> #include <stdio.h> #include <vector> #include <atomic> #include <memory> #include <locale> #include <codecvt> namespace LogVisor { #if _WIN32 && UNICODE #define LOG_UCS2 1 #endif #if LOG_VISOR_EXCEPTIONS /** * @brief Exception thrown when FatalError is issued */ class FatalException : public std::exception { std::string m_what; public: FatalException(const char* format, va_list ap) { char buf[1024]; vsnprintf(buf, 1024, format, ap); m_what.assign(buf); } FatalException(const wchar_t* format, va_list ap) { wchar_t buf[1024]; vswprintf(buf, 1024, format, ap); std::wstring_convert<std::codecvt_utf8<wchar_t>> conv; m_what.assign(conv.to_bytes(buf)); } #if _MSC_VER inline const char* what() const {return m_what.c_str();} #else inline const char* what() const noexcept {return m_what.c_str();} #endif }; #endif /** * @brief Severity level for log messages */ enum Level { Info, /**< Non-error informative message */ Warning, /**< Non-error warning message */ Error, /**< Recoverable error message */ FatalError /**< Non-recoverable error message (throws exception) */ }; /** * @brief Backend interface for receiving app-wide log events */ struct ILogger { virtual ~ILogger() {} virtual void report(const char* modName, Level severity, const char* format, va_list ap)=0; virtual void report(const char* modName, Level severity, const wchar_t* format, va_list ap)=0; virtual void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const char* format, va_list ap)=0; virtual void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const wchar_t* format, va_list ap)=0; }; /** * @brief Assign calling thread a descriptive name * @param name Descriptive thread name */ void RegisterThreadName(const char* name); /** * @brief Centralized logger vector * * All loggers added to this vector will receive reports as they occur */ extern std::vector<std::unique_ptr<ILogger>> MainLoggers; /** * @brief Centralized error counter * * All submodules accumulate this value */ extern std::atomic_size_t ErrorCount; /** * @brief Centralized frame index * * All log events include this as part of their timestamp if non-zero. * The default value is zero, the app is responsible for updating it * within its main loop. */ extern std::atomic_uint_fast64_t FrameIndex; /** * @brief Restore centralized logger vector to default state (silent operation) */ static inline void UnregisterLoggers() {MainLoggers.clear();} /** * @brief Construct and register a real-time console logger singleton * * This will output to stderr on POSIX platforms and spawn a new console window on Windows. * If there's already a registered console logger, this is a no-op. */ void RegisterConsoleLogger(); /** * @brief Construct and register a file logger * @param filepath Path to write the file * * If there's already a file logger registered to the same file, this is a no-op. */ void RegisterFileLogger(const char* filepath); #if LOG_UCS2 /** * @brief Construct and register a file logger (wchar_t version) * @param filepath Path to write the file * * If there's already a file logger registered to the same file, this is a no-op. */ void RegisterFileLogger(const wchar_t* filepath); #endif /** * @brief This is constructed per-subsystem in a locally centralized fashon */ class LogModule { const char* m_modName; public: LogModule(const char* modName) : m_modName(modName) {} /** * @brief Route new log message to centralized ILogger * @param severity Level of log report severity * @param format Standard printf-style format string */ template <typename CharType> inline void report(Level severity, const CharType* format, ...) { va_list ap; va_start(ap, format); report(severity, format, ap); va_end(ap); } template <typename CharType> inline void report(Level severity, const CharType* format, va_list ap) { for (auto& logger : MainLoggers) logger->report(m_modName, severity, format, ap); if (severity == FatalError) #if LOG_VISOR_EXCEPTIONS throw FatalException(format, ap); #else abort(); #endif else if (severity == Error) ++ErrorCount; } /** * @brief Route new log message with source info to centralized ILogger * @param severity Level of log report severity * @param file Source file name from __FILE__ macro * @param linenum Source line number from __LINE__ macro * @param format Standard printf-style format string */ template <typename CharType> inline void reportSource(Level severity, const char* file, unsigned linenum, const CharType* format, ...) { va_list ap; va_start(ap, format); reportSource(severity, file, linenum, format, ap); va_end(ap); } template <typename CharType> inline void reportSource(Level severity, const char* file, unsigned linenum, const CharType* format, va_list ap) { for (auto& logger : MainLoggers) logger->reportSource(m_modName, severity, file, linenum, format, ap); if (severity == FatalError) #if LOG_VISOR_EXCEPTIONS throw FatalException(format, ap); #else abort(); #endif else if (severity == Error) ++ErrorCount; } }; } #endif // __LOG_VISOR_HPP__ <commit_msg>Removed exceptions completely<commit_after>#ifndef __LOG_VISOR_HPP__ #define __LOG_VISOR_HPP__ #include <stdarg.h> #include <string.h> #include <stdio.h> #include <vector> #include <atomic> #include <memory> namespace LogVisor { #if _WIN32 && UNICODE #define LOG_UCS2 1 #endif /** * @brief Severity level for log messages */ enum Level { Info, /**< Non-error informative message */ Warning, /**< Non-error warning message */ Error, /**< Recoverable error message */ FatalError /**< Non-recoverable error message (throws exception) */ }; /** * @brief Backend interface for receiving app-wide log events */ struct ILogger { virtual ~ILogger() {} virtual void report(const char* modName, Level severity, const char* format, va_list ap)=0; virtual void report(const char* modName, Level severity, const wchar_t* format, va_list ap)=0; virtual void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const char* format, va_list ap)=0; virtual void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const wchar_t* format, va_list ap)=0; }; /** * @brief Assign calling thread a descriptive name * @param name Descriptive thread name */ void RegisterThreadName(const char* name); /** * @brief Centralized logger vector * * All loggers added to this vector will receive reports as they occur */ extern std::vector<std::unique_ptr<ILogger>> MainLoggers; /** * @brief Centralized error counter * * All submodules accumulate this value */ extern std::atomic_size_t ErrorCount; /** * @brief Centralized frame index * * All log events include this as part of their timestamp if non-zero. * The default value is zero, the app is responsible for updating it * within its main loop. */ extern std::atomic_uint_fast64_t FrameIndex; /** * @brief Restore centralized logger vector to default state (silent operation) */ static inline void UnregisterLoggers() {MainLoggers.clear();} /** * @brief Construct and register a real-time console logger singleton * * This will output to stderr on POSIX platforms and spawn a new console window on Windows. * If there's already a registered console logger, this is a no-op. */ void RegisterConsoleLogger(); /** * @brief Construct and register a file logger * @param filepath Path to write the file * * If there's already a file logger registered to the same file, this is a no-op. */ void RegisterFileLogger(const char* filepath); #if LOG_UCS2 /** * @brief Construct and register a file logger (wchar_t version) * @param filepath Path to write the file * * If there's already a file logger registered to the same file, this is a no-op. */ void RegisterFileLogger(const wchar_t* filepath); #endif /** * @brief This is constructed per-subsystem in a locally centralized fashon */ class LogModule { const char* m_modName; public: LogModule(const char* modName) : m_modName(modName) {} /** * @brief Route new log message to centralized ILogger * @param severity Level of log report severity * @param format Standard printf-style format string */ template <typename CharType> inline void report(Level severity, const CharType* format, ...) { va_list ap; va_start(ap, format); report(severity, format, ap); va_end(ap); } template <typename CharType> inline void report(Level severity, const CharType* format, va_list ap) { for (auto& logger : MainLoggers) logger->report(m_modName, severity, format, ap); if (severity == FatalError) abort(); else if (severity == Error) ++ErrorCount; } /** * @brief Route new log message with source info to centralized ILogger * @param severity Level of log report severity * @param file Source file name from __FILE__ macro * @param linenum Source line number from __LINE__ macro * @param format Standard printf-style format string */ template <typename CharType> inline void reportSource(Level severity, const char* file, unsigned linenum, const CharType* format, ...) { va_list ap; va_start(ap, format); reportSource(severity, file, linenum, format, ap); va_end(ap); } template <typename CharType> inline void reportSource(Level severity, const char* file, unsigned linenum, const CharType* format, va_list ap) { for (auto& logger : MainLoggers) logger->reportSource(m_modName, severity, file, linenum, format, ap); if (severity == FatalError) abort(); else if (severity == Error) ++ErrorCount; } }; } #endif // __LOG_VISOR_HPP__ <|endoftext|>
<commit_before>/*$Id$ * * This source file is a part of the Berlin Project. * Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca> * http://www.berlin-consortium.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #ifndef _Plugin_hh #define _Plugin_hh #include <Prague/Sys/DLL.hh> namespace Prague { template <class T> class Plugin : public DLL { public: Plugin(const string &file, const string &loader = "load") : DLL(file) { typedef T *(* DL) (); DL dl = (DL) resolve(loader); t = dl ? (T *) dl() : 0; } ~Dynamic() { delete t;} T *operator () { return t;} private: T *t; }; #define dload(T) extern "C" T *load() { return new T;} }; #endif /* _Plugin_hh */ <commit_msg><commit_after>/*$Id$ * * This source file is a part of the Berlin Project. * Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca> * http://www.berlin-consortium.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #ifndef _Plugin_hh #define _Plugin_hh #include <Prague/Sys/DLL.hh> namespace Prague { template <class T> class Plugin : public DLL { public: Plugin(const string &file, const string &loader = "load") : DLL(file) { typedef T *(* DL) (); DL dl = (DL) resolve(loader); t = dl ? (T *) dl() : 0; } ~Plugin() { delete t; } T * operator () () { return t; } protected: private: T *t; }; #define dload(T) extern "C" T *load() { return new T;} }; #endif /* _Plugin_hh */ <|endoftext|>
<commit_before>/* Copyright 2019 Axel Huebl, Benjamin Worpitz, Erik Zenker * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <alpaka/vec/Vec.hpp> #include <alpaka/core/Common.hpp> #include <alpaka/core/Unused.hpp> #include <type_traits> namespace alpaka { namespace idx { namespace detail { //############################################################################# //! Maps a linear index to a N dimensional index. template< std::size_t TidxDimOut, std::size_t TidxDimIn, typename TSfinae = void> struct MapIdx; //############################################################################# //! Maps a N dimensional index to the same N dimensional index. template< std::size_t TidxDim> struct MapIdx< TidxDim, TidxDim> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A N dimensional vector. ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( vec::Vec<dim::DimInt<TidxDim>, TElem> const & idx, vec::Vec<dim::DimInt<TidxDim>, TElem> const & extent) -> vec::Vec<dim::DimInt<TidxDim>, TElem> { alpaka::ignore_unused(extent); return idx; } }; //############################################################################# //! Maps a 1 dimensional index to a N dimensional index. template< std::size_t TidxDimOut> struct MapIdx< TidxDimOut, 1u, std::enable_if_t<TidxDimOut != 1u>> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to // \return A N dimensional vector. ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( vec::Vec<dim::DimInt<1u>, TElem> const & idx, vec::Vec<dim::DimInt<TidxDimOut>, TElem> const & extent) -> vec::Vec<dim::DimInt<TidxDimOut>, TElem> { auto idxNd(vec::Vec<dim::DimInt<TidxDimOut>, TElem>::all(0u)); constexpr std::size_t lastIdx(TidxDimOut - 1u); // fast-dim idxNd[lastIdx] = static_cast<TElem>(idx[0u] % extent[lastIdx]); // in-between TElem hyperPlanesBefore = extent[lastIdx]; for(std::size_t r(1u); r < lastIdx; ++r) { std::size_t const d = lastIdx - r; idxNd[d] = static_cast<TElem>(idx[0u] / hyperPlanesBefore % extent[d]); hyperPlanesBefore *= extent[d]; } // slow-dim idxNd[0u] = static_cast<TElem>(idx[0u] / hyperPlanesBefore); return idxNd; } }; //############################################################################# //! Maps a N dimensional index to a 1 dimensional index. template< std::size_t TidxDimIn> struct MapIdx< 1u, TidxDimIn, std::enable_if_t<TidxDimIn != 1u>> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 1 dimensional vector. ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx, vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & extent) -> vec::Vec<dim::DimInt<1u>, TElem> { TElem idx1d(idx[0u]); for(std::size_t d(1u); d < TidxDimIn; ++d) { idx1d = static_cast<TElem>(idx1d * extent[d] + idx[d]); } return {idx1d}; } }; } //############################################################################# //! Maps a N dimensional index to a N dimensional position. //! //! \tparam TidxDimOut Dimension of the index vector to map to. //! \tparam TidxDimIn Dimension of the index vector to map from. //! \tparam TElem Type of the elements of the index vector to map from. ALPAKA_NO_HOST_ACC_WARNING template< std::size_t TidxDimOut, std::size_t TidxDimIn, typename TElem> ALPAKA_FN_HOST_ACC auto mapIdx( vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx, vec::Vec<dim::DimInt<(TidxDimOut < TidxDimIn) ? TidxDimIn : TidxDimOut>, TElem> const & extent) -> vec::Vec<dim::DimInt<TidxDimOut>, TElem> { static_assert(TidxDimOut > 0u, "The dimension of the output vector has to be greater than zero!"); static_assert(TidxDimIn > 0u, "The dimension of the input vector has to be greater than zero!"); return detail::MapIdx< TidxDimOut, TidxDimIn> ::mapIdx( idx, extent); } } } <commit_msg>Add MapIdxPitch<commit_after>/* Copyright 2019 Axel Huebl, Benjamin Worpitz, Erik Zenker * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <alpaka/vec/Vec.hpp> #include <alpaka/core/Common.hpp> #include <alpaka/core/Unused.hpp> #include <type_traits> namespace alpaka { namespace idx { namespace detail { //############################################################################# //! Maps a linear index to a N dimensional index. template< std::size_t TidxDimOut, std::size_t TidxDimIn, typename TSfinae = void> struct MapIdx; //############################################################################# //! Maps a N dimensional index to the same N dimensional index. template< std::size_t TidxDim> struct MapIdx< TidxDim, TidxDim> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A N dimensional vector. ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( vec::Vec<dim::DimInt<TidxDim>, TElem> const & idx, vec::Vec<dim::DimInt<TidxDim>, TElem> const & extent) -> vec::Vec<dim::DimInt<TidxDim>, TElem> { alpaka::ignore_unused(extent); return idx; } }; //############################################################################# //! Maps a 1 dimensional index to a N dimensional index. template< std::size_t TidxDimOut> struct MapIdx< TidxDimOut, 1u, std::enable_if_t<TidxDimOut != 1u>> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to // \return A N dimensional vector. ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( vec::Vec<dim::DimInt<1u>, TElem> const & idx, vec::Vec<dim::DimInt<TidxDimOut>, TElem> const & extent) -> vec::Vec<dim::DimInt<TidxDimOut>, TElem> { auto idxNd(vec::Vec<dim::DimInt<TidxDimOut>, TElem>::all(0u)); constexpr std::size_t lastIdx(TidxDimOut - 1u); // fast-dim idxNd[lastIdx] = static_cast<TElem>(idx[0u] % extent[lastIdx]); // in-between TElem hyperPlanesBefore = extent[lastIdx]; for(std::size_t r(1u); r < lastIdx; ++r) { std::size_t const d = lastIdx - r; idxNd[d] = static_cast<TElem>(idx[0u] / hyperPlanesBefore % extent[d]); hyperPlanesBefore *= extent[d]; } // slow-dim idxNd[0u] = static_cast<TElem>(idx[0u] / hyperPlanesBefore); return idxNd; } }; //############################################################################# //! Maps a N dimensional index to a 1 dimensional index. template< std::size_t TidxDimIn> struct MapIdx< 1u, TidxDimIn, std::enable_if_t<TidxDimIn != 1u>> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 1 dimensional vector. ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx, vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & extent) -> vec::Vec<dim::DimInt<1u>, TElem> { TElem idx1d(idx[0u]); for(std::size_t d(1u); d < TidxDimIn; ++d) { idx1d = static_cast<TElem>(idx1d * extent[d] + idx[d]); } return {idx1d}; } }; } //############################################################################# //! Maps a N dimensional index to a N dimensional position. //! //! \tparam TidxDimOut Dimension of the index vector to map to. //! \tparam TidxDimIn Dimension of the index vector to map from. //! \tparam TElem Type of the elements of the index vector to map from. ALPAKA_NO_HOST_ACC_WARNING template< std::size_t TidxDimOut, std::size_t TidxDimIn, typename TElem> ALPAKA_FN_HOST_ACC auto mapIdx( vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx, vec::Vec<dim::DimInt<(TidxDimOut < TidxDimIn) ? TidxDimIn : TidxDimOut>, TElem> const & extent) -> vec::Vec<dim::DimInt<TidxDimOut>, TElem> { static_assert(TidxDimOut > 0u, "The dimension of the output vector has to be greater than zero!"); static_assert(TidxDimIn > 0u, "The dimension of the input vector has to be greater than zero!"); return detail::MapIdx< TidxDimOut, TidxDimIn> ::mapIdx( idx, extent); } namespace detail { //############################################################################# //! Maps a linear index to a N dimensional index. template< std::size_t TidxDimOut, std::size_t TidxDimIn, typename TSfinae = void> struct MapIdxPitch; //############################################################################# //! Maps a N dimensional index to the same N dimensional index. template< std::size_t TidxDim> struct MapIdxPitch< TidxDim, TidxDim> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param pitch Spatial pitch (in elems) to map the index to // \return A N dimensional vector. ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdxPitch( vec::Vec<dim::DimInt<TidxDim>, TElem> const & idx, vec::Vec<dim::DimInt<TidxDim>, TElem> const & pitch) -> vec::Vec<dim::DimInt<TidxDim>, TElem> { alpaka::ignore_unused(pitch); return idx; } }; //############################################################################# //! Maps a 1 dimensional index to a N dimensional index. template< std::size_t TidxDimOut> struct MapIdxPitch< TidxDimOut, 1u, typename std::enable_if<TidxDimOut != 1u>::type> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param pitch Spatial pitch (in elems) to map the index to // \return A N dimensional vector. ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdxPitch( vec::Vec<dim::DimInt<1u>, TElem> const & idx, vec::Vec<dim::DimInt<TidxDimOut>, TElem> const & pitch) -> vec::Vec<dim::DimInt<TidxDimOut>, TElem> { auto idxNd(vec::Vec<dim::DimInt<TidxDimOut>, TElem>::all(0u)); constexpr std::size_t lastIdx(TidxDimOut - 1u); TElem tmp = idx[0u]; for(std::size_t d(0u); d < lastIdx; ++d) { idxNd[d] = static_cast<TElem>(tmp / pitch[d+1]); tmp %= pitch[d+1]; } idxNd[lastIdx] = tmp; return idxNd; } }; //############################################################################# //! Maps a N dimensional index to a 1 dimensional index. template< std::size_t TidxDimIn> struct MapIdxPitch< 1u, TidxDimIn, typename std::enable_if<TidxDimIn != 1u>::type> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param pitch Spatial pitch (in elems) to map the index to // \return A 1 dimensional vector. ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdxPitch( vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx, vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & pitch) -> vec::Vec<dim::DimInt<1u>, TElem> { constexpr auto lastDim = TidxDimIn - 1; TElem idx1d(idx[lastDim]); for(std::size_t d(0u); d < lastDim; ++d) { idx1d = static_cast<TElem>(idx1d + pitch[d+1] * idx[d]); } return {idx1d}; } }; } //############################################################################# //! Maps a N dimensional index to a N dimensional position. //! //! \tparam TidxDimOut Dimension of the index vector to map to. //! \tparam TidxDimIn Dimension of the index vector to map from. //! \tparam TElem Type of the elements of the index vector to map from. ALPAKA_NO_HOST_ACC_WARNING template< std::size_t TidxDimOut, std::size_t TidxDimIn, typename TElem> ALPAKA_FN_HOST_ACC auto mapIdxPitch( vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx, vec::Vec<dim::DimInt<(TidxDimOut < TidxDimIn) ? TidxDimIn : TidxDimOut>, TElem> const & pitch) -> vec::Vec<dim::DimInt<TidxDimOut>, TElem> { static_assert(TidxDimOut > 0u, "The dimension of the output vector has to be greater than zero!"); static_assert(TidxDimIn > 0u, "The dimension of the input vector has to be greater than zero!"); return detail::MapIdxPitch< TidxDimOut, TidxDimIn> ::mapIdxPitch( idx, pitch); } } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "CppUnitTest.h" #include "..\ProjectEuler\Problem1.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace ProjectEulerTests { TEST_CLASS(Problem1Tests) { public: TEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(0); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(1); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(2); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(3); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input4_Returns3) { auto result = Problem1::SumMultiplesOf3And5Below(4); Assert::AreEqual(3, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input5_Returns3) { auto result = Problem1::SumMultiplesOf3And5Below(5); Assert::AreEqual(3, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input6_Returns8) { auto result = Problem1::SumMultiplesOf3And5Below(6); Assert::AreEqual(8, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input7_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(7); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input8_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(8); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input9_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(9); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input10_Returns23) { auto result = Problem1::SumMultiplesOf3And5Below(10); Assert::AreEqual(23, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input100_Returns2318) { auto result = Problem1::SumMultiplesOf3And5Below(100); Assert::AreEqual(2318, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input1000_Returns233168) { auto result = Problem1::SumMultiplesOf3And5Below(1000); Assert::AreEqual(233168, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input10000_Returns23331668) { auto result = Problem1::SumMultiplesOf3And5Below(10000); Assert::AreEqual(23331668, result); } TEST_METHOD(SumBelow_Input0_Returns0) { auto result = Problem1::SumBelow(0); Assert::AreEqual(0L, result); } TEST_METHOD(SumBelow_Input1_Returns0) { auto result = Problem1::SumBelow(1); Assert::AreEqual(0L, result); } }; }<commit_msg>red-commit - SumBelow_Input2_Returns1<commit_after>#include "stdafx.h" #include "CppUnitTest.h" #include "..\ProjectEuler\Problem1.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace ProjectEulerTests { TEST_CLASS(Problem1Tests) { public: TEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(0); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(1); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(2); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(3); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input4_Returns3) { auto result = Problem1::SumMultiplesOf3And5Below(4); Assert::AreEqual(3, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input5_Returns3) { auto result = Problem1::SumMultiplesOf3And5Below(5); Assert::AreEqual(3, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input6_Returns8) { auto result = Problem1::SumMultiplesOf3And5Below(6); Assert::AreEqual(8, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input7_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(7); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input8_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(8); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input9_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(9); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input10_Returns23) { auto result = Problem1::SumMultiplesOf3And5Below(10); Assert::AreEqual(23, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input100_Returns2318) { auto result = Problem1::SumMultiplesOf3And5Below(100); Assert::AreEqual(2318, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input1000_Returns233168) { auto result = Problem1::SumMultiplesOf3And5Below(1000); Assert::AreEqual(233168, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input10000_Returns23331668) { auto result = Problem1::SumMultiplesOf3And5Below(10000); Assert::AreEqual(23331668, result); } TEST_METHOD(SumBelow_Input0_Returns0) { auto result = Problem1::SumBelow(0); Assert::AreEqual(0L, result); } TEST_METHOD(SumBelow_Input1_Returns0) { auto result = Problem1::SumBelow(1); Assert::AreEqual(0L, result); } TEST_METHOD(SumBelow_Input2_Returns1) { auto result = Problem1::SumBelow(2); Assert::AreEqual(1L, result); } }; }<|endoftext|>
<commit_before><commit_msg>cid#1169841 Big parameter passed by value<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/ui/ui_test.h" #include "base/command_line.h" #include "base/file_util.h" #include "net/base/net_util.h" typedef UITest ChromeMainTest; // Launch the app, then close the app. TEST_F(ChromeMainTest, AppLaunch) { // If we make it here at all, we've succeeded in retrieving the app window // in UITest::SetUp()--otherwise we'd fail with an exception in SetUp(). if (UITest::in_process_renderer()) { EXPECT_EQ(1, UITest::GetBrowserProcessCount()); } else { #if defined(OS_CHROMEOS) // On Linux we'll have five processes: browser, renderer, app launcher, // zygote and sandbox helper. EXPECT_EQ(5, UITest::GetBrowserProcessCount()); #elif defined(OS_LINUX) // On Linux we'll have four processes: browser, renderer, zygote and // sandbox helper. EXPECT_EQ(4, UITest::GetBrowserProcessCount()); #else // We should have two instances of the browser process alive - // one is the Browser and the other is the Renderer. EXPECT_EQ(2, UITest::GetBrowserProcessCount()); #endif } } // Make sure that the testing interface is there and giving reasonable answers. TEST_F(ChromeMainTest, AppTestingInterface) { int window_count = 0; EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(1, window_count); EXPECT_EQ(1, GetTabCount()); } // Make sure that the second invocation creates a new window. TEST_F(ChromeMainTest, SecondLaunch) { include_testing_id_ = false; use_existing_browser_ = true; ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed( CommandLine(CommandLine::ARGUMENTS_ONLY))); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, action_timeout_ms())); } TEST_F(ChromeMainTest, ReuseBrowserInstanceWhenOpeningFile) { include_testing_id_ = false; use_existing_browser_ = true; FilePath test_file = test_data_directory_.AppendASCII("empty.html"); CommandLine command_line(CommandLine::ARGUMENTS_ONLY); command_line.AppendLooseValue(test_file.ToWStringHack()); ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(command_line)); ASSERT_TRUE(automation()->IsURLDisplayed(net::FilePathToFileURL(test_file))); } <commit_msg>Fixing a comment.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/ui/ui_test.h" #include "base/command_line.h" #include "base/file_util.h" #include "net/base/net_util.h" typedef UITest ChromeMainTest; // Launch the app, then close the app. TEST_F(ChromeMainTest, AppLaunch) { // If we make it here at all, we've succeeded in retrieving the app window // in UITest::SetUp()--otherwise we'd fail with an exception in SetUp(). if (UITest::in_process_renderer()) { EXPECT_EQ(1, UITest::GetBrowserProcessCount()); } else { #if defined(OS_CHROMEOS) // On Chromeos we'll have five processes: browser, renderer, app launcher, // zygote and sandbox helper. EXPECT_EQ(5, UITest::GetBrowserProcessCount()); #elif defined(OS_LINUX) // On Linux we'll have four processes: browser, renderer, zygote and // sandbox helper. EXPECT_EQ(4, UITest::GetBrowserProcessCount()); #else // We should have two instances of the browser process alive - // one is the Browser and the other is the Renderer. EXPECT_EQ(2, UITest::GetBrowserProcessCount()); #endif } } // Make sure that the testing interface is there and giving reasonable answers. TEST_F(ChromeMainTest, AppTestingInterface) { int window_count = 0; EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(1, window_count); EXPECT_EQ(1, GetTabCount()); } // Make sure that the second invocation creates a new window. TEST_F(ChromeMainTest, SecondLaunch) { include_testing_id_ = false; use_existing_browser_ = true; ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed( CommandLine(CommandLine::ARGUMENTS_ONLY))); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, action_timeout_ms())); } TEST_F(ChromeMainTest, ReuseBrowserInstanceWhenOpeningFile) { include_testing_id_ = false; use_existing_browser_ = true; FilePath test_file = test_data_directory_.AppendASCII("empty.html"); CommandLine command_line(CommandLine::ARGUMENTS_ONLY); command_line.AppendLooseValue(test_file.ToWStringHack()); ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(command_line)); ASSERT_TRUE(automation()->IsURLDisplayed(net::FilePathToFileURL(test_file))); } <|endoftext|>
<commit_before>#include "lm/trie_sort.hh" #include "lm/config.hh" #include "lm/lm_exception.hh" #include "lm/read_arpa.hh" #include "lm/vocab.hh" #include "lm/weights.hh" #include "lm/word_index.hh" #include "util/file_piece.hh" #include "util/mmap.hh" #include "util/proxy_iterator.hh" #include "util/sized_iterator.hh" #include <algorithm> #include <cstring> #include <cstdio> #include <cstdlib> #include <deque> #include <limits> #include <vector> namespace lm { namespace ngram { namespace trie { void WriteOrThrow(FILE *to, const void *data, size_t size) { assert(size); if (1 != std::fwrite(data, size, 1, to)) UTIL_THROW(util::ErrnoException, "Short write; requested size " << size); } namespace { typedef util::SizedIterator NGramIter; // Proxy for an entry except there is some extra cruft between the entries. This is used to sort (n-1)-grams using the same memory as the sorted n-grams. class PartialViewProxy { public: PartialViewProxy() : attention_size_(0), inner_() {} PartialViewProxy(void *ptr, std::size_t block_size, std::size_t attention_size) : attention_size_(attention_size), inner_(ptr, block_size) {} operator std::string() const { return std::string(reinterpret_cast<const char*>(inner_.Data()), attention_size_); } PartialViewProxy &operator=(const PartialViewProxy &from) { memcpy(inner_.Data(), from.inner_.Data(), attention_size_); return *this; } PartialViewProxy &operator=(const std::string &from) { memcpy(inner_.Data(), from.data(), attention_size_); return *this; } const void *Data() const { return inner_.Data(); } void *Data() { return inner_.Data(); } private: friend class util::ProxyIterator<PartialViewProxy>; typedef std::string value_type; const std::size_t attention_size_; typedef util::SizedInnerIterator InnerIterator; InnerIterator &Inner() { return inner_; } const InnerIterator &Inner() const { return inner_; } InnerIterator inner_; }; typedef util::ProxyIterator<PartialViewProxy> PartialIter; FILE *DiskFlush(const void *mem_begin, const void *mem_end, const util::TempMaker &maker) { util::scoped_fd file(maker.Make()); util::WriteOrThrow(file.get(), mem_begin, (uint8_t*)mem_end - (uint8_t*)mem_begin); return util::FDOpenOrThrow(file); } FILE *WriteContextFile(uint8_t *begin, uint8_t *end, const util::TempMaker &maker, std::size_t entry_size, unsigned char order) { const size_t context_size = sizeof(WordIndex) * (order - 1); // Sort just the contexts using the same memory. PartialIter context_begin(PartialViewProxy(begin + sizeof(WordIndex), entry_size, context_size)); PartialIter context_end(PartialViewProxy(end + sizeof(WordIndex), entry_size, context_size)); #if defined(_WIN32) || defined(_WIN64) std::stable_sort #else std::sort #endif (context_begin, context_end, util::SizedCompare<EntryCompare, PartialViewProxy>(EntryCompare(order - 1))); util::scoped_FILE out(maker.MakeFile()); // Write out to file and uniqueify at the same time. Could have used unique_copy if there was an appropriate OutputIterator. if (context_begin == context_end) return out.release(); PartialIter i(context_begin); WriteOrThrow(out.get(), i->Data(), context_size); const void *previous = i->Data(); ++i; for (; i != context_end; ++i) { if (memcmp(previous, i->Data(), context_size)) { WriteOrThrow(out.get(), i->Data(), context_size); previous = i->Data(); } } return out.release(); } struct ThrowCombine { void operator()(std::size_t /*entry_size*/, const void * /*first*/, const void * /*second*/, FILE * /*out*/) const { UTIL_THROW(FormatLoadException, "Duplicate n-gram detected."); } }; // Useful for context files that just contain records with no value. struct FirstCombine { void operator()(std::size_t entry_size, const void *first, const void * /*second*/, FILE *out) const { WriteOrThrow(out, first, entry_size); } }; template <class Combine> FILE *MergeSortedFiles(FILE *first_file, FILE *second_file, const util::TempMaker &maker, std::size_t weights_size, unsigned char order, const Combine &combine) { std::size_t entry_size = sizeof(WordIndex) * order + weights_size; RecordReader first, second; first.Init(first_file, entry_size); second.Init(second_file, entry_size); util::scoped_FILE out_file(maker.MakeFile()); EntryCompare less(order); while (first && second) { if (less(first.Data(), second.Data())) { WriteOrThrow(out_file.get(), first.Data(), entry_size); ++first; } else if (less(second.Data(), first.Data())) { WriteOrThrow(out_file.get(), second.Data(), entry_size); ++second; } else { combine(entry_size, first.Data(), second.Data(), out_file.get()); ++first; ++second; } } for (RecordReader &remains = (first ? first : second); remains; ++remains) { WriteOrThrow(out_file.get(), remains.Data(), entry_size); } return out_file.release(); } } // namespace void RecordReader::Init(FILE *file, std::size_t entry_size) { rewind(file); file_ = file; data_.reset(malloc(entry_size)); UTIL_THROW_IF(!data_.get(), util::ErrnoException, "Failed to malloc read buffer"); remains_ = true; entry_size_ = entry_size; ++*this; } void RecordReader::Overwrite(const void *start, std::size_t amount) { long internal = (uint8_t*)start - (uint8_t*)data_.get(); UTIL_THROW_IF(fseek(file_, internal - entry_size_, SEEK_CUR), util::ErrnoException, "Couldn't seek backwards for revision"); WriteOrThrow(file_, start, amount); long forward = entry_size_ - internal - amount; #if !defined(_WIN32) && !defined(_WIN64) if (forward) #endif UTIL_THROW_IF(fseek(file_, forward, SEEK_CUR), util::ErrnoException, "Couldn't seek forwards past revision"); } void RecordReader::Rewind() { rewind(file_); remains_ = true; ++*this; } SortedFiles::SortedFiles(const Config &config, util::FilePiece &f, std::vector<uint64_t> &counts, size_t buffer, const std::string &file_prefix, SortedVocabulary &vocab) { util::TempMaker maker(file_prefix); PositiveProbWarn warn(config.positive_log_probability); unigram_.reset(maker.Make()); { // In case <unk> appears. size_t size_out = (counts[0] + 1) * sizeof(ProbBackoff); util::scoped_mmap unigram_mmap(util::MapZeroedWrite(unigram_.get(), size_out), size_out); Read1Grams(f, counts[0], vocab, reinterpret_cast<ProbBackoff*>(unigram_mmap.get()), warn); CheckSpecials(config, vocab); if (!vocab.SawUnk()) ++counts[0]; } // Only use as much buffer as we need. size_t buffer_use = 0; for (unsigned int order = 2; order < counts.size(); ++order) { buffer_use = std::max<size_t>(buffer_use, static_cast<size_t>((sizeof(WordIndex) * order + 2 * sizeof(float)) * counts[order - 1])); } buffer_use = std::max<size_t>(buffer_use, static_cast<size_t>((sizeof(WordIndex) * counts.size() + sizeof(float)) * counts.back())); buffer = std::min<size_t>(buffer, buffer_use); util::scoped_malloc mem; mem.reset(malloc(buffer)); if (!mem.get()) UTIL_THROW(util::ErrnoException, "malloc failed for sort buffer size " << buffer); for (unsigned char order = 2; order <= counts.size(); ++order) { ConvertToSorted(f, vocab, counts, maker, order, warn, mem.get(), buffer); } ReadEnd(f); } namespace { class Closer { public: explicit Closer(std::deque<FILE*> &files) : files_(files) {} ~Closer() { for (std::deque<FILE*>::iterator i = files_.begin(); i != files_.end(); ++i) { util::scoped_FILE deleter(*i); } } void PopFront() { util::scoped_FILE deleter(files_.front()); files_.pop_front(); } private: std::deque<FILE*> &files_; }; } // namespace void SortedFiles::ConvertToSorted(util::FilePiece &f, const SortedVocabulary &vocab, const std::vector<uint64_t> &counts, const util::TempMaker &maker, unsigned char order, PositiveProbWarn &warn, void *mem, std::size_t mem_size) { ReadNGramHeader(f, order); const size_t count = counts[order - 1]; // Size of weights. Does it include backoff? const size_t words_size = sizeof(WordIndex) * order; const size_t weights_size = sizeof(float) + ((order == counts.size()) ? 0 : sizeof(float)); const size_t entry_size = words_size + weights_size; const size_t batch_size = std::min(count, mem_size / entry_size); uint8_t *const begin = reinterpret_cast<uint8_t*>(mem); std::deque<FILE*> files, contexts; Closer files_closer(files), contexts_closer(contexts); for (std::size_t batch = 0, done = 0; done < count; ++batch) { uint8_t *out = begin; uint8_t *out_end = out + std::min(count - done, batch_size) * entry_size; if (order == counts.size()) { for (; out != out_end; out += entry_size) { ReadNGram(f, order, vocab, reinterpret_cast<WordIndex*>(out), *reinterpret_cast<Prob*>(out + words_size), warn); } } else { for (; out != out_end; out += entry_size) { ReadNGram(f, order, vocab, reinterpret_cast<WordIndex*>(out), *reinterpret_cast<ProbBackoff*>(out + words_size), warn); } } // Sort full records by full n-gram. util::SizedProxy proxy_begin(begin, entry_size), proxy_end(out_end, entry_size); // parallel_sort uses too much RAM. TODO: figure out why windows sort doesn't like my proxies. #if defined(_WIN32) || defined(_WIN64) std::stable_sort #else std::sort #endif (NGramIter(proxy_begin), NGramIter(proxy_end), util::SizedCompare<EntryCompare>(EntryCompare(order))); files.push_back(DiskFlush(begin, out_end, maker)); contexts.push_back(WriteContextFile(begin, out_end, maker, entry_size, order)); done += (out_end - begin) / entry_size; } // All individual files created. Merge them. while (files.size() > 1) { files.push_back(MergeSortedFiles(files[0], files[1], maker, weights_size, order, ThrowCombine())); files_closer.PopFront(); files_closer.PopFront(); contexts.push_back(MergeSortedFiles(contexts[0], contexts[1], maker, 0, order - 1, FirstCombine())); contexts_closer.PopFront(); contexts_closer.PopFront(); } if (!files.empty()) { // Steal from closers. full_[order - 2].reset(files.front()); files.pop_front(); context_[order - 2].reset(contexts.front()); contexts.pop_front(); } } } // namespace trie } // namespace ngram } // namespace lm <commit_msg>Don't segfault trie building when there is no n-gram of a given order. Jon Clark.<commit_after>#include "lm/trie_sort.hh" #include "lm/config.hh" #include "lm/lm_exception.hh" #include "lm/read_arpa.hh" #include "lm/vocab.hh" #include "lm/weights.hh" #include "lm/word_index.hh" #include "util/file_piece.hh" #include "util/mmap.hh" #include "util/proxy_iterator.hh" #include "util/sized_iterator.hh" #include <algorithm> #include <cstring> #include <cstdio> #include <cstdlib> #include <deque> #include <limits> #include <vector> namespace lm { namespace ngram { namespace trie { void WriteOrThrow(FILE *to, const void *data, size_t size) { assert(size); if (1 != std::fwrite(data, size, 1, to)) UTIL_THROW(util::ErrnoException, "Short write; requested size " << size); } namespace { typedef util::SizedIterator NGramIter; // Proxy for an entry except there is some extra cruft between the entries. This is used to sort (n-1)-grams using the same memory as the sorted n-grams. class PartialViewProxy { public: PartialViewProxy() : attention_size_(0), inner_() {} PartialViewProxy(void *ptr, std::size_t block_size, std::size_t attention_size) : attention_size_(attention_size), inner_(ptr, block_size) {} operator std::string() const { return std::string(reinterpret_cast<const char*>(inner_.Data()), attention_size_); } PartialViewProxy &operator=(const PartialViewProxy &from) { memcpy(inner_.Data(), from.inner_.Data(), attention_size_); return *this; } PartialViewProxy &operator=(const std::string &from) { memcpy(inner_.Data(), from.data(), attention_size_); return *this; } const void *Data() const { return inner_.Data(); } void *Data() { return inner_.Data(); } private: friend class util::ProxyIterator<PartialViewProxy>; typedef std::string value_type; const std::size_t attention_size_; typedef util::SizedInnerIterator InnerIterator; InnerIterator &Inner() { return inner_; } const InnerIterator &Inner() const { return inner_; } InnerIterator inner_; }; typedef util::ProxyIterator<PartialViewProxy> PartialIter; FILE *DiskFlush(const void *mem_begin, const void *mem_end, const util::TempMaker &maker) { util::scoped_fd file(maker.Make()); util::WriteOrThrow(file.get(), mem_begin, (uint8_t*)mem_end - (uint8_t*)mem_begin); return util::FDOpenOrThrow(file); } FILE *WriteContextFile(uint8_t *begin, uint8_t *end, const util::TempMaker &maker, std::size_t entry_size, unsigned char order) { const size_t context_size = sizeof(WordIndex) * (order - 1); // Sort just the contexts using the same memory. PartialIter context_begin(PartialViewProxy(begin + sizeof(WordIndex), entry_size, context_size)); PartialIter context_end(PartialViewProxy(end + sizeof(WordIndex), entry_size, context_size)); #if defined(_WIN32) || defined(_WIN64) std::stable_sort #else std::sort #endif (context_begin, context_end, util::SizedCompare<EntryCompare, PartialViewProxy>(EntryCompare(order - 1))); util::scoped_FILE out(maker.MakeFile()); // Write out to file and uniqueify at the same time. Could have used unique_copy if there was an appropriate OutputIterator. if (context_begin == context_end) return out.release(); PartialIter i(context_begin); WriteOrThrow(out.get(), i->Data(), context_size); const void *previous = i->Data(); ++i; for (; i != context_end; ++i) { if (memcmp(previous, i->Data(), context_size)) { WriteOrThrow(out.get(), i->Data(), context_size); previous = i->Data(); } } return out.release(); } struct ThrowCombine { void operator()(std::size_t /*entry_size*/, const void * /*first*/, const void * /*second*/, FILE * /*out*/) const { UTIL_THROW(FormatLoadException, "Duplicate n-gram detected."); } }; // Useful for context files that just contain records with no value. struct FirstCombine { void operator()(std::size_t entry_size, const void *first, const void * /*second*/, FILE *out) const { WriteOrThrow(out, first, entry_size); } }; template <class Combine> FILE *MergeSortedFiles(FILE *first_file, FILE *second_file, const util::TempMaker &maker, std::size_t weights_size, unsigned char order, const Combine &combine) { std::size_t entry_size = sizeof(WordIndex) * order + weights_size; RecordReader first, second; first.Init(first_file, entry_size); second.Init(second_file, entry_size); util::scoped_FILE out_file(maker.MakeFile()); EntryCompare less(order); while (first && second) { if (less(first.Data(), second.Data())) { WriteOrThrow(out_file.get(), first.Data(), entry_size); ++first; } else if (less(second.Data(), first.Data())) { WriteOrThrow(out_file.get(), second.Data(), entry_size); ++second; } else { combine(entry_size, first.Data(), second.Data(), out_file.get()); ++first; ++second; } } for (RecordReader &remains = (first ? first : second); remains; ++remains) { WriteOrThrow(out_file.get(), remains.Data(), entry_size); } return out_file.release(); } } // namespace void RecordReader::Init(FILE *file, std::size_t entry_size) { entry_size_ = entry_size; data_.reset(malloc(entry_size)); UTIL_THROW_IF(!data_.get(), util::ErrnoException, "Failed to malloc read buffer"); file_ = file; if (file) { rewind(file); remains_ = true; ++*this; } else { remains_ = false; } } void RecordReader::Overwrite(const void *start, std::size_t amount) { long internal = (uint8_t*)start - (uint8_t*)data_.get(); UTIL_THROW_IF(fseek(file_, internal - entry_size_, SEEK_CUR), util::ErrnoException, "Couldn't seek backwards for revision"); WriteOrThrow(file_, start, amount); long forward = entry_size_ - internal - amount; #if !defined(_WIN32) && !defined(_WIN64) if (forward) #endif UTIL_THROW_IF(fseek(file_, forward, SEEK_CUR), util::ErrnoException, "Couldn't seek forwards past revision"); } void RecordReader::Rewind() { if (file_) { rewind(file_); remains_ = true; ++*this; } else { remains_ = false; } } SortedFiles::SortedFiles(const Config &config, util::FilePiece &f, std::vector<uint64_t> &counts, size_t buffer, const std::string &file_prefix, SortedVocabulary &vocab) { util::TempMaker maker(file_prefix); PositiveProbWarn warn(config.positive_log_probability); unigram_.reset(maker.Make()); { // In case <unk> appears. size_t size_out = (counts[0] + 1) * sizeof(ProbBackoff); util::scoped_mmap unigram_mmap(util::MapZeroedWrite(unigram_.get(), size_out), size_out); Read1Grams(f, counts[0], vocab, reinterpret_cast<ProbBackoff*>(unigram_mmap.get()), warn); CheckSpecials(config, vocab); if (!vocab.SawUnk()) ++counts[0]; } // Only use as much buffer as we need. size_t buffer_use = 0; for (unsigned int order = 2; order < counts.size(); ++order) { buffer_use = std::max<size_t>(buffer_use, static_cast<size_t>((sizeof(WordIndex) * order + 2 * sizeof(float)) * counts[order - 1])); } buffer_use = std::max<size_t>(buffer_use, static_cast<size_t>((sizeof(WordIndex) * counts.size() + sizeof(float)) * counts.back())); buffer = std::min<size_t>(buffer, buffer_use); util::scoped_malloc mem; mem.reset(malloc(buffer)); if (!mem.get()) UTIL_THROW(util::ErrnoException, "malloc failed for sort buffer size " << buffer); for (unsigned char order = 2; order <= counts.size(); ++order) { ConvertToSorted(f, vocab, counts, maker, order, warn, mem.get(), buffer); } ReadEnd(f); } namespace { class Closer { public: explicit Closer(std::deque<FILE*> &files) : files_(files) {} ~Closer() { for (std::deque<FILE*>::iterator i = files_.begin(); i != files_.end(); ++i) { util::scoped_FILE deleter(*i); } } void PopFront() { util::scoped_FILE deleter(files_.front()); files_.pop_front(); } private: std::deque<FILE*> &files_; }; } // namespace void SortedFiles::ConvertToSorted(util::FilePiece &f, const SortedVocabulary &vocab, const std::vector<uint64_t> &counts, const util::TempMaker &maker, unsigned char order, PositiveProbWarn &warn, void *mem, std::size_t mem_size) { ReadNGramHeader(f, order); const size_t count = counts[order - 1]; // Size of weights. Does it include backoff? const size_t words_size = sizeof(WordIndex) * order; const size_t weights_size = sizeof(float) + ((order == counts.size()) ? 0 : sizeof(float)); const size_t entry_size = words_size + weights_size; const size_t batch_size = std::min(count, mem_size / entry_size); uint8_t *const begin = reinterpret_cast<uint8_t*>(mem); std::deque<FILE*> files, contexts; Closer files_closer(files), contexts_closer(contexts); for (std::size_t batch = 0, done = 0; done < count; ++batch) { uint8_t *out = begin; uint8_t *out_end = out + std::min(count - done, batch_size) * entry_size; if (order == counts.size()) { for (; out != out_end; out += entry_size) { ReadNGram(f, order, vocab, reinterpret_cast<WordIndex*>(out), *reinterpret_cast<Prob*>(out + words_size), warn); } } else { for (; out != out_end; out += entry_size) { ReadNGram(f, order, vocab, reinterpret_cast<WordIndex*>(out), *reinterpret_cast<ProbBackoff*>(out + words_size), warn); } } // Sort full records by full n-gram. util::SizedProxy proxy_begin(begin, entry_size), proxy_end(out_end, entry_size); // parallel_sort uses too much RAM. TODO: figure out why windows sort doesn't like my proxies. #if defined(_WIN32) || defined(_WIN64) std::stable_sort #else std::sort #endif (NGramIter(proxy_begin), NGramIter(proxy_end), util::SizedCompare<EntryCompare>(EntryCompare(order))); files.push_back(DiskFlush(begin, out_end, maker)); contexts.push_back(WriteContextFile(begin, out_end, maker, entry_size, order)); done += (out_end - begin) / entry_size; } // All individual files created. Merge them. while (files.size() > 1) { files.push_back(MergeSortedFiles(files[0], files[1], maker, weights_size, order, ThrowCombine())); files_closer.PopFront(); files_closer.PopFront(); contexts.push_back(MergeSortedFiles(contexts[0], contexts[1], maker, 0, order - 1, FirstCombine())); contexts_closer.PopFront(); contexts_closer.PopFront(); } if (!files.empty()) { // Steal from closers. full_[order - 2].reset(files.front()); files.pop_front(); context_[order - 2].reset(contexts.front()); contexts.pop_front(); } } } // namespace trie } // namespace ngram } // namespace lm <|endoftext|>
<commit_before><commit_msg>Reenable PosixSessionEnd test.<commit_after><|endoftext|>
<commit_before>/* @Copyright Barrett Adair 2015-2017 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_CLBL_TRTS_ADD_MEMBER_CONST_HPP #define BOOST_CLBL_TRTS_ADD_MEMBER_CONST_HPP #include <boost/callable_traits/detail/core.hpp> namespace boost { namespace callable_traits { //[ add_member_const_hpp /*` [section:ref_add_member_const add_member_const] [heading Header] ``#include <boost/callable_traits/add_member_const.hpp>`` [heading Definition] */ template<typename T> using add_member_const_t = //see below //<- #ifdef BOOST_CLBL_TRTS_DISABLE_ABOMINABLE_FUNCTIONS detail::sfinae_try< typename detail::traits<T>::add_member_const, detail::fail_when_same<typename detail::traits<T>::add_member_const, detail::abominable_functions_not_supported_on_this_compiler, this_compiler_doesnt_support_abominable_function_types>, detail::fail_if_invalid<typename detail::traits<T>::add_member_const, member_qualifiers_are_illegal_for_this_type>>; #else detail::try_but_fail_if_invalid< typename detail::traits<T>::add_member_const, member_qualifiers_are_illegal_for_this_type>; #endif // #ifdef BOOST_CLBL_TRTS_DISABLE_ABOMINABLE_FUNCTIONS namespace detail { template<typename T, typename = std::false_type> struct add_member_const_impl {}; template<typename T> struct add_member_const_impl <T, typename std::is_same< add_member_const_t<T>, detail::dummy>::type> { using type = add_member_const_t<T>; }; } //-> template<typename T> struct add_member_const : detail::add_member_const_impl<T> {}; //<- }} // namespace boost::callable_traits //-> /*` [heading Constraints] * `T` must be a function type or a member function pointer type * If `T` is a pointer, it may not be cv/ref qualified [heading Behavior] * A substitution failure occurs if the constraints are violated. * Adds a member `const` qualifier to `T`, if not already present. [heading Input/Output Examples] [table [[`T`] [`add_member_const_t<T>`]] [[`int()`] [`int() const`]] [[`int(foo::*)()`] [`int(foo::*)() const`]] [[`int(foo::*)() &`] [`int(foo::*)() const &`]] [[`int(foo::*)() &&`] [`int(foo::*)() const &&`]] [[`int(foo::*)() const`] [`int(foo::*)() const`]] [[`int(foo::*)() volatile`] [`int(foo::*)() const volatile`]] [[`int(foo::*)() transaction_safe`] [`int(foo::*)() const transaction_safe`]] [[`int`] [(substitution failure)]] [[`int (&)()`] [(substitution failure)]] [[`int (*)()`] [(substitution failure)]] [[`int foo::*`] [(substitution failure)]] [[`int (foo::* const)()`] [(substitution failure)]] ] [heading Example Program] [import ../example/add_member_const.cpp] [add_member_const] [endsect] */ //] #endif // #ifndef BOOST_CLBL_TRTS_ADD_MEMBER_CONST_HPP <commit_msg>Delete add_member_const.hpp<commit_after><|endoftext|>
<commit_before><commit_msg>start centre: Solid color fits the new artwork better.<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/dreamview/backend/simulation_world/simulation_world_updater.h" #include "google/protobuf/util/json_util.h" #include "modules/dreamview/backend/common/dreamview_gflags.h" #include "modules/map/hdmap/hdmap_util.h" namespace apollo { namespace dreamview { using apollo::common::adapter::AdapterManager; using apollo::common::monitor::MonitorMessageItem; using apollo::common::util::GetProtoFromASCIIFile; using apollo::hdmap::EndWayPointFile; using apollo::routing::RoutingRequest; using google::protobuf::util::MessageToJsonString; using Json = nlohmann::json; SimulationWorldUpdater::SimulationWorldUpdater(WebSocketHandler *websocket, const MapService *map_service, bool routing_from_file) : sim_world_service_(map_service, routing_from_file), map_service_(map_service), websocket_(websocket) { // Initialize default end point LoadDefaultEndPoint(); websocket_->RegisterMessageHandler( "RetrieveMapData", [this](const Json &json, WebSocketHandler::Connection *conn) { auto iter = json.find("elements"); if (iter != json.end()) { MapElementIds map_element_ids(*iter); auto retrieved = map_service_->RetrieveMapElements(map_element_ids); std::string retrieved_json_string; MessageToJsonString(retrieved, &retrieved_json_string); Json response; response["type"] = "MapData"; response["data"] = Json::parse(retrieved_json_string); websocket_->SendData(conn, response.dump()); } }); websocket_->RegisterMessageHandler( "RetrieveMapElementsByRadius", [this](const Json &json, WebSocketHandler::Connection *conn) { auto radius = json.find("radius"); if (radius == json.end()) { AERROR << "Cannot retrieve map elements with unknown radius."; return; } Json response = sim_world_service_.GetMapElements(*radius); response["type"] = "MapElements"; websocket_->SendData(conn, response.dump()); }); websocket_->RegisterMessageHandler( "SendRoutingRequest", [this](const Json &json, WebSocketHandler::Connection *conn) { RoutingRequest routing_request; bool succeed = ConstructRoutingRequest(json, &routing_request); if (succeed) { AdapterManager::FillRoutingRequestHeader(FLAGS_dreamview_module_name, &routing_request); AdapterManager::PublishRoutingRequest(routing_request); } // Publish monitor message. if (succeed) { sim_world_service_.PublishMonitorMessage(MonitorMessageItem::INFO, "Routing Request Sent"); } else { sim_world_service_.PublishMonitorMessage( MonitorMessageItem::ERROR, "Failed to send routing request"); } }); websocket_->RegisterMessageHandler( "RequestSimulationWorld", [this](const Json &json, WebSocketHandler::Connection *conn) { if (!sim_world_service_.ReadyToPush()) { AWARN_EVERY(100) << "Not sending simulation world as the data is not ready!"; return; } std::string to_send; { // Pay the price to copy the data instead of sending data over the // wire while holding the lock. boost::shared_lock<boost::shared_mutex> reader_lock(mutex_); to_send = simulation_world_json_; } websocket_->SendData(conn, to_send, true); }); websocket_->RegisterMessageHandler( "GetDefaultEndPoint", [this](const Json &json, WebSocketHandler::Connection *conn) { Json response; response["type"] = "DefaultEndPoint"; if (LoadDefaultEndPoint()) { response["end_x"] = default_end_point_.pose().x(); response["end_y"] = default_end_point_.pose().y(); } websocket_->SendData(conn, response.dump()); }); } bool SimulationWorldUpdater::ConstructRoutingRequest( const Json &json, RoutingRequest *routing_request) { // Input validations if (json.find("start") == json.end() || json.find("sendDefaultRoute") == json.end()) { AERROR << "Cannot prepare a routing request: input validation failed."; return false; } // set start point auto start = json["start"]; if (start.find("x") == start.end() || start.find("y") == start.end()) { AERROR << "Failed to prepare a routing request: start point not found"; return false; } routing_request->clear_waypoint(); map_service_->ConstructLaneWayPoint(start["x"], start["y"], routing_request->add_waypoint()); // set way point(s) if any auto iter = json.find("waypoint"); if (iter != json.end()) { auto *waypoint = routing_request->mutable_waypoint(); for (size_t i = 0; i < iter->size(); ++i) { auto &point = (*iter)[i]; if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"], waypoint->Add())) { waypoint->RemoveLast(); } } } // set end point auto *endLane = routing_request->add_waypoint(); if (json["sendDefaultRoute"]) { // Try to reload end point if it hasn't been loaded yet. if (!LoadDefaultEndPoint()) { return false; } endLane->set_id(default_end_point_.id()); endLane->set_s(default_end_point_.s()); auto *pose = endLane->mutable_pose(); pose->set_x(default_end_point_.pose().x()); pose->set_y(default_end_point_.pose().y()); } else { if (json.find("end") == json.end()) { AERROR << "Failed to prepare a routing request: end point not found"; return false; } auto end = json["end"]; if (end.find("x") == end.end() || end.find("y") == end.end()) { AERROR << "Failed to prepare a routing request: end point not found"; return false; } map_service_->ConstructLaneWayPoint(end["x"], end["y"], endLane); } AINFO << "Constructed RoutingRequest to be sent, waypoints: " << routing_request->DebugString(); return true; } void SimulationWorldUpdater::Start() { // start ROS timer, one-shot = false, auto-start = true timer_ = AdapterManager::CreateTimer(ros::Duration(kSimWorldTimeInterval), &SimulationWorldUpdater::OnTimer, this); } void SimulationWorldUpdater::OnTimer(const ros::TimerEvent &event) { sim_world_service_.Update(); { boost::unique_lock<boost::shared_mutex> writer_lock(mutex_); simulation_world_json_ = sim_world_service_.GetUpdateAsJson(FLAGS_map_radius).dump(); } } bool SimulationWorldUpdater::LoadDefaultEndPoint() { bool ret = default_end_point_.has_id() ? true : GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_); if (!ret) { AWARN << "Failed to load default end point from " << EndWayPointFile(); } return ret; } } // namespace dreamview } // namespace apollo <commit_msg>Dreamview: simplify end point (#662)<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/dreamview/backend/simulation_world/simulation_world_updater.h" #include "google/protobuf/util/json_util.h" #include "modules/dreamview/backend/common/dreamview_gflags.h" #include "modules/map/hdmap/hdmap_util.h" namespace apollo { namespace dreamview { using apollo::common::adapter::AdapterManager; using apollo::common::monitor::MonitorMessageItem; using apollo::common::util::GetProtoFromASCIIFile; using apollo::hdmap::EndWayPointFile; using apollo::routing::RoutingRequest; using google::protobuf::util::MessageToJsonString; using Json = nlohmann::json; SimulationWorldUpdater::SimulationWorldUpdater(WebSocketHandler *websocket, const MapService *map_service, bool routing_from_file) : sim_world_service_(map_service, routing_from_file), map_service_(map_service), websocket_(websocket) { // Initialize default end point LoadDefaultEndPoint(); websocket_->RegisterMessageHandler( "RetrieveMapData", [this](const Json &json, WebSocketHandler::Connection *conn) { auto iter = json.find("elements"); if (iter != json.end()) { MapElementIds map_element_ids(*iter); auto retrieved = map_service_->RetrieveMapElements(map_element_ids); std::string retrieved_json_string; MessageToJsonString(retrieved, &retrieved_json_string); Json response; response["type"] = "MapData"; response["data"] = Json::parse(retrieved_json_string); websocket_->SendData(conn, response.dump()); } }); websocket_->RegisterMessageHandler( "RetrieveMapElementsByRadius", [this](const Json &json, WebSocketHandler::Connection *conn) { auto radius = json.find("radius"); if (radius == json.end()) { AERROR << "Cannot retrieve map elements with unknown radius."; return; } Json response = sim_world_service_.GetMapElements(*radius); response["type"] = "MapElements"; websocket_->SendData(conn, response.dump()); }); websocket_->RegisterMessageHandler( "SendRoutingRequest", [this](const Json &json, WebSocketHandler::Connection *conn) { RoutingRequest routing_request; bool succeed = ConstructRoutingRequest(json, &routing_request); if (succeed) { AdapterManager::FillRoutingRequestHeader(FLAGS_dreamview_module_name, &routing_request); AdapterManager::PublishRoutingRequest(routing_request); } // Publish monitor message. if (succeed) { sim_world_service_.PublishMonitorMessage(MonitorMessageItem::INFO, "Routing Request Sent"); } else { sim_world_service_.PublishMonitorMessage( MonitorMessageItem::ERROR, "Failed to send routing request"); } }); websocket_->RegisterMessageHandler( "RequestSimulationWorld", [this](const Json &json, WebSocketHandler::Connection *conn) { if (!sim_world_service_.ReadyToPush()) { AWARN_EVERY(100) << "Not sending simulation world as the data is not ready!"; return; } std::string to_send; { // Pay the price to copy the data instead of sending data over the // wire while holding the lock. boost::shared_lock<boost::shared_mutex> reader_lock(mutex_); to_send = simulation_world_json_; } websocket_->SendData(conn, to_send, true); }); websocket_->RegisterMessageHandler( "GetDefaultEndPoint", [this](const Json &json, WebSocketHandler::Connection *conn) { Json response; response["type"] = "DefaultEndPoint"; if (LoadDefaultEndPoint()) { response["end_x"] = default_end_point_.pose().x(); response["end_y"] = default_end_point_.pose().y(); } websocket_->SendData(conn, response.dump()); }); } bool SimulationWorldUpdater::ConstructRoutingRequest( const Json &json, RoutingRequest *routing_request) { // Input validations if (json.find("start") == json.end() || json.find("sendDefaultRoute") == json.end()) { AERROR << "Cannot prepare a routing request: input validation failed."; return false; } // set start point auto start = json["start"]; if (start.find("x") == start.end() || start.find("y") == start.end()) { AERROR << "Failed to prepare a routing request: start point not found"; return false; } routing_request->clear_waypoint(); map_service_->ConstructLaneWayPoint(start["x"], start["y"], routing_request->add_waypoint()); // set way point(s) if any auto iter = json.find("waypoint"); if (iter != json.end()) { auto *waypoint = routing_request->mutable_waypoint(); for (size_t i = 0; i < iter->size(); ++i) { auto &point = (*iter)[i]; if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"], waypoint->Add())) { waypoint->RemoveLast(); } } } // set end point auto *end_point = routing_request->add_waypoint(); if (json["sendDefaultRoute"]) { // Try to reload end point if it hasn't been loaded yet. if (!LoadDefaultEndPoint()) { return false; } end_point->CopyFrom(default_end_point_); } else { if (json.find("end") == json.end()) { AERROR << "Failed to prepare a routing request: end point not found"; return false; } auto end = json["end"]; if (end.find("x") == end.end() || end.find("y") == end.end()) { AERROR << "Failed to prepare a routing request: end point not found"; return false; } map_service_->ConstructLaneWayPoint(end["x"], end["y"], end_point); } AINFO << "Constructed RoutingRequest to be sent, waypoints: " << routing_request->DebugString(); return true; } void SimulationWorldUpdater::Start() { // start ROS timer, one-shot = false, auto-start = true timer_ = AdapterManager::CreateTimer(ros::Duration(kSimWorldTimeInterval), &SimulationWorldUpdater::OnTimer, this); } void SimulationWorldUpdater::OnTimer(const ros::TimerEvent &event) { sim_world_service_.Update(); { boost::unique_lock<boost::shared_mutex> writer_lock(mutex_); simulation_world_json_ = sim_world_service_.GetUpdateAsJson(FLAGS_map_radius).dump(); } } bool SimulationWorldUpdater::LoadDefaultEndPoint() { bool ret = default_end_point_.has_id() ? true : GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_); if (!ret) { AWARN << "Failed to load default end point from " << EndWayPointFile(); } return ret; } } // namespace dreamview } // namespace apollo <|endoftext|>
<commit_before>/** * (c) Camille Scott, 2019 * File : utagger.hh * License: MIT * Author : Camille Scott <camille.scott.w@gmail.com> * Date : 05.08.2019 */ #ifndef BOINK_UTAGGER_HH #define BOINK_UTAGGER_HH #include <memory> #include <optional> #include "boink/traversal.hh" #include "boink/hashing/kmeriterator.hh" #include "boink/hashing/ukhs.hh" #include "boink/hashing/hash_combine.hh" #include "boink/dbg.hh" #include "boink/cdbg/udbg.hh" #include "boink/storage/storage.hh" namespace boink { namespace cdbg { template <class StorageType> struct UTagger { typedef dBG<StorageType, hashing::UKHS::LazyShifter> dbg_type; typedef typename dbg_type::shifter_type shifter_type; typedef Traverse<dbg_type> traversal_type; typedef typename traversal_type::dBG traverser_type; typedef hashing::KmerIterator<shifter_type> kmer_iter_type; typedef typename shifter_type::hash_type hash_type; typedef typename hashing::UKHS::value_type value_type; typedef typename shifter_type::kmer_type kmer_type; typedef typename shifter_type::shift_type shift_type; typedef TraversalState::State state_type; typedef std::tuple<value_type, value_type> link_type; struct Tag { value_type left_partition; value_type right_partition; link_type link; }; class StreamingTagger : public traverser_type, public events::EventNotifier { public: using traverser_type::filter_nodes; using traverser_type::find_left_kmers; using traverser_type::find_right_kmers; using traverser_type::gather_left; using traverser_type::gather_right; using traverser_type::traverse_left; using traverser_type::traverse_right; using traverser_type::get_decision_neighbors; typedef spp::sparse_hash_map<link_type, Tag, hash_tuple::hash<link_type>> tag_map_t; typedef typename tag_map_t::const_iterator tag_map_iter_t; tag_map_t tag_map; std::shared_ptr<dbg_type> dbg; std::shared_ptr<hashing::UKHS::Map> ukhs; const uint16_t unikmer_k; StreamingTagger(std::shared_ptr<dbg_type> dbg, std::shared_ptr<hashing::UKHS::Map> ukhs) : traverser_type(dbg->K(), ukhs->K(), ukhs), EventNotifier(), dbg(dbg), ukhs(ukhs), unikmer_k(ukhs->K()) { } size_t insert_sequence(const std::string& sequence) { std::deque<hash_type> hashes; auto new_tags = find_new_tags(sequence, hashes); for (const auto& item : new_tags) { tag_map[item.first] = item.second; } return new_tags.size(); } tag_map_t find_new_tags(const std::string& sequence, std::deque<hash_type>& hashes) { kmer_iter_type kmer_iter(sequence, this); std::set<hash_type> new_kmers; std::deque<std::pair<std::vector<shift_type>, std::vector<shift_type>>> neighbors; while(!kmer_iter.done()) { auto hash = kmer_iter.next(); hashes.push_back(hash); if (dbg->insert(hash)) { // If the k-mer is new, track it and gather it's potential // neighbors to save on hashing later new_kmers.insert(hash); neighbors.push_back(std::make_pair(this->gather_left(), this->gather_right())); } } tag_map_t tags; bool first_new = new_kmers.count(hashes.front()), second_new; auto first = hashes.cbegin(); auto second = hashes.cbegin() + 1; while (second != hashes.cend()) { //std::cerr << "----------" << std::endl; //std::cerr << "first: " << *first << ", second: " << *second << std::endl; second_new = new_kmers.count(*second); if (first_new || second_new) { //std::cerr << " checking internal pair." << std::endl; auto tag = create_tag(*first, *second); if (tag) { tags[tag.value().link] = std::move(tag.value()); } } if (first_new) { //std::cerr << " checking neighbors." << std::endl; find_neighborhood_tags(*first, this->filter_nodes(dbg.get(), neighbors.front()), tags); neighbors.pop_front(); } first_new = second_new; ++first; ++second; } if (second_new) { find_neighborhood_tags(hashes.back(), this->filter_nodes(dbg.get(), neighbors.front()), tags); } return tags; } void find_neighborhood_tags(const hash_type& root, const std::pair<std::vector<shift_type>, std::vector<shift_type>>& neighbors, tag_map_t& tags) { // check in-neighbors for (auto& in_neighbor : neighbors.first) { auto tag = create_tag(in_neighbor.hash, root); if (tag) { tags[tag.value().link] = std::move(tag.value()); } } // and out neighbors for (auto& out_neighbor : neighbors.second) { auto tag = create_tag(root, out_neighbor.hash); if (tag) { tags[tag.value().link] = std::move(tag.value()); } } } std::optional<Tag> create_tag(const hash_type& first, const hash_type& second) { if (first.unikmer.partition != second.unikmer.partition) { //std::cerr << "\tunikmers don't match" << std::endl; //std::cerr << "\tfirst: " << first << ", second:" << second << std::endl; Tag tag; tag.left_partition = first.unikmer.partition; tag.right_partition = second.unikmer.partition; tag.link = std::make_pair(first.hash, second.hash); return tag; } else { return {}; } } }; }; } } #endif <commit_msg>Add tag querying<commit_after>/** * (c) Camille Scott, 2019 * File : utagger.hh * License: MIT * Author : Camille Scott <camille.scott.w@gmail.com> * Date : 05.08.2019 */ #ifndef BOINK_UTAGGER_HH #define BOINK_UTAGGER_HH #include <memory> #include <optional> #include "boink/processors.hh" #include "boink/traversal.hh" #include "boink/hashing/kmeriterator.hh" #include "boink/hashing/ukhs.hh" #include "boink/hashing/hash_combine.hh" #include "boink/dbg.hh" #include "boink/cdbg/udbg.hh" #include "boink/storage/storage.hh" namespace boink { namespace cdbg { template <class StorageType> struct UTagger { typedef dBG<StorageType, hashing::UKHS::LazyShifter> dbg_type; typedef typename dbg_type::shifter_type shifter_type; typedef Traverse<dbg_type> traversal_type; typedef typename traversal_type::dBG traverser_type; typedef hashing::KmerIterator<shifter_type> kmer_iter_type; typedef typename shifter_type::hash_type hash_type; typedef typename hashing::UKHS::value_type value_type; typedef typename shifter_type::kmer_type kmer_type; typedef typename shifter_type::shift_type shift_type; typedef TraversalState::State state_type; typedef std::tuple<value_type, value_type> link_type; struct Tag { value_type left_partition; value_type right_partition; link_type link; }; class StreamingTagger : public traverser_type, public events::EventNotifier { public: using traverser_type::filter_nodes; using traverser_type::find_left_kmers; using traverser_type::find_right_kmers; using traverser_type::gather_left; using traverser_type::gather_right; using traverser_type::traverse_left; using traverser_type::traverse_right; using traverser_type::get_decision_neighbors; typedef spp::sparse_hash_map<link_type, Tag, hash_tuple::hash<link_type>> tag_map_t; typedef typename tag_map_t::const_iterator tag_map_iter_t; typedef spp::sparse_hash_set<link_type, hash_tuple::hash<link_type>> link_set_t; typedef typename link_set_t::const_iterator link_set_iter_t; tag_map_t tag_map; std::shared_ptr<dbg_type> dbg; std::shared_ptr<hashing::UKHS::Map> ukhs; const uint16_t unikmer_k; StreamingTagger(std::shared_ptr<dbg_type> dbg, std::shared_ptr<hashing::UKHS::Map> ukhs) : traverser_type(dbg->K(), ukhs->K(), ukhs), EventNotifier(), dbg(dbg), ukhs(ukhs), unikmer_k(ukhs->K()) { } static std::shared_ptr<StreamingTagger> build(std::shared_ptr<dbg_type> dbg, std::shared_ptr<hashing::UKHS::Map> ukhs) { return std::make_shared<StreamingTagger>(dbg, ukhs); } /** * @Synopsis Creates all tags in sequence's neighborhood and adds them to the master * tag map, while adding the hashes from sequence to the underlying de Bruijn graph. * * @Param sequence Sequence to insert. * * @Returns Number of tags created. */ size_t insert_sequence(const std::string& sequence) { auto new_tags = find_new_tags(sequence); if (new_tags.size()) { for (const auto& item : new_tags) { tag_map[item.first] = item.second; } return new_tags.size(); } return 0; } /** * @Synopsis Finds all new tags induced by the insertion of sequence and returns them. * * @Param sequence * * @Returns The new tags. */ tag_map_t find_new_tags(const std::string& sequence) { kmer_iter_type kmer_iter(sequence, this); std::vector<hash_type> hashes; std::deque<std::pair<std::vector<shift_type>, std::vector<shift_type>>> neighbors; while(!kmer_iter.done()) { auto hash = kmer_iter.next(); if (dbg->insert(hash)) { hashes.push_back(hash); neighbors.push_back(std::make_pair(this->gather_left(), this->gather_right())); } } tag_map_t tags; if (hashes.size() == 0) { return tags; } for (const auto& hash : hashes) { create_neighborhood_tags(hash, this->filter_nodes(dbg.get(), neighbors.front()), tags); neighbors.pop_front(); } return tags; } /** * @Synopsis Creates all possible tags in the given neighbood surrounding root * and adds them to the map given by tags. * * @Param root The neighborhood root. * @Param neighbors The (filtered) neighbors of root. * @Param tags Map to store tags in. */ void create_neighborhood_tags(const hash_type& root, const std::pair<std::vector<shift_type>, std::vector<shift_type>>& neighbors, tag_map_t& tags) { // check in-neighbors for (auto& in_neighbor : neighbors.first) { auto tag = create_tag(in_neighbor.hash, root); if (tag) { tags[tag.value().link] = std::move(tag.value()); } } // and out neighbors for (auto& out_neighbor : neighbors.second) { auto tag = create_tag(root, out_neighbor.hash); if (tag) { tags[tag.value().link] = std::move(tag.value()); } } } /** * @Synopsis Checks if (first, second) could be a Tag, and if so, creates the appropriate * tag and returns it. * * @Param first * @Param second * * @Returns An std::optional<Tag> containing the Tag if successful. */ std::optional<Tag> create_tag(const hash_type& first, const hash_type& second) { if (is_tag(first, second)) { //std::cerr << "\tunikmers don't match" << std::endl; //std::cerr << "\tfirst: " << first << ", second:" << second << std::endl; Tag tag; tag.left_partition = first.unikmer.partition; tag.right_partition = second.unikmer.partition; tag.link = std::make_pair(first.hash, second.hash); return tag; } else { return {}; } } /** * @Synopsis True if the pair (u,v) could be a tag; assumes they are neighbors. * * @Param u * @Param v * * @Returns True if possibly a tag. */ bool is_tag(const hash_type& u, const hash_type& v) { return u.unikmer.partition != v.unikmer.partition; } /** * @Synopsis Check if the pair (u,v) are a tag link and return the corresponding tag if so. * * @Param u * @Param v * * @Returns An std::optional<Tag> containing the tag if found. */ std::optional<Tag> query_tag(const hash_type& u, const hash_type& v) { if (!is_tag(u, v)) { return {}; } auto search = tag_map.find(std::make_pair(u, v)); if (search != tag_map.end()) { return search->second; } return {}; } /** * @Synopsis Find tags within the given sequence. * * @Param sequence Sequence to search. * * @Returns Ordered vector of tags from sequence. */ std::vector<Tag> query_sequence_tags(const std::string& sequence) { std::vector<Tag> tags; kmer_iter_type kmer_iter(sequence, this); hash_type u = kmer_iter.next(); if (kmer_iter.done()) { return tags; } while(!kmer_iter.done()) { hash_type v = kmer_iter.next(); auto tag = query_tag(u, v); if (tag) { tags.push_back(tag.value()); } u = v; } return tags; } /** * @Synopsis Find (unique) tags within the given sequence or directly adjacent to its k-mers. * * @Param sequence Sequence to search. * * @Returns Set of links corresponding to neighboring tags. */ link_set_t query_neighborhood_tags(const std::string& sequence) { kmer_iter_type kmer_iter(sequence, this); link_set_t found; while(!kmer_iter.done()) { hash_type root = kmer_iter.next(); auto neighborhood = this->filter_nodes(dbg.get(), std::make_pair(this->gather_left(), this->gather_right())); for (auto& in_neighbor : neighborhood.first) { if (auto tag = query_tag(in_neighbor.hash, root)) { found.insert(tag.value().link); } } // and out neighbors for (auto& out_neighbor : neighborhood.second) { if (auto tag = query_tag(root, out_neighbor.hash)) { found.insert(tag.value().link); } } } return found; } }; using Processor = InserterProcessor<StreamingTagger>; }; } } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FillProperties.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 00:40:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART_FILLPROPERTIES_HXX #define CHART_FILLPROPERTIES_HXX #include "PropertyHelper.hxx" #include "FastPropertyIdRanges.hxx" #ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_ #include <com/sun/star/beans/Property.hpp> #endif #include <vector> namespace chart { // implements service FillProperties class FillProperties { public: // FastProperty Ids for properties enum { // com.sun.star.drawing.FillProperties PROP_FILL_STYLE = FAST_PROPERTY_ID_START_FILL_PROP, PROP_FILL_COLOR, PROP_FILL_TRANSPARENCE, PROP_FILL_GRADIENT, PROP_FILL_HATCH, PROP_FILL_TRANSPARENCY_STYLE, PROP_FILL_TRANSPARENCY_GRADIENT }; static void AddPropertiesToVector( ::std::vector< ::com::sun::star::beans::Property > & rOutProperties, bool bIncludeStyleProperties = false ); static void AddDefaultsToMap( ::chart::helper::tPropertyValueMap & rOutMap, bool bIncludeStyleProperties = false ); private: // not implemented FillProperties(); }; } // namespace chart // CHART_FILLPROPERTIES_HXX #endif <commit_msg>INTEGRATION: CWS chart2mst3 (1.1.4); FILE MERGED 2006/10/20 20:30:55 iha 1.1.4.8: implement gradient step count 2005/10/07 11:41:06 bm 1.1.4.7: RESYNC: (1.1-1.2); FILE MERGED 2005/07/14 14:42:44 iha 1.1.4.6: cleanup Fillproperties 2005/07/14 12:32:49 iha 1.1.4.5: remove unused parameter 'bIncludeStyleProperties' 2005/07/12 12:57:06 bm 1.1.4.4: use named properties for gradients etc. in chart model 2005/06/16 07:56:48 iha 1.1.4.3: added missing Property FillBackground 2005/06/15 18:17:25 iha 1.1.4.2: correct name for Property FillTransparenceGradient + added comments 2004/02/13 16:51:23 bm 1.1.4.1: join from changes on branch bm_post_chart01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FillProperties.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:16:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART_FILLPROPERTIES_HXX #define CHART_FILLPROPERTIES_HXX #include "PropertyHelper.hxx" #include "FastPropertyIdRanges.hxx" #ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_ #include <com/sun/star/beans/Property.hpp> #endif #include <vector> namespace chart { // implements service FillProperties class FillProperties { public: // FastProperty Ids for properties enum { // com.sun.star.drawing.FillProperties // com.sun.star.drawing.FillProperties PROP_FILL_STYLE = FAST_PROPERTY_ID_START_FILL_PROP , PROP_FILL_COLOR , PROP_FILL_TRANSPARENCE , PROP_FILL_TRANSPARENCE_GRADIENT_NAME // , PROP_FILL_TRANSPARENCE_GRADIENT //optional , PROP_FILL_GRADIENT_NAME , PROP_FILL_GRADIENT_STEPCOUNT // , PROP_FILL_GRADIENT //optional , PROP_FILL_HATCH_NAME // , PROP_FILL_HATCH //optional //------------------------ // bitmap properties start , PROP_FILL_BITMAP_NAME // , PROP_FILL_BITMAP //optional // , PROP_FILL_BITMAP_URL //optional , PROP_FILL_BITMAP_OFFSETX , PROP_FILL_BITMAP_OFFSETY , PROP_FILL_BITMAP_POSITION_OFFSETX , PROP_FILL_BITMAP_POSITION_OFFSETY , PROP_FILL_BITMAP_RECTANGLEPOINT , PROP_FILL_BITMAP_LOGICALSIZE , PROP_FILL_BITMAP_SIZEX , PROP_FILL_BITMAP_SIZEY , PROP_FILL_BITMAP_MODE // bitmap properties end //------------------------ , PROP_FILL_BACKGROUND }; static void AddPropertiesToVector( ::std::vector< ::com::sun::star::beans::Property > & rOutProperties ); static void AddDefaultsToMap( ::chart::tPropertyValueMap & rOutMap ); private: // not implemented FillProperties(); }; } // namespace chart // CHART_FILLPROPERTIES_HXX #endif <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/string_util.h" #include "base/sys_info.h" #include "base/values.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/l10n_util.h" #include "chrome/common/pref_names.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" namespace { // Given a page title, returns the expected window caption string. std::wstring WindowCaptionFromPageTitle(std::wstring page_title) { if (page_title.empty()) return l10n_util::GetString(IDS_PRODUCT_NAME); return l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, page_title); } class BrowserTest : public UITest { protected: HWND GetMainWindow() { scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); scoped_ptr<WindowProxy> window(browser->GetWindow()); HWND window_handle; EXPECT_TRUE(window->GetHWND(&window_handle)); return window_handle; } std::wstring GetWindowTitle() { HWND window_handle = GetMainWindow(); std::wstring result; int length = ::GetWindowTextLength(window_handle) + 1; ::GetWindowText(window_handle, WriteInto(&result, length), length); return result; } }; class VisibleBrowserTest : public UITest { protected: VisibleBrowserTest() : UITest() { show_window_ = true; } }; } // namespace // Launch the app on a page with no title, check that the app title was set // correctly. TEST_F(BrowserTest, NoTitle) { std::wstring test_file = test_data_directory_; file_util::AppendToPath(&test_file, L"title1.html"); NavigateToURL(net::FilePathToFileURL(test_file)); Sleep(sleep_timeout_ms()); // The browser lazily updates the title. EXPECT_EQ(WindowCaptionFromPageTitle(L"title1.html"), GetWindowTitle()); EXPECT_EQ(L"title1.html", GetActiveTabTitle()); } // Launch the app, navigate to a page with a title, check that the app title // was set correctly. TEST_F(BrowserTest, Title) { std::wstring test_file = test_data_directory_; file_util::AppendToPath(&test_file, L"title2.html"); NavigateToURL(net::FilePathToFileURL(test_file)); Sleep(sleep_timeout_ms()); // The browser lazily updates the title. const std::wstring test_title(L"Title Of Awesomeness"); EXPECT_EQ(WindowCaptionFromPageTitle(test_title), GetWindowTitle()); EXPECT_EQ(test_title, GetActiveTabTitle()); } // Create 34 tabs and verify that a lot of processes have been created. The // exact number of processes depends on the amount of memory. Previously we // had a hard limit of 31 processes and this test is mainly directed at // verifying that we don't crash when we pass this limit. TEST_F(BrowserTest, ThirtyFourTabs) { std::wstring test_file = test_data_directory_; file_util::AppendToPath(&test_file, L"title2.html"); GURL url(net::FilePathToFileURL(test_file)); scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); // There is one initial tab. for (int ix = 0; ix != 33; ++ix) { EXPECT_TRUE(window->AppendTab(url)); } int tab_count = 0; EXPECT_TRUE(window->GetTabCount(&tab_count)); EXPECT_EQ(34, tab_count); // Do not test the rest in single process mode. if (in_process_renderer()) return; // See browser\renderer_host\render_process_host.cc for the algorithm to // decide how many processes to create. int process_count = GetBrowserProcessCount(); if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) { EXPECT_GE(process_count, 24); } else { EXPECT_LE(process_count, 23); } } // The browser should quit quickly if it receives a WM_ENDSESSION message. TEST_F(BrowserTest, WindowsSessionEnd) { std::wstring test_file = test_data_directory_; file_util::AppendToPath(&test_file, L"title1.html"); NavigateToURL(net::FilePathToFileURL(test_file)); Sleep(action_timeout_ms()); // Simulate an end of session. Normally this happens when the user // shuts down the pc or logs off. HWND window_handle = GetMainWindow(); ASSERT_TRUE(::PostMessageW(window_handle, WM_ENDSESSION, 0, 0)); Sleep(action_timeout_ms()); ASSERT_FALSE(IsBrowserRunning()); // Make sure the UMA metrics say we didn't crash. scoped_ptr<DictionaryValue> local_prefs(GetLocalState()); bool exited_cleanly; ASSERT_TRUE(local_prefs.get()); ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilityExitedCleanly, &exited_cleanly)); ASSERT_TRUE(exited_cleanly); // And that session end was successful. bool session_end_completed; ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilitySessionEndCompleted, &session_end_completed)); ASSERT_TRUE(session_end_completed); // Make sure session restore says we didn't crash. scoped_ptr<DictionaryValue> profile_prefs(GetDefaultProfilePreferences()); ASSERT_TRUE(profile_prefs.get()); ASSERT_TRUE(profile_prefs->GetBoolean(prefs::kSessionExitedCleanly, &exited_cleanly)); ASSERT_TRUE(exited_cleanly); } // This test is flakey, see bug 5668 for details. TEST_F(BrowserTest, DISABLED_JavascriptAlertActivatesTab) { scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); int start_index; ASSERT_TRUE(window->GetActiveTabIndex(&start_index)); ASSERT_TRUE(window->AppendTab(GURL("about:blank"))); int javascript_tab_index; ASSERT_TRUE(window->GetActiveTabIndex(&javascript_tab_index)); TabProxy* javascript_tab = window->GetActiveTab(); // Switch back to the starting tab, then send the second tab a javascript // alert, which should force it to become active. ASSERT_TRUE(window->ActivateTab(start_index)); ASSERT_TRUE( javascript_tab->NavigateToURLAsync(GURL("javascript:alert('Alert!')"))); ASSERT_TRUE(window->WaitForTabToBecomeActive(javascript_tab_index, action_max_timeout_ms())); } // Test that scripts can fork a new renderer process for a tab in a particular // case (which matches following a link in Gmail). The script must open a new // tab, set its window.opener to null, and redirect it to a cross-site URL. // (Bug 1115708) // This test can only run if V8 is in use, and not KJS, because KJS will not // set window.opener to null properly. #ifdef CHROME_V8 TEST_F(BrowserTest, NullOpenerRedirectForksProcess) { // This test only works in multi-process mode if (in_process_renderer()) return; const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); std::wstring test_file(test_data_directory_); scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); scoped_ptr<TabProxy> tab(window->GetActiveTab()); // Start with a file:// url file_util::AppendToPath(&test_file, L"title2.html"); tab->NavigateToURL(net::FilePathToFileURL(test_file)); int orig_tab_count = -1; ASSERT_TRUE(window->GetTabCount(&orig_tab_count)); int orig_process_count = GetBrowserProcessCount(); ASSERT_TRUE(orig_process_count >= 1); // Use JavaScript URL to "fork" a new tab, just like Gmail. (Open tab to a // blank page, set its opener to null, and redirect it cross-site.) std::wstring url_prefix(L"javascript:(function(){w=window.open();"); GURL fork_url(url_prefix + L"w.opener=null;w.document.location=\"http://localhost:1337\";})()"); // Make sure that a new tab has been created and that we have a new renderer // process for it. tab->NavigateToURLAsync(fork_url); Sleep(action_timeout_ms()); ASSERT_EQ(orig_process_count + 1, GetBrowserProcessCount()); int new_tab_count = -1; ASSERT_TRUE(window->GetTabCount(&new_tab_count)); ASSERT_EQ(orig_tab_count + 1, new_tab_count); } #endif // Tests that non-Gmail-like script redirects (i.e., non-null window.opener) or // a same-page-redirect) will not fork a new process. TEST_F(BrowserTest, OtherRedirectsDontForkProcess) { // This test only works in multi-process mode if (in_process_renderer()) return; const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); std::wstring test_file(test_data_directory_); scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); scoped_ptr<TabProxy> tab(window->GetActiveTab()); // Start with a file:// url file_util::AppendToPath(&test_file, L"title2.html"); tab->NavigateToURL(net::FilePathToFileURL(test_file)); int orig_tab_count = -1; ASSERT_TRUE(window->GetTabCount(&orig_tab_count)); int orig_process_count = GetBrowserProcessCount(); ASSERT_TRUE(orig_process_count >= 1); // Use JavaScript URL to almost fork a new tab, but not quite. (Leave the // opener non-null.) Should not fork a process. std::wstring url_prefix(L"javascript:(function(){w=window.open();"); GURL dont_fork_url(url_prefix + L"w.document.location=\"http://localhost:1337\";})()"); // Make sure that a new tab but not new process has been created. tab->NavigateToURLAsync(dont_fork_url); Sleep(action_timeout_ms()); ASSERT_EQ(orig_process_count, GetBrowserProcessCount()); int new_tab_count = -1; ASSERT_TRUE(window->GetTabCount(&new_tab_count)); ASSERT_EQ(orig_tab_count + 1, new_tab_count); // Same thing if the current tab tries to redirect itself. GURL dont_fork_url2(url_prefix + L"document.location=\"http://localhost:1337\";})()"); // Make sure that no new process has been created. tab->NavigateToURLAsync(dont_fork_url2); Sleep(action_timeout_ms()); ASSERT_EQ(orig_process_count, GetBrowserProcessCount()); } TEST_F(VisibleBrowserTest, WindowOpenClose) { std::wstring test_file(test_data_directory_); file_util::AppendToPath(&test_file, L"window.close.html"); NavigateToURL(net::FilePathToFileURL(test_file)); int i; for (i = 0; i < 10; ++i) { Sleep(action_max_timeout_ms() / 10); std::wstring title = GetActiveTabTitle(); if (title == L"PASSED") { // Success, bail out. break; } } if (i == 10) FAIL() << "failed to get error page title"; } <commit_msg>Disable ThirtyFoudTabs test as it is failing consitently now on all buildbots.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/string_util.h" #include "base/sys_info.h" #include "base/values.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/l10n_util.h" #include "chrome/common/pref_names.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/url_request/url_request_unittest.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" namespace { // Given a page title, returns the expected window caption string. std::wstring WindowCaptionFromPageTitle(std::wstring page_title) { if (page_title.empty()) return l10n_util::GetString(IDS_PRODUCT_NAME); return l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, page_title); } class BrowserTest : public UITest { protected: HWND GetMainWindow() { scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); scoped_ptr<WindowProxy> window(browser->GetWindow()); HWND window_handle; EXPECT_TRUE(window->GetHWND(&window_handle)); return window_handle; } std::wstring GetWindowTitle() { HWND window_handle = GetMainWindow(); std::wstring result; int length = ::GetWindowTextLength(window_handle) + 1; ::GetWindowText(window_handle, WriteInto(&result, length), length); return result; } }; class VisibleBrowserTest : public UITest { protected: VisibleBrowserTest() : UITest() { show_window_ = true; } }; } // namespace // Launch the app on a page with no title, check that the app title was set // correctly. TEST_F(BrowserTest, NoTitle) { std::wstring test_file = test_data_directory_; file_util::AppendToPath(&test_file, L"title1.html"); NavigateToURL(net::FilePathToFileURL(test_file)); Sleep(sleep_timeout_ms()); // The browser lazily updates the title. EXPECT_EQ(WindowCaptionFromPageTitle(L"title1.html"), GetWindowTitle()); EXPECT_EQ(L"title1.html", GetActiveTabTitle()); } // Launch the app, navigate to a page with a title, check that the app title // was set correctly. TEST_F(BrowserTest, Title) { std::wstring test_file = test_data_directory_; file_util::AppendToPath(&test_file, L"title2.html"); NavigateToURL(net::FilePathToFileURL(test_file)); Sleep(sleep_timeout_ms()); // The browser lazily updates the title. const std::wstring test_title(L"Title Of Awesomeness"); EXPECT_EQ(WindowCaptionFromPageTitle(test_title), GetWindowTitle()); EXPECT_EQ(test_title, GetActiveTabTitle()); } // Create 34 tabs and verify that a lot of processes have been created. The // exact number of processes depends on the amount of memory. Previously we // had a hard limit of 31 processes and this test is mainly directed at // verifying that we don't crash when we pass this limit. // Disabling this test as it is making all the buildbots running ui tests red. // see http://code.google.com/p/chromium/issues/detail?id=5668 TEST_F(BrowserTest, DISABLED_ThirtyFourTabs) { std::wstring test_file = test_data_directory_; file_util::AppendToPath(&test_file, L"title2.html"); GURL url(net::FilePathToFileURL(test_file)); scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); // There is one initial tab. for (int ix = 0; ix != 33; ++ix) { EXPECT_TRUE(window->AppendTab(url)); } int tab_count = 0; EXPECT_TRUE(window->GetTabCount(&tab_count)); EXPECT_EQ(34, tab_count); // Do not test the rest in single process mode. if (in_process_renderer()) return; // See browser\renderer_host\render_process_host.cc for the algorithm to // decide how many processes to create. int process_count = GetBrowserProcessCount(); if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) { EXPECT_GE(process_count, 24); } else { EXPECT_LE(process_count, 23); } } // The browser should quit quickly if it receives a WM_ENDSESSION message. TEST_F(BrowserTest, WindowsSessionEnd) { std::wstring test_file = test_data_directory_; file_util::AppendToPath(&test_file, L"title1.html"); NavigateToURL(net::FilePathToFileURL(test_file)); Sleep(action_timeout_ms()); // Simulate an end of session. Normally this happens when the user // shuts down the pc or logs off. HWND window_handle = GetMainWindow(); ASSERT_TRUE(::PostMessageW(window_handle, WM_ENDSESSION, 0, 0)); Sleep(action_timeout_ms()); ASSERT_FALSE(IsBrowserRunning()); // Make sure the UMA metrics say we didn't crash. scoped_ptr<DictionaryValue> local_prefs(GetLocalState()); bool exited_cleanly; ASSERT_TRUE(local_prefs.get()); ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilityExitedCleanly, &exited_cleanly)); ASSERT_TRUE(exited_cleanly); // And that session end was successful. bool session_end_completed; ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilitySessionEndCompleted, &session_end_completed)); ASSERT_TRUE(session_end_completed); // Make sure session restore says we didn't crash. scoped_ptr<DictionaryValue> profile_prefs(GetDefaultProfilePreferences()); ASSERT_TRUE(profile_prefs.get()); ASSERT_TRUE(profile_prefs->GetBoolean(prefs::kSessionExitedCleanly, &exited_cleanly)); ASSERT_TRUE(exited_cleanly); } // This test is flakey, see bug 5668 for details. TEST_F(BrowserTest, DISABLED_JavascriptAlertActivatesTab) { scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); int start_index; ASSERT_TRUE(window->GetActiveTabIndex(&start_index)); ASSERT_TRUE(window->AppendTab(GURL("about:blank"))); int javascript_tab_index; ASSERT_TRUE(window->GetActiveTabIndex(&javascript_tab_index)); TabProxy* javascript_tab = window->GetActiveTab(); // Switch back to the starting tab, then send the second tab a javascript // alert, which should force it to become active. ASSERT_TRUE(window->ActivateTab(start_index)); ASSERT_TRUE( javascript_tab->NavigateToURLAsync(GURL("javascript:alert('Alert!')"))); ASSERT_TRUE(window->WaitForTabToBecomeActive(javascript_tab_index, action_max_timeout_ms())); } // Test that scripts can fork a new renderer process for a tab in a particular // case (which matches following a link in Gmail). The script must open a new // tab, set its window.opener to null, and redirect it to a cross-site URL. // (Bug 1115708) // This test can only run if V8 is in use, and not KJS, because KJS will not // set window.opener to null properly. #ifdef CHROME_V8 TEST_F(BrowserTest, NullOpenerRedirectForksProcess) { // This test only works in multi-process mode if (in_process_renderer()) return; const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); std::wstring test_file(test_data_directory_); scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); scoped_ptr<TabProxy> tab(window->GetActiveTab()); // Start with a file:// url file_util::AppendToPath(&test_file, L"title2.html"); tab->NavigateToURL(net::FilePathToFileURL(test_file)); int orig_tab_count = -1; ASSERT_TRUE(window->GetTabCount(&orig_tab_count)); int orig_process_count = GetBrowserProcessCount(); ASSERT_TRUE(orig_process_count >= 1); // Use JavaScript URL to "fork" a new tab, just like Gmail. (Open tab to a // blank page, set its opener to null, and redirect it cross-site.) std::wstring url_prefix(L"javascript:(function(){w=window.open();"); GURL fork_url(url_prefix + L"w.opener=null;w.document.location=\"http://localhost:1337\";})()"); // Make sure that a new tab has been created and that we have a new renderer // process for it. tab->NavigateToURLAsync(fork_url); Sleep(action_timeout_ms()); ASSERT_EQ(orig_process_count + 1, GetBrowserProcessCount()); int new_tab_count = -1; ASSERT_TRUE(window->GetTabCount(&new_tab_count)); ASSERT_EQ(orig_tab_count + 1, new_tab_count); } #endif // Tests that non-Gmail-like script redirects (i.e., non-null window.opener) or // a same-page-redirect) will not fork a new process. TEST_F(BrowserTest, OtherRedirectsDontForkProcess) { // This test only works in multi-process mode if (in_process_renderer()) return; const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); std::wstring test_file(test_data_directory_); scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); scoped_ptr<TabProxy> tab(window->GetActiveTab()); // Start with a file:// url file_util::AppendToPath(&test_file, L"title2.html"); tab->NavigateToURL(net::FilePathToFileURL(test_file)); int orig_tab_count = -1; ASSERT_TRUE(window->GetTabCount(&orig_tab_count)); int orig_process_count = GetBrowserProcessCount(); ASSERT_TRUE(orig_process_count >= 1); // Use JavaScript URL to almost fork a new tab, but not quite. (Leave the // opener non-null.) Should not fork a process. std::wstring url_prefix(L"javascript:(function(){w=window.open();"); GURL dont_fork_url(url_prefix + L"w.document.location=\"http://localhost:1337\";})()"); // Make sure that a new tab but not new process has been created. tab->NavigateToURLAsync(dont_fork_url); Sleep(action_timeout_ms()); ASSERT_EQ(orig_process_count, GetBrowserProcessCount()); int new_tab_count = -1; ASSERT_TRUE(window->GetTabCount(&new_tab_count)); ASSERT_EQ(orig_tab_count + 1, new_tab_count); // Same thing if the current tab tries to redirect itself. GURL dont_fork_url2(url_prefix + L"document.location=\"http://localhost:1337\";})()"); // Make sure that no new process has been created. tab->NavigateToURLAsync(dont_fork_url2); Sleep(action_timeout_ms()); ASSERT_EQ(orig_process_count, GetBrowserProcessCount()); } TEST_F(VisibleBrowserTest, WindowOpenClose) { std::wstring test_file(test_data_directory_); file_util::AppendToPath(&test_file, L"window.close.html"); NavigateToURL(net::FilePathToFileURL(test_file)); int i; for (i = 0; i < 10; ++i) { Sleep(action_max_timeout_ms() / 10); std::wstring title = GetActiveTabTitle(); if (title == L"PASSED") { // Success, bail out. break; } } if (i == 10) FAIL() << "failed to get error page title"; } <|endoftext|>
<commit_before> // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <services.h> #include <uielement/panelwrapper.hxx> #include <threadhelp/resetableguard.hxx> #include <helper/actiontriggerhelper.hxx> #include <uielement/constitemcontainer.hxx> #include <uielement/rootitemcontainer.hxx> #include <uielement/panelwindow.hxx> #include <services/modelwinservice.hxx> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/awt/XSystemDependentMenuPeer.hpp> #include <com/sun/star/awt/XMenuBar.hpp> #include <com/sun/star/container/XIndexContainer.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/ui/UIElementType.hpp> //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <toolkit/unohlp.hxx> #include <toolkit/awt/vclxwindow.hxx> #include <comphelper/processfactory.hxx> #include <svtools/miscopt.hxx> #include <vcl/svapp.hxx> #include <rtl/logfile.hxx> using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::beans; using namespace com::sun::star::frame; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::awt; using namespace ::com::sun::star::ui; namespace framework { PanelWrapper::PanelWrapper( const Reference< XMultiServiceFactory >& xServiceManager ) : UIElementWrapperBase( UIElementType::DOCKINGWINDOW ), m_xServiceManager( xServiceManager ), m_bNoClose(false) { } PanelWrapper::~PanelWrapper() { } // XInterface void SAL_CALL PanelWrapper::acquire() throw() { UIElementWrapperBase::acquire(); } void SAL_CALL PanelWrapper::release() throw() { UIElementWrapperBase::release(); } uno::Any SAL_CALL PanelWrapper::queryInterface( const uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException ) { return UIElementWrapperBase::queryInterface( rType ); } // XComponent void SAL_CALL PanelWrapper::dispose() throw ( RuntimeException ) { Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY ); Reference< XMultiServiceFactory > xSMGR( m_xServiceManager ); Reference< XWindow > xWindow; { ResetableGuard aLock( m_aLock ); if ( m_bDisposed ) return; xSMGR = m_xServiceManager; } com::sun::star::lang::EventObject aEvent( xThis ); m_aListenerContainer.disposeAndClear( aEvent ); rtl::OUString aModelWinService( SERVICENAME_MODELWINSERVICE ); Reference< XNameAccess > xNameAccess( xSMGR->createInstance( aModelWinService ), UNO_QUERY ); if ( xNameAccess.is() ) { ModelWinService* pService = dynamic_cast< ModelWinService* >( xNameAccess.get() ); if ( pService != 0 ) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); PanelWindow* pPanelWindow = dynamic_cast< PanelWindow* >( m_xPanelWindow.get() ); if ( pPanelWindow != NULL ) { xWindow = VCLUnoHelper::GetInterface( pPanelWindow->getContentWindow() ); pService->deregisterModelForXWindow( xWindow ); } } } ResetableGuard aLock( m_aLock ); m_xPanelWindow.clear(); m_bDisposed = sal_True; } // XInitialization void SAL_CALL PanelWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException ) { ResetableGuard aLock( m_aLock ); if ( m_bDisposed ) throw DisposedException(); if ( !m_bInitialized ) { UIElementWrapperBase::initialize( aArguments ); sal_Bool bPopupMode( sal_False ); Reference< XWindow > xContentWindow; for ( sal_Int32 i = 0; i < aArguments.getLength(); i++ ) { PropertyValue aPropValue; if ( aArguments[i] >>= aPropValue ) { if ( aPropValue.Name.equalsAsciiL( "PopupMode", 9 )) aPropValue.Value >>= bPopupMode; else if ( aPropValue.Name.equalsAsciiL( "ContentWindow", 13 )) aPropValue.Value >>= xContentWindow; } } Reference< XFrame > xFrame( m_xWeakFrame ); if ( xFrame.is() ) { PanelWindow* pPanelWindow(0); Window* pContentWindow(0); { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() ); pContentWindow = VCLUnoHelper::GetWindow( xContentWindow ); if ( pWindow ) { ULONG nStyles = WB_LINESPACING | WB_BORDER | WB_SCROLL | WB_MOVEABLE | WB_3DLOOK | WB_DOCKABLE | WB_SIZEABLE | WB_CLOSEABLE; pPanelWindow = new PanelWindow( pWindow, nStyles ); m_xPanelWindow = VCLUnoHelper::GetInterface( pPanelWindow ); pPanelWindow->setResourceURL( m_aResourceURL ); pPanelWindow->setContentWindow( pContentWindow ); } } try { } catch ( NoSuchElementException& ) { } } } } // XEventListener void SAL_CALL PanelWrapper::disposing( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException) { // nothing todo } // XUpdatable void SAL_CALL PanelWrapper::update() throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aLock( m_aLock ); if ( m_bDisposed ) throw DisposedException(); } // XUIElement interface Reference< XInterface > SAL_CALL PanelWrapper::getRealInterface( ) throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aLock( m_aLock ); return m_xPanelWindow; } void SAL_CALL PanelWrapper::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const com::sun::star::uno::Any& aValue ) throw( com::sun::star::uno::Exception ) { ResetableGuard aLock( m_aLock ); sal_Bool bNoClose( m_bNoClose ); aLock.unlock(); UIElementWrapperBase::setFastPropertyValue_NoBroadcast( nHandle, aValue ); aLock.lock(); sal_Bool bNewNoClose( m_bNoClose ); if ( m_xPanelWindow.is() && !m_bDisposed && ( bNewNoClose != bNoClose )) { PanelWindow* pPanelWindow = dynamic_cast< PanelWindow* >( VCLUnoHelper::GetWindow( m_xPanelWindow ) ); if ( pPanelWindow ) { if ( bNewNoClose ) { pPanelWindow->SetStyle( pPanelWindow->GetStyle() & ~WB_CLOSEABLE ); pPanelWindow->SetFloatStyle( pPanelWindow->GetFloatStyle() & ~WB_CLOSEABLE ); } else { pPanelWindow->SetStyle( pPanelWindow->GetStyle() | WB_CLOSEABLE ); pPanelWindow->SetFloatStyle( pPanelWindow->GetFloatStyle() | WB_CLOSEABLE ); } } } } } // namespace framework <commit_msg>CWS gnumake2: another build breaker<commit_after> // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <services.h> #include <uielement/panelwrapper.hxx> #include <threadhelp/resetableguard.hxx> #include <uielement/constitemcontainer.hxx> #include <uielement/rootitemcontainer.hxx> #include <uielement/panelwindow.hxx> #include <services/modelwinservice.hxx> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/awt/XSystemDependentMenuPeer.hpp> #include <com/sun/star/awt/XMenuBar.hpp> #include <com/sun/star/container/XIndexContainer.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/ui/UIElementType.hpp> //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <toolkit/unohlp.hxx> #include <toolkit/awt/vclxwindow.hxx> #include <comphelper/processfactory.hxx> #include <svtools/miscopt.hxx> #include <vcl/svapp.hxx> #include <rtl/logfile.hxx> using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::beans; using namespace com::sun::star::frame; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::awt; using namespace ::com::sun::star::ui; namespace framework { PanelWrapper::PanelWrapper( const Reference< XMultiServiceFactory >& xServiceManager ) : UIElementWrapperBase( UIElementType::DOCKINGWINDOW ), m_xServiceManager( xServiceManager ), m_bNoClose(false) { } PanelWrapper::~PanelWrapper() { } // XInterface void SAL_CALL PanelWrapper::acquire() throw() { UIElementWrapperBase::acquire(); } void SAL_CALL PanelWrapper::release() throw() { UIElementWrapperBase::release(); } uno::Any SAL_CALL PanelWrapper::queryInterface( const uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException ) { return UIElementWrapperBase::queryInterface( rType ); } // XComponent void SAL_CALL PanelWrapper::dispose() throw ( RuntimeException ) { Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY ); Reference< XMultiServiceFactory > xSMGR( m_xServiceManager ); Reference< XWindow > xWindow; { ResetableGuard aLock( m_aLock ); if ( m_bDisposed ) return; xSMGR = m_xServiceManager; } com::sun::star::lang::EventObject aEvent( xThis ); m_aListenerContainer.disposeAndClear( aEvent ); rtl::OUString aModelWinService( SERVICENAME_MODELWINSERVICE ); Reference< XNameAccess > xNameAccess( xSMGR->createInstance( aModelWinService ), UNO_QUERY ); if ( xNameAccess.is() ) { ModelWinService* pService = dynamic_cast< ModelWinService* >( xNameAccess.get() ); if ( pService != 0 ) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); PanelWindow* pPanelWindow = dynamic_cast< PanelWindow* >( m_xPanelWindow.get() ); if ( pPanelWindow != NULL ) { xWindow = VCLUnoHelper::GetInterface( pPanelWindow->getContentWindow() ); pService->deregisterModelForXWindow( xWindow ); } } } ResetableGuard aLock( m_aLock ); m_xPanelWindow.clear(); m_bDisposed = sal_True; } // XInitialization void SAL_CALL PanelWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException ) { ResetableGuard aLock( m_aLock ); if ( m_bDisposed ) throw DisposedException(); if ( !m_bInitialized ) { UIElementWrapperBase::initialize( aArguments ); sal_Bool bPopupMode( sal_False ); Reference< XWindow > xContentWindow; for ( sal_Int32 i = 0; i < aArguments.getLength(); i++ ) { PropertyValue aPropValue; if ( aArguments[i] >>= aPropValue ) { if ( aPropValue.Name.equalsAsciiL( "PopupMode", 9 )) aPropValue.Value >>= bPopupMode; else if ( aPropValue.Name.equalsAsciiL( "ContentWindow", 13 )) aPropValue.Value >>= xContentWindow; } } Reference< XFrame > xFrame( m_xWeakFrame ); if ( xFrame.is() ) { PanelWindow* pPanelWindow(0); Window* pContentWindow(0); { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() ); pContentWindow = VCLUnoHelper::GetWindow( xContentWindow ); if ( pWindow ) { ULONG nStyles = WB_LINESPACING | WB_BORDER | WB_SCROLL | WB_MOVEABLE | WB_3DLOOK | WB_DOCKABLE | WB_SIZEABLE | WB_CLOSEABLE; pPanelWindow = new PanelWindow( pWindow, nStyles ); m_xPanelWindow = VCLUnoHelper::GetInterface( pPanelWindow ); pPanelWindow->setResourceURL( m_aResourceURL ); pPanelWindow->setContentWindow( pContentWindow ); } } try { } catch ( NoSuchElementException& ) { } } } } // XEventListener void SAL_CALL PanelWrapper::disposing( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException) { // nothing todo } // XUpdatable void SAL_CALL PanelWrapper::update() throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aLock( m_aLock ); if ( m_bDisposed ) throw DisposedException(); } // XUIElement interface Reference< XInterface > SAL_CALL PanelWrapper::getRealInterface( ) throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aLock( m_aLock ); return m_xPanelWindow; } void SAL_CALL PanelWrapper::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const com::sun::star::uno::Any& aValue ) throw( com::sun::star::uno::Exception ) { ResetableGuard aLock( m_aLock ); sal_Bool bNoClose( m_bNoClose ); aLock.unlock(); UIElementWrapperBase::setFastPropertyValue_NoBroadcast( nHandle, aValue ); aLock.lock(); sal_Bool bNewNoClose( m_bNoClose ); if ( m_xPanelWindow.is() && !m_bDisposed && ( bNewNoClose != bNoClose )) { PanelWindow* pPanelWindow = dynamic_cast< PanelWindow* >( VCLUnoHelper::GetWindow( m_xPanelWindow ) ); if ( pPanelWindow ) { if ( bNewNoClose ) { pPanelWindow->SetStyle( pPanelWindow->GetStyle() & ~WB_CLOSEABLE ); pPanelWindow->SetFloatStyle( pPanelWindow->GetFloatStyle() & ~WB_CLOSEABLE ); } else { pPanelWindow->SetStyle( pPanelWindow->GetStyle() | WB_CLOSEABLE ); pPanelWindow->SetFloatStyle( pPanelWindow->GetFloatStyle() | WB_CLOSEABLE ); } } } } } // namespace framework <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://qt.nokia.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <limits.h> #include <QTest> #include <QMetaType> #include <QSignalSpy> #include <QDebug> #include <qgeopositioninfosource.h> #include <qgeopositioninfo.h> #include "testqgeopositioninfosource_p.h" #include "qlocationtestutils_p.h" Q_DECLARE_METATYPE(QGeoPositionInfoSource::PositioningMethod) Q_DECLARE_METATYPE(QGeoPositionInfoSource::PositioningMethods) Q_DECLARE_METATYPE(QGeoPositionInfo) #define MAX_WAITING_TIME 50000 // Must provide a valid source, unless testing the source // returned by QGeoPositionInfoSource::createSource() on a system // that has no default source #define CHECK_SOURCE_VALID { \ if (QGeoPositionInfoSource::createSource() == 0) \ QSKIP("No default position source on this system", SkipAll); \ else \ QFAIL("createTestSource() must return a valid source!"); \ } class MyPositionSource : public QGeoPositionInfoSource { Q_OBJECT public: MyPositionSource(QObject *parent = 0) : QGeoPositionInfoSource(parent) { } QGeoPositionInfo lastKnownPosition(bool /*fromSatellitePositioningMethodsOnly = false*/) const { return QGeoPositionInfo(); } virtual PositioningMethods supportedPositioningMethods() const { return 0; } virtual int minimumUpdateInterval() const { return 0; } virtual void startUpdates() {} virtual void stopUpdates() {} virtual void requestUpdate(int) {} }; void TestQGeoPositionInfoSource::base_initTestCase() { qRegisterMetaType<QGeoPositionInfo>(); } void TestQGeoPositionInfoSource::base_init() { m_source = createTestSource(); } void TestQGeoPositionInfoSource::base_cleanup() { delete m_source; m_source = 0; } void TestQGeoPositionInfoSource::base_cleanupTestCase() { } void TestQGeoPositionInfoSource::initTestCase() { base_initTestCase(); } void TestQGeoPositionInfoSource::init() { base_init(); } void TestQGeoPositionInfoSource::cleanup() { base_cleanup(); } void TestQGeoPositionInfoSource::cleanupTestCase() { base_cleanupTestCase(); } // TC_ID_3_x_1 void TestQGeoPositionInfoSource::constructor_withParent() { QLocationTestUtils::uheap_mark(); QObject *parent = new QObject(); new MyPositionSource(parent); delete parent; QLocationTestUtils::uheap_mark_end(); } // TC_ID_3_x_2 void TestQGeoPositionInfoSource::constructor_noParent() { QLocationTestUtils::uheap_mark(); MyPositionSource *obj = new MyPositionSource(); delete obj; QLocationTestUtils::uheap_mark_end(); } void TestQGeoPositionInfoSource::updateInterval() { MyPositionSource s; QCOMPARE(s.updateInterval(), 0); } void TestQGeoPositionInfoSource::setPreferredPositioningMethods() { QFETCH(int, methods); MyPositionSource s; s.setPreferredPositioningMethods(static_cast<QGeoPositionInfoSource::PositioningMethods>(methods)); QCOMPARE(s.preferredPositioningMethods(), static_cast<QGeoPositionInfoSource::PositioningMethods>(methods)); } void TestQGeoPositionInfoSource::setPreferredPositioningMethods_data() { QTest::addColumn<int>("methods"); QTest::newRow("sat") << int(QGeoPositionInfoSource::SatellitePositioningMethods); QTest::newRow("sat | non-sat") << int(QGeoPositionInfoSource::SatellitePositioningMethods | QGeoPositionInfoSource::NonSatellitePositioningMethods); QTest::newRow("all") << int(QGeoPositionInfoSource::AllPositioningMethods); QTest::newRow("all | sat") << int(QGeoPositionInfoSource::AllPositioningMethods | QGeoPositionInfoSource::NonSatellitePositioningMethods); } void TestQGeoPositionInfoSource::preferredPositioningMethods() { MyPositionSource s; QCOMPARE(s.preferredPositioningMethods(), 0); } //TC_ID_3_x_1 : Create a position source with the given parent that reads from the system's default sources of location data void TestQGeoPositionInfoSource::createSource() { QLocationTestUtils::uheap_mark(); QObject *parent = new QObject; QGeoPositionInfoSource *source = QGeoPositionInfoSource::createSource(parent); #if defined(Q_OS_SYMBIAN) QVERIFY(source != 0); #else QVERIFY(source == 0); #endif delete parent; QLocationTestUtils::uheap_mark_end(); } void TestQGeoPositionInfoSource::setUpdateInterval() { CHECK_SOURCE_VALID; QFETCH(int, interval); QFETCH(int, expectedInterval); m_source->setUpdateInterval(interval); QCOMPARE(m_source->updateInterval(), expectedInterval); } void TestQGeoPositionInfoSource::setUpdateInterval_data() { QTest::addColumn<int>("interval"); QTest::addColumn<int>("expectedInterval"); QGeoPositionInfoSource *source = createTestSource(); int minUpdateInterval = source ? source->minimumUpdateInterval() : -1; QTest::newRow("INT_MIN") << INT_MIN << minUpdateInterval; QTest::newRow("-1") << -1 << minUpdateInterval; QTest::newRow("0") << 0 << 0; QTest::newRow("in btw zero and minInterval") << 1 << minUpdateInterval; QTest::newRow("more than minInterval") << minUpdateInterval + 1 << minUpdateInterval + 1; QTest::newRow("less then minInterval") << minUpdateInterval - 1 << minUpdateInterval; QTest::newRow("equal to minInterval") << minUpdateInterval << minUpdateInterval; QTest::newRow("INT_MAX") << INT_MAX << INT_MAX; } void TestQGeoPositionInfoSource::lastKnownPosition() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source,SIGNAL(positionUpdated(const QGeoPositionInfo&))); int time_out = 20000; m_source->setUpdateInterval(time_out); m_source->startUpdates(); QTRY_COMPARE_WITH_TIMEOUT(spy.count(),1,30000); QList<QVariant> list = spy.takeFirst(); QGeoPositionInfo info; info = list.at(0).value<QGeoPositionInfo>(); QGeoPositionInfo lastPositioninfo; lastPositioninfo = m_source->lastKnownPosition(); QCOMPARE(info.coordinate(),lastPositioninfo.coordinate()); QCOMPARE(info.dateTime(),lastPositioninfo.dateTime()); QCOMPARE(qFuzzyCompare(info.property(QGeoPositionInfo::HorizontalAccuracy), lastPositioninfo.property(QGeoPositionInfo::HorizontalAccuracy)),TRUE); QCOMPARE(qFuzzyCompare(info.property(QGeoPositionInfo::VerticalAccuracy), lastPositioninfo.property(QGeoPositionInfo::VerticalAccuracy)),TRUE); } void TestQGeoPositionInfoSource::minimumUpdateInterval() { CHECK_SOURCE_VALID; QVERIFY(m_source->minimumUpdateInterval() > 0); } //TC_ID_3_x_1 void TestQGeoPositionInfoSource::startUpdates_testIntervals() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&))); m_source->setUpdateInterval(8000); int interval = m_source->updateInterval(); m_source->startUpdates(); QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, 20000); for (int i=0; i<9; i++) { QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, (interval*3)); spy.clear(); } // TODO Currently updates are coming irregularly from S60 #if !defined(Q_OS_SYMBIAN) for (int i=0; i<9; i++) { QTRY_COMPARE_WITH_TIMEOUT_RANGE(spy.count(), 1, 7000, 10000); spy.clear(); } #endif m_source->stopUpdates(); } //TC_ID_3_x_2 void TestQGeoPositionInfoSource::startUpdates_testDefaultInterval() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&))); m_source->startUpdates(); for (int i=0; i<3; i++) { QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, 3000); spy.clear(); } m_source->stopUpdates(); } //TC_ID_3_x_3 void TestQGeoPositionInfoSource::startUpdates_testZeroInterval() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&))); m_source->setUpdateInterval(0); m_source->startUpdates(); for (int i=0; i<3; i++) { QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, 3000); spy.clear(); } m_source->stopUpdates(); } //TC_ID_3_x_1 void TestQGeoPositionInfoSource::stopUpdates() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&))); m_source->setUpdateInterval(8000); m_source->startUpdates(); for (int i=0; i<2; i++) { QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, 10000); spy.clear(); } m_source->stopUpdates(); QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 0, 10000); spy.clear(); m_source->setUpdateInterval(0); m_source->startUpdates(); m_source->stopUpdates(); QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 0, 10000); } //TC_ID_3_x_2 void TestQGeoPositionInfoSource::stopUpdates_withoutStart() { CHECK_SOURCE_VALID; m_source->stopUpdates(); // check there is no crash } void TestQGeoPositionInfoSource::requestUpdate() { CHECK_SOURCE_VALID; QFETCH(int, timeout); QSignalSpy spy(m_source, SIGNAL(requestTimeout())); m_source->requestUpdate(timeout); QTRY_COMPARE(spy.count(), 1); } void TestQGeoPositionInfoSource::requestUpdate_data() { QTest::addColumn<int>("timeout"); QTest::newRow("zero") << 0; //TC_ID_3_x_6 QTest::newRow("less than zero") << -1; //TC_ID_3_x_7 } // TC_ID_3_x_1 : Create position source and call requestUpdate with valid timeout value void TestQGeoPositionInfoSource::requestUpdate_validTimeout() { CHECK_SOURCE_VALID; QSignalSpy spyUpdate(m_source, SIGNAL(positionUpdated(QGeoPositionInfo))); m_source->requestUpdate(20000); //Q_WAIT(spyUpdate.count(), 1, 20000); //QCOMPARE(spyUpdate.count(),1); QTRY_COMPARE_WITH_TIMEOUT(spyUpdate.count(), 1, 20000); spyUpdate.clear(); } // TC_ID_3_x_2 : Create position source and call requestUpdate with a timeout less than minimumupdateInterval void TestQGeoPositionInfoSource::requestUpdate_timeoutLessThanMinimumInterval() { CHECK_SOURCE_VALID; QSignalSpy spyTimeout(m_source, SIGNAL(requestTimeout())); m_source->requestUpdate(1); //Q_WAIT(spyTimeout.count(), 1, 10); //QCOMPARE(spyTimeout.count(), 1); QTRY_COMPARE_WITH_TIMEOUT(spyTimeout.count(), 1, 10); spyTimeout.clear(); } // TC_ID_3_x_3 : Call requestUpdate() with same value repeatedly void TestQGeoPositionInfoSource::requestUpdate_repeatedCalls() { CHECK_SOURCE_VALID; QSignalSpy spyUpdate(m_source, SIGNAL(positionUpdated(QGeoPositionInfo))); m_source->requestUpdate(20000); //Q_WAIT(spyUpdate.count(), 1, 20000); //QCOMPARE(spyUpdate.count(), 1); QTRY_COMPARE_WITH_TIMEOUT(spyUpdate.count(), 1, 20000); spyUpdate.clear(); m_source->requestUpdate(20000); //Q_WAIT(spyUpdate.count(), 1, 20000); //QCOMPARE(spyUpdate.count(),1); QTRY_COMPARE_WITH_TIMEOUT(spyUpdate.count(), 1, 20000); spyUpdate.clear(); } //TC_ID_3_x_4 void TestQGeoPositionInfoSource::requestUpdate_withUpdateInterval() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&))); m_source->setUpdateInterval(MAX_WAITING_TIME); m_source->startUpdates(); QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, MAX_WAITING_TIME); m_source->requestUpdate(25000); QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 2, 27000); m_source->stopUpdates(); } #include "testqgeopositioninfosource.moc" <commit_msg>Fix tests where conditions fail if an additional position update is received because the QTRY_* function has not stopped immediately after the first update is received (due to qWait()).<commit_after>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://qt.nokia.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <limits.h> #include <QTest> #include <QMetaType> #include <QSignalSpy> #include <QDebug> #include <QTimer> #include <qgeopositioninfosource.h> #include <qgeopositioninfo.h> #include "testqgeopositioninfosource_p.h" #include "qlocationtestutils_p.h" Q_DECLARE_METATYPE(QGeoPositionInfoSource::PositioningMethod) Q_DECLARE_METATYPE(QGeoPositionInfoSource::PositioningMethods) Q_DECLARE_METATYPE(QGeoPositionInfo) #define MAX_WAITING_TIME 50000 // Must provide a valid source, unless testing the source // returned by QGeoPositionInfoSource::createSource() on a system // that has no default source #define CHECK_SOURCE_VALID { \ if (!m_source) { \ if (QGeoPositionInfoSource::createSource() == 0) \ QSKIP("No default position source on this system", SkipAll); \ else \ QFAIL("createTestSource() must return a valid source!"); \ } \ } class MyPositionSource : public QGeoPositionInfoSource { Q_OBJECT public: MyPositionSource(QObject *parent = 0) : QGeoPositionInfoSource(parent) { } QGeoPositionInfo lastKnownPosition(bool /*fromSatellitePositioningMethodsOnly = false*/) const { return QGeoPositionInfo(); } virtual PositioningMethods supportedPositioningMethods() const { return 0; } virtual int minimumUpdateInterval() const { return 0; } virtual void startUpdates() {} virtual void stopUpdates() {} virtual void requestUpdate(int) {} }; void TestQGeoPositionInfoSource::base_initTestCase() { qRegisterMetaType<QGeoPositionInfo>(); } void TestQGeoPositionInfoSource::base_init() { m_source = createTestSource(); } void TestQGeoPositionInfoSource::base_cleanup() { delete m_source; m_source = 0; } void TestQGeoPositionInfoSource::base_cleanupTestCase() { } void TestQGeoPositionInfoSource::initTestCase() { base_initTestCase(); } void TestQGeoPositionInfoSource::init() { base_init(); } void TestQGeoPositionInfoSource::cleanup() { base_cleanup(); } void TestQGeoPositionInfoSource::cleanupTestCase() { base_cleanupTestCase(); } // TC_ID_3_x_1 void TestQGeoPositionInfoSource::constructor_withParent() { QLocationTestUtils::uheap_mark(); QObject *parent = new QObject(); new MyPositionSource(parent); delete parent; QLocationTestUtils::uheap_mark_end(); } // TC_ID_3_x_2 void TestQGeoPositionInfoSource::constructor_noParent() { QLocationTestUtils::uheap_mark(); MyPositionSource *obj = new MyPositionSource(); delete obj; QLocationTestUtils::uheap_mark_end(); } void TestQGeoPositionInfoSource::updateInterval() { MyPositionSource s; QCOMPARE(s.updateInterval(), 0); } void TestQGeoPositionInfoSource::setPreferredPositioningMethods() { QFETCH(int, methods); MyPositionSource s; s.setPreferredPositioningMethods(static_cast<QGeoPositionInfoSource::PositioningMethods>(methods)); QCOMPARE(s.preferredPositioningMethods(), static_cast<QGeoPositionInfoSource::PositioningMethods>(methods)); } void TestQGeoPositionInfoSource::setPreferredPositioningMethods_data() { QTest::addColumn<int>("methods"); QTest::newRow("sat") << int(QGeoPositionInfoSource::SatellitePositioningMethods); QTest::newRow("sat | non-sat") << int(QGeoPositionInfoSource::SatellitePositioningMethods | QGeoPositionInfoSource::NonSatellitePositioningMethods); QTest::newRow("all") << int(QGeoPositionInfoSource::AllPositioningMethods); QTest::newRow("all | sat") << int(QGeoPositionInfoSource::AllPositioningMethods | QGeoPositionInfoSource::NonSatellitePositioningMethods); } void TestQGeoPositionInfoSource::preferredPositioningMethods() { MyPositionSource s; QCOMPARE(s.preferredPositioningMethods(), 0); } //TC_ID_3_x_1 : Create a position source with the given parent that reads from the system's default sources of location data void TestQGeoPositionInfoSource::createSource() { QLocationTestUtils::uheap_mark(); QObject *parent = new QObject; QGeoPositionInfoSource *source = QGeoPositionInfoSource::createSource(parent); #if defined(Q_OS_SYMBIAN) QVERIFY(source != 0); #else QVERIFY(source == 0); #endif delete parent; QLocationTestUtils::uheap_mark_end(); } void TestQGeoPositionInfoSource::setUpdateInterval() { CHECK_SOURCE_VALID; QFETCH(int, interval); QFETCH(int, expectedInterval); m_source->setUpdateInterval(interval); QCOMPARE(m_source->updateInterval(), expectedInterval); } void TestQGeoPositionInfoSource::setUpdateInterval_data() { QTest::addColumn<int>("interval"); QTest::addColumn<int>("expectedInterval"); QGeoPositionInfoSource *source = createTestSource(); int minUpdateInterval = source ? source->minimumUpdateInterval() : -1; QTest::newRow("INT_MIN") << INT_MIN << minUpdateInterval; QTest::newRow("-1") << -1 << minUpdateInterval; QTest::newRow("0") << 0 << 0; QTest::newRow("in btw zero and minInterval") << 1 << minUpdateInterval; QTest::newRow("more than minInterval") << minUpdateInterval + 1 << minUpdateInterval + 1; QTest::newRow("less then minInterval") << minUpdateInterval - 1 << minUpdateInterval; QTest::newRow("equal to minInterval") << minUpdateInterval << minUpdateInterval; QTest::newRow("INT_MAX") << INT_MAX << INT_MAX; } void TestQGeoPositionInfoSource::lastKnownPosition() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source,SIGNAL(positionUpdated(const QGeoPositionInfo&))); int time_out = 20000; m_source->setUpdateInterval(time_out); m_source->startUpdates(); //QTRY_COMPARE_WITH_TIMEOUT(spy.count(),1,30000); // Use QEventLoop instead of qWait() to ensure we stop as soon as a // position is emitted (otherwise the lastKnownPosition() may have // changed by the time it is checked) QEventLoop loop; QTimer timer; timer.setInterval(30000); connect(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&)), &loop, SLOT(quit())); connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); timer.start(); loop.exec(); QCOMPARE(spy.count(), 1); QList<QVariant> list = spy.takeFirst(); QGeoPositionInfo info; info = list.at(0).value<QGeoPositionInfo>(); QGeoPositionInfo lastPositioninfo; lastPositioninfo = m_source->lastKnownPosition(); QCOMPARE(info.coordinate(),lastPositioninfo.coordinate()); QCOMPARE(info.dateTime(),lastPositioninfo.dateTime()); QCOMPARE(qFuzzyCompare(info.property(QGeoPositionInfo::HorizontalAccuracy), lastPositioninfo.property(QGeoPositionInfo::HorizontalAccuracy)),TRUE); QCOMPARE(qFuzzyCompare(info.property(QGeoPositionInfo::VerticalAccuracy), lastPositioninfo.property(QGeoPositionInfo::VerticalAccuracy)),TRUE); } void TestQGeoPositionInfoSource::minimumUpdateInterval() { CHECK_SOURCE_VALID; QVERIFY(m_source->minimumUpdateInterval() > 0); } //TC_ID_3_x_1 void TestQGeoPositionInfoSource::startUpdates_testIntervals() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&))); m_source->setUpdateInterval(8000); int interval = m_source->updateInterval(); m_source->startUpdates(); QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, 20000); for (int i=0; i<9; i++) { QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, (interval*3)); spy.clear(); } // TODO Currently updates are coming irregularly from S60 #if !defined(Q_OS_SYMBIAN) for (int i=0; i<9; i++) { QTRY_COMPARE_WITH_TIMEOUT_RANGE(spy.count(), 1, 7000, 10000); spy.clear(); } #endif m_source->stopUpdates(); } //TC_ID_3_x_2 void TestQGeoPositionInfoSource::startUpdates_testDefaultInterval() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&))); m_source->startUpdates(); for (int i=0; i<3; i++) { QTRY_VERIFY_WITH_TIMEOUT(spy.count() > 0, 3000); spy.clear(); } m_source->stopUpdates(); } //TC_ID_3_x_3 void TestQGeoPositionInfoSource::startUpdates_testZeroInterval() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&))); m_source->setUpdateInterval(0); m_source->startUpdates(); for (int i=0; i<3; i++) { QTRY_VERIFY_WITH_TIMEOUT(spy.count() > 0, 3000); spy.clear(); } m_source->stopUpdates(); } //TC_ID_3_x_1 void TestQGeoPositionInfoSource::stopUpdates() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&))); m_source->setUpdateInterval(8000); m_source->startUpdates(); for (int i=0; i<2; i++) { QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, 10000); spy.clear(); } m_source->stopUpdates(); QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 0, 10000); spy.clear(); m_source->setUpdateInterval(0); m_source->startUpdates(); m_source->stopUpdates(); QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 0, 10000); } //TC_ID_3_x_2 void TestQGeoPositionInfoSource::stopUpdates_withoutStart() { CHECK_SOURCE_VALID; m_source->stopUpdates(); // check there is no crash } void TestQGeoPositionInfoSource::requestUpdate() { CHECK_SOURCE_VALID; QFETCH(int, timeout); QSignalSpy spy(m_source, SIGNAL(requestTimeout())); m_source->requestUpdate(timeout); QTRY_COMPARE(spy.count(), 1); } void TestQGeoPositionInfoSource::requestUpdate_data() { QTest::addColumn<int>("timeout"); QTest::newRow("zero") << 0; //TC_ID_3_x_6 QTest::newRow("less than zero") << -1; //TC_ID_3_x_7 } // TC_ID_3_x_1 : Create position source and call requestUpdate with valid timeout value void TestQGeoPositionInfoSource::requestUpdate_validTimeout() { CHECK_SOURCE_VALID; QSignalSpy spyUpdate(m_source, SIGNAL(positionUpdated(QGeoPositionInfo))); m_source->requestUpdate(20000); //Q_WAIT(spyUpdate.count(), 1, 20000); //QCOMPARE(spyUpdate.count(),1); QTRY_COMPARE_WITH_TIMEOUT(spyUpdate.count(), 1, 20000); spyUpdate.clear(); } // TC_ID_3_x_2 : Create position source and call requestUpdate with a timeout less than minimumupdateInterval void TestQGeoPositionInfoSource::requestUpdate_timeoutLessThanMinimumInterval() { CHECK_SOURCE_VALID; QSignalSpy spyTimeout(m_source, SIGNAL(requestTimeout())); m_source->requestUpdate(1); //Q_WAIT(spyTimeout.count(), 1, 10); //QCOMPARE(spyTimeout.count(), 1); QTRY_COMPARE_WITH_TIMEOUT(spyTimeout.count(), 1, 10); spyTimeout.clear(); } // TC_ID_3_x_3 : Call requestUpdate() with same value repeatedly void TestQGeoPositionInfoSource::requestUpdate_repeatedCalls() { CHECK_SOURCE_VALID; QSignalSpy spyUpdate(m_source, SIGNAL(positionUpdated(QGeoPositionInfo))); m_source->requestUpdate(20000); //Q_WAIT(spyUpdate.count(), 1, 20000); //QCOMPARE(spyUpdate.count(), 1); QTRY_COMPARE_WITH_TIMEOUT(spyUpdate.count(), 1, 20000); spyUpdate.clear(); m_source->requestUpdate(20000); //Q_WAIT(spyUpdate.count(), 1, 20000); //QCOMPARE(spyUpdate.count(),1); QTRY_COMPARE_WITH_TIMEOUT(spyUpdate.count(), 1, 20000); spyUpdate.clear(); } //TC_ID_3_x_4 void TestQGeoPositionInfoSource::requestUpdate_withUpdateInterval() { CHECK_SOURCE_VALID; QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&))); m_source->setUpdateInterval(MAX_WAITING_TIME); m_source->startUpdates(); QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, MAX_WAITING_TIME); m_source->requestUpdate(25000); QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 2, 27000); m_source->stopUpdates(); } #include "testqgeopositioninfosource.moc" <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef COIN_CHAINBLENDER_HPP #define COIN_CHAINBLENDER_HPP #include <mutex> namespace coin { /** * Implements a chainblender mechanism. */ class chainblender { public: /** * Constructor */ chainblender(); /** * The singleton accessor. */ static chainblender & instance(); private: // ... protected: /** * The std::mutex. */ static std::mutex mutex_; }; } // namespace coin #endif // COIN_CHAINBLENDER_HPP <commit_msg>chainblender partial merge<commit_after>/* * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef COIN_CHAINBLENDER_HPP #define COIN_CHAINBLENDER_HPP #include <cstdint> #include <map> #include <mutex> #include <set> #include <boost/asio.hpp> #include <coin/sha256.hpp> namespace coin { /** * Implements a chainblender mechanism. */ class chainblender { public: /** * A session. */ typedef struct { sha256 hash_id; std::int64_t denomination; std::time_t time; std::uint8_t participants; bool is_active; } session_t; /** * k */ enum { k = 8 }; /** * n */ enum { n = 2 }; /** * Constructor */ chainblender(); /** * The singleton accessor. */ static chainblender & instance(); /** * Create the denominations. */ std::set<std::int64_t> denominations(); /** * Calculates the score of a chainblender relay node. * @param ep The boost::asio::ip::tcp::endpoint. */ std::int16_t calculate_score( const boost::asio::ip::tcp::endpoint & ep ); /** * The sessions. */ std::map<sha256, session_t> & sessions(); private: /** * The sessions. */ std::map<sha256, session_t> m_sessions; protected: /** * The std::mutex. */ static std::mutex mutex_; }; } // namespace coin #endif // COIN_CHAINBLENDER_HPP <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "itkKurtosisFitFunctor.h" #include <iostream> #include <iomanip> void itk::KurtosisFitFunctor::operator()(vnl_matrix<double> & newSignal, const vnl_matrix<double> & SignalMatrix, const double & S0) { vnl_vector<double> initalGuess(2); // initialize Least Squres Function // SignalMatrix.cols() defines the number of shells points lestSquaresFunction model(SignalMatrix.cols()); model.set_bvalues(m_BValueList);// set BValue Vector e.g.: [1000, 2000, 3000] <- shell b Values // initialize Levenberg Marquardt vnl_levenberg_marquardt minimizer(model); minimizer.set_max_function_evals(1000); // Iterations minimizer.set_f_tolerance(1e-10); // Function tolerance // for each Direction calculate LSF Coeffs ADC & AKC for(unsigned int i = 0 ; i < SignalMatrix.rows(); i++) { model.set_measurements(SignalMatrix.get_row(i)); model.set_reference_measurement(S0); initalGuess.put(0, 0.f); // ADC initalGuess.put(1, 0.8f); // AKC // start Levenberg-Marquardt minimizer.minimize_without_gradient(initalGuess); const double & ADC = initalGuess.get(0); const double & AKC = initalGuess.get(1); newSignal.put(i, 0, S0 * std::exp(-m_TargetBvalue * ADC + 1./6. * m_TargetBvalue* m_TargetBvalue * ADC * ADC * AKC)); newSignal.put(i, 1, minimizer.get_end_error()); // RMS Error //OUTPUT FOR EVALUATION std::cout << std::scientific << std::setprecision(5) << initalGuess[0] << "," // fitted ADC << initalGuess[1] << "," // fitted AKC << S0 << "," // S0 value << minimizer.get_end_error() << ","; // End error for(unsigned int j = 0; j < SignalMatrix.get_row(i).size(); j++ ){ std::cout << std::scientific << std::setprecision(5) << SignalMatrix.get_row(i)[j]; // S_n Values corresponding to shell 1 to shell n if(j != SignalMatrix.get_row(i).size()-1) std::cout << ","; } std::cout << std::endl; } } <commit_msg>comment out evaluation output<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "itkKurtosisFitFunctor.h" #include <iostream> #include <iomanip> void itk::KurtosisFitFunctor::operator()(vnl_matrix<double> & newSignal, const vnl_matrix<double> & SignalMatrix, const double & S0) { vnl_vector<double> initalGuess(2); // initialize Least Squres Function // SignalMatrix.cols() defines the number of shells points lestSquaresFunction model(SignalMatrix.cols()); model.set_bvalues(m_BValueList);// set BValue Vector e.g.: [1000, 2000, 3000] <- shell b Values // initialize Levenberg Marquardt vnl_levenberg_marquardt minimizer(model); minimizer.set_max_function_evals(1000); // Iterations minimizer.set_f_tolerance(1e-10); // Function tolerance // for each Direction calculate LSF Coeffs ADC & AKC for(unsigned int i = 0 ; i < SignalMatrix.rows(); i++) { model.set_measurements(SignalMatrix.get_row(i)); model.set_reference_measurement(S0); initalGuess.put(0, 0.f); // ADC initalGuess.put(1, 0.8f); // AKC // start Levenberg-Marquardt minimizer.minimize_without_gradient(initalGuess); const double & ADC = initalGuess.get(0); const double & AKC = initalGuess.get(1); newSignal.put(i, 0, S0 * std::exp(-m_TargetBvalue * ADC + 1./6. * m_TargetBvalue* m_TargetBvalue * ADC * ADC * AKC)); newSignal.put(i, 1, minimizer.get_end_error()); // RMS Error //OUTPUT FOR EVALUATION /*std::cout << std::scientific << std::setprecision(5) << initalGuess[0] << "," // fitted ADC << initalGuess[1] << "," // fitted AKC << S0 << "," // S0 value << minimizer.get_end_error() << ","; // End error for(unsigned int j = 0; j < SignalMatrix.get_row(i).size(); j++ ){ std::cout << std::scientific << std::setprecision(5) << SignalMatrix.get_row(i)[j]; // S_n Values corresponding to shell 1 to shell n if(j != SignalMatrix.get_row(i).size()-1) std::cout << ","; } std::cout << std::endl;*/ } } <|endoftext|>