text
stringlengths
54
60.6k
<commit_before>/*=================================================================== APM_PLANNER Open Source Ground Control Station (c) 2013 APM_PLANNER PROJECT <http://www.diydrones.com> This file is part of the APM_PLANNER project APM_PLANNER 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. APM_PLANNER 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 APM_PLANNER. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ #include "OsdConfig.h" #include <QMessageBox> OsdConfig::OsdConfig(QWidget *parent) : AP2ConfigWidget(parent) { ui.setupUi(this); connect(ui.enablePushButton,SIGNAL(clicked()),this,SLOT(enableButtonClicked())); initConnections(); } OsdConfig::~OsdConfig() { } void OsdConfig::enableButtonClicked() { if (!m_uas) { showNullMAVErrorMessageBox(); return; } m_uas->getParamManager()->setParameter(1,"SR0_EXT_STAT",2); m_uas->getParamManager()->setParameter(1,"SR0_EXTRA1",10); m_uas->getParamManager()->setParameter(1,"SR0_EXTRA2",10); m_uas->getParamManager()->setParameter(1,"SR0_EXTRA3",2); m_uas->getParamManager()->setParameter(1,"SR0_POSITION",3); m_uas->getParamManager()->setParameter(1,"SR0_RAW_CTRL",2); m_uas->getParamManager()->setParameter(1,"SR0_RAW_SENS",2); m_uas->getParamManager()->setParameter(1,"SR0_RC_CHAN",2); } <commit_msg>OSD Setup: Fix to set channel rates SR1 and SR3 <commit_after>/*=================================================================== APM_PLANNER Open Source Ground Control Station (c) 2013 APM_PLANNER PROJECT <http://www.diydrones.com> This file is part of the APM_PLANNER project APM_PLANNER 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. APM_PLANNER 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 APM_PLANNER. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ #include "OsdConfig.h" #include <QMessageBox> OsdConfig::OsdConfig(QWidget *parent) : AP2ConfigWidget(parent) { ui.setupUi(this); connect(ui.enablePushButton,SIGNAL(clicked()),this,SLOT(enableButtonClicked())); initConnections(); } OsdConfig::~OsdConfig() { } void OsdConfig::enableButtonClicked() { if (!m_uas) { showNullMAVErrorMessageBox(); return; } m_uas->getParamManager()->setParameter(1,"SR0_EXT_STAT",2); m_uas->getParamManager()->setParameter(1,"SR0_EXTRA1",2); m_uas->getParamManager()->setParameter(1,"SR0_EXTRA2",2); m_uas->getParamManager()->setParameter(1,"SR0_EXTRA3",2); m_uas->getParamManager()->setParameter(1,"SR0_POSITION",2); m_uas->getParamManager()->setParameter(1,"SR0_RAW_CTRL",2); m_uas->getParamManager()->setParameter(1,"SR0_RAW_SENS",2); m_uas->getParamManager()->setParameter(1,"SR0_RC_CHAN",2); m_uas->getParamManager()->setParameter(1,"SR1_EXT_STAT",2); m_uas->getParamManager()->setParameter(1,"SR1_EXTRA1",2); m_uas->getParamManager()->setParameter(1,"SR1_EXTRA2",2); m_uas->getParamManager()->setParameter(1,"SR1_EXTRA3",2); m_uas->getParamManager()->setParameter(1,"SR1_POSITION",2); m_uas->getParamManager()->setParameter(1,"SR1_RAW_CTRL",2); m_uas->getParamManager()->setParameter(1,"SR1_RAW_SENS",2); m_uas->getParamManager()->setParameter(1,"SR1_RC_CHAN",2); m_uas->getParamManager()->setParameter(1,"SR3_EXT_STAT",2); m_uas->getParamManager()->setParameter(1,"SR3_EXTRA1",2); m_uas->getParamManager()->setParameter(1,"SR3_EXTRA2",2); m_uas->getParamManager()->setParameter(1,"SR3_EXTRA3",2); m_uas->getParamManager()->setParameter(1,"SR3_POSITION",2); m_uas->getParamManager()->setParameter(1,"SR3_RAW_CTRL",2); m_uas->getParamManager()->setParameter(1,"SR3_RAW_SENS",2); m_uas->getParamManager()->setParameter(1,"SR3_RC_CHAN",2); } <|endoftext|>
<commit_before>#include <hayai.hpp> #include <boost/format.hpp> #include <humblelogging/api.h> #include <db.h> #include <annotationsearch.h> #include <operators/precedence.h> #include <operators/inclusion.h> HUMBLE_LOGGER(logger, "default"); using namespace annis; class TigerTestFixture : public ::hayai::Fixture { public: virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/tiger2"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; class RidgesTestFixture : public ::hayai::Fixture { public: virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/ridges"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; class FallbackRidgesTestFixture : public ::hayai::Fixture { public: FallbackRidgesTestFixture() :db(false) { } virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/ridges"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; BENCHMARK_F(TigerTestFixture, Cat, 5, 1) { AnnotationNameSearch search(db, "cat"); counter=0; while(search.hasNext()) { search.next(); counter++; } } // pos="NN" & norm="Blumen" & #1 _i_ #2 BENCHMARK_F(RidgesTestFixture, PosNNIncludesNormBlumen, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "norm", "Blumen"); annis::Inclusion join(db, n1, n2); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } // pos="NN" .2,10 pos="ART" BENCHMARK_F(RidgesTestFixture, NNPreceedingART, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "pos", "ART"); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m=join.next(); m.found; m = join.next()) { counter++; } } // tok .2,10 tok BENCHMARK_F(RidgesTestFixture, TokPreceedingTok, 5, 1) { unsigned int counter=0; AnnotationNameSearch n1(db, annis::annis_ns, annis::annis_tok); AnnotationNameSearch n2(db, annis::annis_ns,annis::annis_tok); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } // pos="NN" .2,10 pos="ART" BENCHMARK_F(FallbackRidgesTestFixture, NNPreceedingART, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "pos", "ART"); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m=join.next(); m.found; m = join.next()) { counter++; } } // tok .2,10 tok BENCHMARK_F(FallbackRidgesTestFixture, TokPreceedingTok, 5, 1) { unsigned int counter=0; AnnotationNameSearch n1(db, annis::annis_ns, annis::annis_tok); AnnotationNameSearch n2(db, annis::annis_ns,annis::annis_tok); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } int main(int argc, char** argv) { humble::logging::Factory &fac = humble::logging::Factory::getInstance(); fac.setDefaultLogLevel(humble::logging::LogLevel::Info); fac.registerAppender(new humble::logging::FileAppender("benchmark_annis4.log")); hayai::ConsoleOutputter consoleOutputter; hayai::Benchmarker::AddOutputter(consoleOutputter); if(argc >= 2) { for(int i=1; i < argc; i++) { std::cout << "adding include filter" << argv[i] << std::endl; hayai::Benchmarker::AddIncludeFilter(argv[i]); } } hayai::Benchmarker::RunAllTests(); return 0; } <commit_msg>rename fixtures to make it easier to filter them<commit_after>#include <hayai.hpp> #include <boost/format.hpp> #include <humblelogging/api.h> #include <db.h> #include <annotationsearch.h> #include <operators/precedence.h> #include <operators/inclusion.h> HUMBLE_LOGGER(logger, "default"); using namespace annis; class Tiger : public ::hayai::Fixture { public: virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/tiger2"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; class Ridges : public ::hayai::Fixture { public: virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/ridges"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; class RidgesFallback : public ::hayai::Fixture { public: RidgesFallback() :db(false) { } virtual void SetUp() { char* testDataEnv = std::getenv("ANNIS4_TEST_DATA"); std::string dataDir("data"); if(testDataEnv != NULL) { dataDir = testDataEnv; } dbLoaded = db.load(dataDir + "/ridges"); counter = 0; } /// After each run, clear the vector of random integers. virtual void TearDown() { HL_INFO(logger, (boost::format("result %1%") % counter).str()); } DB db; bool dbLoaded; unsigned int counter; }; BENCHMARK_F(Tiger, Cat, 5, 1) { AnnotationNameSearch search(db, "cat"); counter=0; while(search.hasNext()) { search.next(); counter++; } } // pos="NN" & norm="Blumen" & #1 _i_ #2 BENCHMARK_F(Ridges, PosNNIncludesNormBlumen, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "norm", "Blumen"); annis::Inclusion join(db, n1, n2); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } // pos="NN" .2,10 pos="ART" BENCHMARK_F(Ridges, NNPreceedingART, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "pos", "ART"); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m=join.next(); m.found; m = join.next()) { counter++; } } // tok .2,10 tok BENCHMARK_F(Ridges, TokPreceedingTok, 5, 1) { unsigned int counter=0; AnnotationNameSearch n1(db, annis::annis_ns, annis::annis_tok); AnnotationNameSearch n2(db, annis::annis_ns,annis::annis_tok); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } // pos="NN" .2,10 pos="ART" BENCHMARK_F(RidgesFallback, NNPreceedingART, 5, 1) { AnnotationNameSearch n1(db, "default_ns", "pos", "NN"); AnnotationNameSearch n2(db, "default_ns", "pos", "ART"); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m=join.next(); m.found; m = join.next()) { counter++; } } // tok .2,10 tok BENCHMARK_F(RidgesFallback, TokPreceedingTok, 5, 1) { unsigned int counter=0; AnnotationNameSearch n1(db, annis::annis_ns, annis::annis_tok); AnnotationNameSearch n2(db, annis::annis_ns,annis::annis_tok); Precedence join(db, n1, n2, 2, 10); for(BinaryMatch m = join.next(); m.found; m = join.next()) { counter++; } } int main(int argc, char** argv) { humble::logging::Factory &fac = humble::logging::Factory::getInstance(); fac.setDefaultLogLevel(humble::logging::LogLevel::Info); fac.registerAppender(new humble::logging::FileAppender("benchmark_annis4.log")); hayai::ConsoleOutputter consoleOutputter; hayai::Benchmarker::AddOutputter(consoleOutputter); if(argc >= 2) { for(int i=1; i < argc; i++) { std::cout << "adding include filter" << argv[i] << std::endl; hayai::Benchmarker::AddIncludeFilter(argv[i]); } } hayai::Benchmarker::RunAllTests(); return 0; } <|endoftext|>
<commit_before>#include "test_sample.hpp" #include <SRDelegate/SRDelegate.hpp> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(SRDelegate_Cpp11) BOOST_AUTO_TEST_CASE(custom) { auto inlineFreeFuncA_3 = generic::delegate<void(void)>(&rawInlineFreeFuncNoParamA); auto inlineFreeFuncA_4 = generic::delegate<void(void)>(&rawInlineFreeFuncNoParamA); auto singleInheritStaticmemFuncNoParamA_1 = generic::delegate<void(void)>::from(&SingleInheritBaseClass::rawStaticMemFuncNoParamA); auto singleInheritStaticmemFuncNoParamA_2 = generic::delegate<void(void)>(&SingleInheritBaseClass::rawStaticMemFuncNoParamA); BOOST_CHECK(inlineFreeFuncA_3 != singleInheritStaticmemFuncNoParamA_1); BOOST_CHECK(inlineFreeFuncA_3 != singleInheritStaticmemFuncNoParamA_2); BOOST_CHECK(singleInheritStaticmemFuncNoParamA_1 == singleInheritStaticmemFuncNoParamA_2); auto inlineFreeFuncB_1 = generic::delegate<void(void)>(&rawInlineFreeFuncNoParamB); BOOST_CHECK(inlineFreeFuncA_3 != inlineFreeFuncB_1); } BOOST_AUTO_TEST_CASE(inlineFreeFuncWithParam) { auto inlineFreeFuncA_1 = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamA>(); auto inlineFreeFuncA_2 = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamA>(); BOOST_CHECK(inlineFreeFuncA_1 == inlineFreeFuncA_2); auto inlineFreeFuncParamA_1 = generic::delegate<void(EventSPtr)>(&rawInlineFreeFuncWithParamA); auto inlineFreeFuncParamA_2 = generic::delegate<void(EventSPtr)>(&rawInlineFreeFuncWithParamA); auto inlineFreeFuncParamB_1 = generic::delegate<void(EventSPtr)>(&rawInlineFreeFuncWithParamB); BOOST_CHECK(inlineFreeFuncParamA_1 == inlineFreeFuncParamA_2); BOOST_CHECK(inlineFreeFuncParamA_1 != inlineFreeFuncParamB_1); auto inlineFreeFuncA_3 = generic::delegate<void(void)>(&rawInlineFreeFuncNoParamA); auto inlineFreeFuncA_4 = generic::delegate<void(void)>(&rawInlineFreeFuncNoParamA); generic::delegate<void(void)> inlineFreeFuncA_5 = &rawInlineFreeFuncNoParamA; auto inlineFreeFuncA_6 = generic::delegate<void(void)>::from(&rawInlineFreeFuncNoParamA); BOOST_CHECK(inlineFreeFuncA_1 == inlineFreeFuncA_3); BOOST_CHECK(inlineFreeFuncA_3 == inlineFreeFuncA_4); BOOST_CHECK(inlineFreeFuncA_3 == inlineFreeFuncA_5); BOOST_CHECK(inlineFreeFuncA_1 == inlineFreeFuncA_6); BOOST_CHECK(inlineFreeFuncA_3 == inlineFreeFuncA_6); } BOOST_AUTO_TEST_CASE(equality_freeFuncNoParam) { auto freeFuncA_1 = generic::delegate<void(void)>::from<&rawFreeFuncNoParamA>(); auto freeFuncA_2 = generic::delegate<void(void)>::from<&rawFreeFuncNoParamA>(); BOOST_CHECK(freeFuncA_1 == freeFuncA_2); auto inlineFreeFuncA_1 = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamA>(); auto inlineFreeFuncA_2 = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamA>(); BOOST_CHECK(inlineFreeFuncA_1 == inlineFreeFuncA_2); auto inlineFreeFuncParamA_1 = generic::delegate<void(EventSPtr)>::from<&rawInlineFreeFuncWithParamA>(); auto inlineFreeFuncParamA_2 = generic::delegate<void(EventSPtr)>::from<&rawInlineFreeFuncWithParamA>(); BOOST_CHECK(inlineFreeFuncParamA_1 == inlineFreeFuncParamA_2); } BOOST_AUTO_TEST_CASE(inequality_freeFuncNoParam) { auto freeFuncA = generic::delegate<void(void)>::from<&rawFreeFuncNoParamA>(); auto freeFuncB = generic::delegate<void(void)>::from<&rawFreeFuncNoParamB>(); BOOST_CHECK(freeFuncA != freeFuncB); auto inlineFreeFuncA = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamA>(); auto inlineFreeFuncB = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamB>(); BOOST_CHECK(inlineFreeFuncA != inlineFreeFuncB); auto inlineFreeFuncParamA = generic::delegate<void(EventSPtr)>::from<&rawInlineFreeFuncWithParamA>(); auto inlineFreeFuncParamB = generic::delegate<void(EventSPtr)>::from<&rawInlineFreeFuncWithParamB>(); BOOST_CHECK(inlineFreeFuncParamA != inlineFreeFuncParamB); } BOOST_AUTO_TEST_CASE(lambda) { generic::delegate<void(void)> lambda_1([](){ int i = 1 + 1; return; }); generic::delegate<void(void)> lambda_2([](){ int i = 1 + 1; return; }); auto lambda_3 = generic::delegate<void(void)>::from([](){ return; }); generic::delegate<void(void)> lambda_4 = [](){ int i = 1 + 1; return; }; BOOST_CHECK(lambda_1 != lambda_2); BOOST_CHECK(lambda_1 != lambda_3); BOOST_CHECK(lambda_1 != lambda_4); } BOOST_AUTO_TEST_CASE(equality_staticMemFuncNoParam) { auto singleInheritStaticmemFuncNoParamA_1 = generic::delegate<void(void)>::from<&SingleInheritBaseClass::rawStaticMemFuncNoParamA>(); auto singleInheritStaticmemFuncNoParamA_2 = generic::delegate<void(void)>::from<&SingleInheritBaseClass::rawStaticMemFuncNoParamA>(); BOOST_CHECK(singleInheritStaticmemFuncNoParamA_1 == singleInheritStaticmemFuncNoParamA_2); } BOOST_AUTO_TEST_CASE(inequality_staticMemFuncNoParam) { auto singleInheritStaticmemFuncNoParamA = generic::delegate<void(void)>::from<&SingleInheritBaseClass::rawStaticMemFuncNoParamA>(); auto singleInheritStaticmemFuncNoParamB = generic::delegate<void(void)>::from<&SingleInheritBaseClass::rawStaticMemFuncNoParamB>(); BOOST_CHECK(singleInheritStaticmemFuncNoParamA != singleInheritStaticmemFuncNoParamB); } BOOST_AUTO_TEST_CASE(equality_memFunc) { SingleInheritBaseClass single_inhert_base_obj; auto singleInheritBMemFuncA_1 = generic::delegate<void(void)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncNoParamA>(&single_inhert_base_obj); auto singleInheritBMemFuncA_2 = generic::delegate<void(void)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncNoParamA>(&single_inhert_base_obj); BOOST_CHECK(singleInheritBMemFuncA_1 == singleInheritBMemFuncA_2); auto singleInheritBMemFuncParamA_1 = generic::delegate<void(EventSPtr)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncWithParamA>(&single_inhert_base_obj); auto singleInheritBMemFuncParamA_2 = generic::delegate<void(EventSPtr)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncWithParamA>(&single_inhert_base_obj); BOOST_CHECK(singleInheritBMemFuncParamA_1 == singleInheritBMemFuncParamA_2); SingleInheritClass single_inhert_obj; auto singleInheritMemFuncA_1 = generic::delegate<void(void)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncNoParamA>(&single_inhert_obj); auto singleInheritMemFuncA_2 = generic::delegate<void(void)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncNoParamA>(&single_inhert_obj); BOOST_CHECK(singleInheritMemFuncA_1 == singleInheritMemFuncA_2); auto singleInheritMemFuncParamA_1 = generic::delegate<void(EventSPtr)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncWithParamA>(&single_inhert_obj); auto singleInheritMemFuncParamA_2 = generic::delegate<void(EventSPtr)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncWithParamA>(&single_inhert_obj); BOOST_CHECK(singleInheritMemFuncParamA_1 == singleInheritMemFuncParamA_2); } BOOST_AUTO_TEST_CASE(inequality_memFunc) { SingleInheritBaseClass single_inhert_base_obj; auto singleInheritBMemFuncA = generic::delegate<void(void)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncNoParamA>(&single_inhert_base_obj); auto singleInheritBMemFuncB = generic::delegate<void(void)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncNoParamB>(&single_inhert_base_obj); BOOST_CHECK(singleInheritBMemFuncA != singleInheritBMemFuncB); auto singleInheritBMemFuncParamA = generic::delegate<void(EventSPtr)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncWithParamA>(&single_inhert_base_obj); auto singleInheritBMemFuncParamB = generic::delegate<void(EventSPtr)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncWithParamB>(&single_inhert_base_obj); BOOST_CHECK(singleInheritBMemFuncParamA != singleInheritBMemFuncParamB); SingleInheritClass single_inhert_obj; auto singleInheritMemFuncA = generic::delegate<void(void)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncNoParamA>(&single_inhert_obj); auto singleInheritMemFuncB = generic::delegate<void(void)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncNoParamB>(&single_inhert_obj); BOOST_CHECK(singleInheritMemFuncA != singleInheritMemFuncB); auto singleInheritMemFuncParamA = generic::delegate<void(EventSPtr)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncWithParamA>(&single_inhert_obj); auto singleInheritMemFuncParamB = generic::delegate<void(EventSPtr)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncWithParamB>(&single_inhert_obj); BOOST_CHECK(singleInheritMemFuncParamA != singleInheritMemFuncParamB); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>add more test case<commit_after>#include "test_sample.hpp" #include <SRDelegate/SRDelegate.hpp> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(SRDelegate_Cpp11) BOOST_AUTO_TEST_CASE(custom) { auto inlineFreeFuncA_3 = generic::delegate<void(void)>(&rawInlineFreeFuncNoParamA); auto inlineFreeFuncA_4 = generic::delegate<void(void)>(&rawInlineFreeFuncNoParamA); auto singleInheritStaticmemFuncNoParamA_1 = generic::delegate<void(void)>::from(&SingleInheritBaseClass::rawStaticMemFuncNoParamA); auto singleInheritStaticmemFuncNoParamA_2 = generic::delegate<void(void)>(&SingleInheritBaseClass::rawStaticMemFuncNoParamA); BOOST_CHECK(inlineFreeFuncA_3 != singleInheritStaticmemFuncNoParamA_1); BOOST_CHECK(inlineFreeFuncA_3 != singleInheritStaticmemFuncNoParamA_2); BOOST_CHECK(singleInheritStaticmemFuncNoParamA_1 == singleInheritStaticmemFuncNoParamA_2); auto inlineFreeFuncB_1 = generic::delegate<void(void)>(&rawInlineFreeFuncNoParamB); BOOST_CHECK(inlineFreeFuncA_3 != inlineFreeFuncB_1); } BOOST_AUTO_TEST_CASE(inlineFreeFuncWithParam) { auto inlineFreeFuncA_1 = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamA>(); auto inlineFreeFuncA_2 = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamA>(); BOOST_CHECK(inlineFreeFuncA_1 == inlineFreeFuncA_2); BOOST_CHECK(inlineFreeFuncA_2 == inlineFreeFuncA_1); auto inlineFreeFuncParamA_1 = generic::delegate<void(EventSPtr)>(&rawInlineFreeFuncWithParamA); auto inlineFreeFuncParamA_2 = generic::delegate<void(EventSPtr)>(&rawInlineFreeFuncWithParamA); auto inlineFreeFuncParamB_1 = generic::delegate<void(EventSPtr)>(&rawInlineFreeFuncWithParamB); BOOST_CHECK(inlineFreeFuncParamA_1 == inlineFreeFuncParamA_2); BOOST_CHECK(inlineFreeFuncParamA_2 == inlineFreeFuncParamA_1); BOOST_CHECK(inlineFreeFuncParamA_1 != inlineFreeFuncParamB_1); BOOST_CHECK(inlineFreeFuncParamB_1 != inlineFreeFuncParamA_1); auto inlineFreeFuncA_3 = generic::delegate<void(void)>(&rawInlineFreeFuncNoParamA); auto inlineFreeFuncA_4 = generic::delegate<void(void)>(&rawInlineFreeFuncNoParamA); generic::delegate<void(void)> inlineFreeFuncA_5 = &rawInlineFreeFuncNoParamA; auto inlineFreeFuncA_6 = generic::delegate<void(void)>::from(&rawInlineFreeFuncNoParamA); BOOST_CHECK(inlineFreeFuncA_1 == inlineFreeFuncA_3); BOOST_CHECK(inlineFreeFuncA_3 == inlineFreeFuncA_4); BOOST_CHECK(inlineFreeFuncA_3 == inlineFreeFuncA_5); BOOST_CHECK(inlineFreeFuncA_1 == inlineFreeFuncA_6); BOOST_CHECK(inlineFreeFuncA_3 == inlineFreeFuncA_6); } BOOST_AUTO_TEST_CASE(equality_freeFuncNoParam) { auto freeFuncA_1 = generic::delegate<void(void)>::from<&rawFreeFuncNoParamA>(); auto freeFuncA_2 = generic::delegate<void(void)>::from<&rawFreeFuncNoParamA>(); BOOST_CHECK(freeFuncA_1 == freeFuncA_2); auto inlineFreeFuncA_1 = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamA>(); auto inlineFreeFuncA_2 = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamA>(); BOOST_CHECK(inlineFreeFuncA_1 == inlineFreeFuncA_2); auto inlineFreeFuncParamA_1 = generic::delegate<void(EventSPtr)>::from<&rawInlineFreeFuncWithParamA>(); auto inlineFreeFuncParamA_2 = generic::delegate<void(EventSPtr)>::from<&rawInlineFreeFuncWithParamA>(); BOOST_CHECK(inlineFreeFuncParamA_1 == inlineFreeFuncParamA_2); } BOOST_AUTO_TEST_CASE(inequality_freeFuncNoParam) { auto freeFuncA = generic::delegate<void(void)>::from<&rawFreeFuncNoParamA>(); auto freeFuncB = generic::delegate<void(void)>::from<&rawFreeFuncNoParamB>(); BOOST_CHECK(freeFuncA != freeFuncB); auto inlineFreeFuncA = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamA>(); auto inlineFreeFuncB = generic::delegate<void(void)>::from<&rawInlineFreeFuncNoParamB>(); BOOST_CHECK(inlineFreeFuncA != inlineFreeFuncB); auto inlineFreeFuncParamA = generic::delegate<void(EventSPtr)>::from<&rawInlineFreeFuncWithParamA>(); auto inlineFreeFuncParamB = generic::delegate<void(EventSPtr)>::from<&rawInlineFreeFuncWithParamB>(); BOOST_CHECK(inlineFreeFuncParamA != inlineFreeFuncParamB); } BOOST_AUTO_TEST_CASE(lambda) { generic::delegate<void(void)> lambda_1([](){ int i = 1 + 1; return; }); generic::delegate<void(void)> lambda_2([](){ int i = 1 + 1; return; }); auto lambda_3 = generic::delegate<void(void)>::from([](){ return; }); generic::delegate<void(void)> lambda_4 = [](){ int i = 1 + 1; return; }; BOOST_CHECK(lambda_1 != lambda_2); BOOST_CHECK(lambda_1 != lambda_3); BOOST_CHECK(lambda_1 != lambda_4); } BOOST_AUTO_TEST_CASE(equality_staticMemFuncNoParam) { auto singleInheritStaticmemFuncNoParamA_1 = generic::delegate<void(void)>::from<&SingleInheritBaseClass::rawStaticMemFuncNoParamA>(); auto singleInheritStaticmemFuncNoParamA_2 = generic::delegate<void(void)>::from<&SingleInheritBaseClass::rawStaticMemFuncNoParamA>(); BOOST_CHECK(singleInheritStaticmemFuncNoParamA_1 == singleInheritStaticmemFuncNoParamA_2); } BOOST_AUTO_TEST_CASE(inequality_staticMemFuncNoParam) { auto singleInheritStaticmemFuncNoParamA = generic::delegate<void(void)>::from<&SingleInheritBaseClass::rawStaticMemFuncNoParamA>(); auto singleInheritStaticmemFuncNoParamB = generic::delegate<void(void)>::from<&SingleInheritBaseClass::rawStaticMemFuncNoParamB>(); BOOST_CHECK(singleInheritStaticmemFuncNoParamA != singleInheritStaticmemFuncNoParamB); } BOOST_AUTO_TEST_CASE(equality_memFunc) { SingleInheritBaseClass single_inhert_base_obj; auto singleInheritBMemFuncA_1 = generic::delegate<void(void)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncNoParamA>(&single_inhert_base_obj); auto singleInheritBMemFuncA_2 = generic::delegate<void(void)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncNoParamA>(&single_inhert_base_obj); BOOST_CHECK(singleInheritBMemFuncA_1 == singleInheritBMemFuncA_2); auto singleInheritBMemFuncParamA_1 = generic::delegate<void(EventSPtr)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncWithParamA>(&single_inhert_base_obj); auto singleInheritBMemFuncParamA_2 = generic::delegate<void(EventSPtr)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncWithParamA>(&single_inhert_base_obj); BOOST_CHECK(singleInheritBMemFuncParamA_1 == singleInheritBMemFuncParamA_2); SingleInheritClass single_inhert_obj; auto singleInheritMemFuncA_1 = generic::delegate<void(void)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncNoParamA>(&single_inhert_obj); auto singleInheritMemFuncA_2 = generic::delegate<void(void)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncNoParamA>(&single_inhert_obj); BOOST_CHECK(singleInheritMemFuncA_1 == singleInheritMemFuncA_2); auto singleInheritMemFuncParamA_1 = generic::delegate<void(EventSPtr)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncWithParamA>(&single_inhert_obj); auto singleInheritMemFuncParamA_2 = generic::delegate<void(EventSPtr)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncWithParamA>(&single_inhert_obj); BOOST_CHECK(singleInheritMemFuncParamA_1 == singleInheritMemFuncParamA_2); } BOOST_AUTO_TEST_CASE(inequality_memFunc) { SingleInheritBaseClass single_inhert_base_obj; auto singleInheritBMemFuncA = generic::delegate<void(void)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncNoParamA>(&single_inhert_base_obj); auto singleInheritBMemFuncB = generic::delegate<void(void)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncNoParamB>(&single_inhert_base_obj); BOOST_CHECK(singleInheritBMemFuncA != singleInheritBMemFuncB); auto singleInheritBMemFuncParamA = generic::delegate<void(EventSPtr)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncWithParamA>(&single_inhert_base_obj); auto singleInheritBMemFuncParamB = generic::delegate<void(EventSPtr)>::from<SingleInheritBaseClass, &SingleInheritBaseClass::rawMemFuncWithParamB>(&single_inhert_base_obj); BOOST_CHECK(singleInheritBMemFuncParamA != singleInheritBMemFuncParamB); SingleInheritClass single_inhert_obj; auto singleInheritMemFuncA = generic::delegate<void(void)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncNoParamA>(&single_inhert_obj); auto singleInheritMemFuncB = generic::delegate<void(void)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncNoParamB>(&single_inhert_obj); BOOST_CHECK(singleInheritMemFuncA != singleInheritMemFuncB); auto singleInheritMemFuncParamA = generic::delegate<void(EventSPtr)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncWithParamA>(&single_inhert_obj); auto singleInheritMemFuncParamB = generic::delegate<void(EventSPtr)>::from<SingleInheritClass, &SingleInheritClass::rawMemFuncWithParamB>(&single_inhert_obj); BOOST_CHECK(singleInheritMemFuncParamA != singleInheritMemFuncParamB); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>//============================================================================= // File: dw_mime.cpp // Contents: Various functions // Maintainer: Doug Sauder <dwsauder@fwb.gulf.net> // WWW: http://www.fwb.gulf.net/~dwsauder/mimepp.html // $Revision$ // $Date$ // // Copyright (c) 1996, 1997 Douglas W. Sauder // All rights reserved. // // IN NO EVENT SHALL DOUGLAS W. SAUDER BE LIABLE TO ANY PARTY FOR DIRECT, // INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF // THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF DOUGLAS W. SAUDER // HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // DOUGLAS W. SAUDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT // NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" // BASIS, AND DOUGLAS W. SAUDER HAS NO OBLIGATION TO PROVIDE MAINTENANCE, // SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. // //============================================================================= #define DW_IMPLEMENTATION #include <mimelib/config.h> #include <mimelib/debug.h> #include <mimelib/string.h> #include <mimelib/msgcmp.h> #include <mimelib/enum.h> #include <mimelib/utility.h> void DwInitialize() { } void DwFinalize() { } int DwCteStrToEnum(const DwString& aStr) { int cte = DwMime::kCteUnknown; int ch = aStr[0]; switch (ch) { case '7': if( DwStrcasecmp(aStr, "7bit") == 0 ) { cte = DwMime::kCte7bit; } break; case '8': if (DwStrcasecmp(aStr, "8bit") == 0) { cte = DwMime::kCte8bit; } break; case 'B': case 'b': if (DwStrcasecmp(aStr, "base64") == 0) { cte = DwMime::kCteBase64; } else if (DwStrcasecmp(aStr, "binary") == 0) { cte = DwMime::kCteBinary; } break; case 'Q': case 'q': if (DwStrcasecmp(aStr, "quoted-printable") == 0) { cte = DwMime::kCteQuotedPrintable; } break; } return cte; } void DwCteEnumToStr(int aEnum, DwString& aStr) { switch (aEnum) { case DwMime::kCte7bit: aStr = "7bit"; break; case DwMime::kCte8bit: aStr = "8bit"; break; case DwMime::kCteBinary: aStr = "binary"; break; case DwMime::kCteBase64: aStr = "base64"; break; case DwMime::kCteQuotedPrintable: aStr = "quoted-printable"; break; } } int DwTypeStrToEnum(const DwString& aStr) { int type = DwMime::kTypeUnknown; int ch = aStr[0]; switch (ch) { case 'A': case 'a': if (DwStrcasecmp(aStr, "application") == 0) { type = DwMime::kTypeApplication; } else if (DwStrcasecmp(aStr, "audio") == 0) { type = DwMime::kTypeAudio; } break; case 'I': case 'i': if (DwStrcasecmp(aStr, "image") == 0) { type = DwMime::kTypeImage; } break; case 'M': case 'm': if (DwStrcasecmp(aStr, "message") == 0) { type = DwMime::kTypeMessage; } else if (DwStrcasecmp(aStr, "multipart") == 0) { type = DwMime::kTypeMultipart; } break; case 'T': case 't': if (DwStrcasecmp(aStr, "text") == 0) { type = DwMime::kTypeText; } break; case 'V': case 'v': if (DwStrcasecmp(aStr, "video") == 0) { type = DwMime::kTypeVideo; } break; case 0: type = DwMime::kTypeNull; break; } return type; } void DwTypeEnumToStr(int aEnum, DwString& aStr) { switch (aEnum) { case DwMime::kTypeNull: aStr = ""; break; case DwMime::kTypeUnknown: default: aStr = "Unknown"; break; case DwMime::kTypeText: aStr = "Text"; break; case DwMime::kTypeMultipart: aStr = "Multipart"; break; case DwMime::kTypeMessage: aStr = "Message"; break; case DwMime::kTypeApplication: aStr = "Application"; break; case DwMime::kTypeImage: aStr = "Image"; break; case DwMime::kTypeAudio: aStr = "Audio"; break; case DwMime::kTypeVideo: aStr = "Video"; break; case DwMime::kTypeModel: aStr = "Model"; break; } } int DwSubtypeStrToEnum(const DwString& aStr) { if (aStr.empty()) { return DwMime::kSubtypeNull; } int type = DwMime::kSubtypeUnknown; int ch = aStr[0]; switch (ch) { case 'A': case 'a': if (DwStrcasecmp(aStr, "alternative") == 0) { type = DwMime::kSubtypeAlternative; } break; case 'B': case 'b': if (DwStrcasecmp(aStr, "basic") == 0) { type = DwMime::kSubtypeBasic; } break; case 'C': case 'c': if (DwStrcasecmp(aStr, "calendar") == 0) { type = DwMime::kSubtypeVCal; } break; case 'D': case 'd': if (DwStrcasecmp(aStr, "digest") == 0) { type = DwMime::kSubtypeDigest; } else if (DwStrcasecmp(aStr, "disposition-notification") == 0 ) { type = DwMime::kSubtypeDispositionNotification; } break; case 'E': case 'e': if (DwStrcasecmp(aStr, "enriched") == 0) { type = DwMime::kSubtypeEnriched; } else if (DwStrcasecmp(aStr, "external-body") == 0) { type = DwMime::kSubtypeExternalBody; } else if (DwStrcasecmp(aStr, "encrypted") == 0) { type = DwMime::kSubtypeEncrypted; } break; case 'G': case 'g': if (DwStrcasecmp(aStr, "gif") == 0) { type = DwMime::kSubtypeGif; } break; case 'H': case 'h': if (DwStrcasecmp(aStr, "html") == 0) { type = DwMime::kSubtypeHtml; } break; case 'J': case 'j': if (DwStrcasecmp(aStr, "jpeg") == 0) { type = DwMime::kSubtypeJpeg; } break; case 'M': case 'm': if (DwStrcasecmp(aStr, "mixed") == 0) { type = DwMime::kSubtypeMixed; } else if (DwStrcasecmp(aStr, "mpeg") == 0) { type = DwMime::kSubtypeMpeg; } else if (DwStrcasecmp(aStr, "ms-tnef") == 0) { type = DwMime::kSubtypeMsTNEF; } break; case 'O': case 'o': if (DwStrcasecmp(aStr, "octet-stream") == 0) { type = DwMime::kSubtypeOctetStream; } break; case 'P': case 'p': if (DwStrcasecmp(aStr, "plain") == 0) { type = DwMime::kSubtypePlain; } else if (DwStrcasecmp(aStr, "parallel") == 0) { type = DwMime::kSubtypeParallel; } else if (DwStrcasecmp(aStr, "partial") == 0) { type = DwMime::kSubtypePartial; } else if (DwStrcasecmp(aStr, "postscript") == 0) { type = DwMime::kSubtypePostscript; } else if (DwStrcasecmp(aStr, "pgp-signature") == 0) { type = DwMime::kSubtypePgpSignature; } else if (DwStrcasecmp(aStr, "pgp-encrypted") == 0) { type = DwMime::kSubtypePgpEncrypted; } else if (DwStrcasecmp(aStr, "pgp") == 0) { type = DwMime::kSubtypePgpClearsigned; } else if (DwStrcasecmp(aStr, "pkcs7-signature") == 0) { type = DwMime::kSubtypePkcs7Signature; } else if (DwStrcasecmp(aStr, "pkcs7-mime") == 0) { type = DwMime::kSubtypePkcs7Mime; } break; case 'R': case 'r': if (DwStrcasecmp(aStr, "richtext") == 0) { type = DwMime::kSubtypeRichtext; } else if (DwStrcasecmp(aStr, "rfc822") == 0) { type = DwMime::kSubtypeRfc822; } else if (DwStrcasecmp(aStr, "report") == 0) { type = DwMime::kSubtypeReport; } else if (DwStrcasecmp(aStr, "rtf") == 0) { type = DwMime::kSubtypeRtf; } else if (DwStrcasecmp(aStr, "related") == 0) { type = DwMime::kSubtypeRelated; } break; case 'S': case 's': if (DwStrcasecmp(aStr, "signed") == 0) { type = DwMime::kSubtypeSigned; } break; case 'X': case 'x': if (DwStrcasecmp(aStr, "x-vcard") == 0) { type = DwMime::kSubtypeXVCard; } else if (DwStrcasecmp(aStr, "x-pkcs7-signature") == 0) { type = DwMime::kSubtypePkcs7Signature; } else if (DwStrcasecmp(aStr, "x-pkcs7-mime") == 0) { type = DwMime::kSubtypePkcs7Mime; } if (DwStrcasecmp(aStr, "x-diff") == 0) { type = DwMime::kSubtypeXDiff; } break; } return type; } void DwSubtypeEnumToStr(int aEnum, DwString& aStr) { switch (aEnum) { case DwMime::kSubtypeNull: aStr = ""; break; case DwMime::kSubtypeUnknown: default: aStr = "Unknown"; break; case DwMime::kSubtypePlain: aStr = "Plain"; break; case DwMime::kSubtypeRichtext: aStr = "Richtext"; break; case DwMime::kSubtypeEnriched: aStr = "Enriched"; break; case DwMime::kSubtypeHtml: aStr = "HTML"; break; case DwMime::kSubtypeVCal: aStr = "Calendar"; break; case DwMime::kSubtypeXVCard: aStr = "X-VCard"; break; case DwMime::kSubtypeXDiff: aStr = "X-Diff"; break; case DwMime::kSubtypeRtf: aStr = "RTF"; break; case DwMime::kSubtypeMixed: aStr = "Mixed"; break; case DwMime::kSubtypeSigned: aStr = "Signed"; break; case DwMime::kSubtypeEncrypted: aStr = "Encrypted"; break; case DwMime::kSubtypeAlternative: aStr = "Alternative"; break; case DwMime::kSubtypeDigest: aStr = "Digest"; break; case DwMime::kSubtypeParallel: aStr = "Parallel"; break; case DwMime::kSubtypeReport: aStr = "report"; break; case DwMime::kSubtypeRelated: aStr = "Related"; break; case DwMime::kSubtypeRfc822: aStr = "Rfc822"; break; case DwMime::kSubtypeDispositionNotification: aStr = "disposition-notification"; break; case DwMime::kSubtypePartial: aStr = "Partial"; break; case DwMime::kSubtypeExternalBody: aStr = "External-body"; break; case DwMime::kSubtypePostscript: aStr = "Postscript"; break; case DwMime::kSubtypeOctetStream: aStr = "Octet-stream"; break; case DwMime::kSubtypePgpSignature: aStr = "pgp-signature"; break; case DwMime::kSubtypePgpEncrypted: aStr = "pgp-encrypted"; break; case DwMime::kSubtypePgpClearsigned: aStr = "pgp"; break; case DwMime::kSubtypePkcs7Signature: aStr = "pkcs7-signature"; break; case DwMime::kSubtypePkcs7Mime: aStr = "pkcs7-mime"; break; case DwMime::kSubtypeMsTNEF: aStr = "ms-tnef"; break; case DwMime::kSubtypeJpeg: aStr = "jpeg"; break; case DwMime::kSubtypeGif: aStr = "gif"; break; case DwMime::kSubtypeBasic: aStr = "basic"; break; case DwMime::kSubtypeMpeg: aStr = "mpeg"; break; } } <commit_msg>Teach mimelib about chiasmus.<commit_after>//============================================================================= // File: dw_mime.cpp // Contents: Various functions // Maintainer: Doug Sauder <dwsauder@fwb.gulf.net> // WWW: http://www.fwb.gulf.net/~dwsauder/mimepp.html // $Revision$ // $Date$ // // Copyright (c) 1996, 1997 Douglas W. Sauder // All rights reserved. // // IN NO EVENT SHALL DOUGLAS W. SAUDER BE LIABLE TO ANY PARTY FOR DIRECT, // INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF // THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF DOUGLAS W. SAUDER // HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // DOUGLAS W. SAUDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT // NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" // BASIS, AND DOUGLAS W. SAUDER HAS NO OBLIGATION TO PROVIDE MAINTENANCE, // SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. // //============================================================================= #define DW_IMPLEMENTATION #include <mimelib/config.h> #include <mimelib/debug.h> #include <mimelib/string.h> #include <mimelib/msgcmp.h> #include <mimelib/enum.h> #include <mimelib/utility.h> void DwInitialize() { } void DwFinalize() { } int DwCteStrToEnum(const DwString& aStr) { int cte = DwMime::kCteUnknown; int ch = aStr[0]; switch (ch) { case '7': if( DwStrcasecmp(aStr, "7bit") == 0 ) { cte = DwMime::kCte7bit; } break; case '8': if (DwStrcasecmp(aStr, "8bit") == 0) { cte = DwMime::kCte8bit; } break; case 'B': case 'b': if (DwStrcasecmp(aStr, "base64") == 0) { cte = DwMime::kCteBase64; } else if (DwStrcasecmp(aStr, "binary") == 0) { cte = DwMime::kCteBinary; } break; case 'Q': case 'q': if (DwStrcasecmp(aStr, "quoted-printable") == 0) { cte = DwMime::kCteQuotedPrintable; } break; } return cte; } void DwCteEnumToStr(int aEnum, DwString& aStr) { switch (aEnum) { case DwMime::kCte7bit: aStr = "7bit"; break; case DwMime::kCte8bit: aStr = "8bit"; break; case DwMime::kCteBinary: aStr = "binary"; break; case DwMime::kCteBase64: aStr = "base64"; break; case DwMime::kCteQuotedPrintable: aStr = "quoted-printable"; break; } } int DwTypeStrToEnum(const DwString& aStr) { int type = DwMime::kTypeUnknown; int ch = aStr[0]; switch (ch) { case 'A': case 'a': if (DwStrcasecmp(aStr, "application") == 0) { type = DwMime::kTypeApplication; } else if (DwStrcasecmp(aStr, "audio") == 0) { type = DwMime::kTypeAudio; } break; case 'I': case 'i': if (DwStrcasecmp(aStr, "image") == 0) { type = DwMime::kTypeImage; } break; case 'M': case 'm': if (DwStrcasecmp(aStr, "message") == 0) { type = DwMime::kTypeMessage; } else if (DwStrcasecmp(aStr, "multipart") == 0) { type = DwMime::kTypeMultipart; } break; case 'T': case 't': if (DwStrcasecmp(aStr, "text") == 0) { type = DwMime::kTypeText; } break; case 'V': case 'v': if (DwStrcasecmp(aStr, "video") == 0) { type = DwMime::kTypeVideo; } break; case 0: type = DwMime::kTypeNull; break; } return type; } void DwTypeEnumToStr(int aEnum, DwString& aStr) { switch (aEnum) { case DwMime::kTypeNull: aStr = ""; break; case DwMime::kTypeUnknown: default: aStr = "Unknown"; break; case DwMime::kTypeText: aStr = "Text"; break; case DwMime::kTypeMultipart: aStr = "Multipart"; break; case DwMime::kTypeMessage: aStr = "Message"; break; case DwMime::kTypeApplication: aStr = "Application"; break; case DwMime::kTypeImage: aStr = "Image"; break; case DwMime::kTypeAudio: aStr = "Audio"; break; case DwMime::kTypeVideo: aStr = "Video"; break; case DwMime::kTypeModel: aStr = "Model"; break; } } int DwSubtypeStrToEnum(const DwString& aStr) { if (aStr.empty()) { return DwMime::kSubtypeNull; } int type = DwMime::kSubtypeUnknown; int ch = aStr[0]; switch (ch) { case 'A': case 'a': if (DwStrcasecmp(aStr, "alternative") == 0) { type = DwMime::kSubtypeAlternative; } break; case 'B': case 'b': if (DwStrcasecmp(aStr, "basic") == 0) { type = DwMime::kSubtypeBasic; } break; case 'C': case 'c': if (DwStrcasecmp(aStr, "calendar") == 0) { type = DwMime::kSubtypeVCal; } break; case 'D': case 'd': if (DwStrcasecmp(aStr, "digest") == 0) { type = DwMime::kSubtypeDigest; } else if (DwStrcasecmp(aStr, "disposition-notification") == 0 ) { type = DwMime::kSubtypeDispositionNotification; } break; case 'E': case 'e': if (DwStrcasecmp(aStr, "enriched") == 0) { type = DwMime::kSubtypeEnriched; } else if (DwStrcasecmp(aStr, "external-body") == 0) { type = DwMime::kSubtypeExternalBody; } else if (DwStrcasecmp(aStr, "encrypted") == 0) { type = DwMime::kSubtypeEncrypted; } break; case 'G': case 'g': if (DwStrcasecmp(aStr, "gif") == 0) { type = DwMime::kSubtypeGif; } break; case 'H': case 'h': if (DwStrcasecmp(aStr, "html") == 0) { type = DwMime::kSubtypeHtml; } break; case 'J': case 'j': if (DwStrcasecmp(aStr, "jpeg") == 0) { type = DwMime::kSubtypeJpeg; } break; case 'M': case 'm': if (DwStrcasecmp(aStr, "mixed") == 0) { type = DwMime::kSubtypeMixed; } else if (DwStrcasecmp(aStr, "mpeg") == 0) { type = DwMime::kSubtypeMpeg; } else if (DwStrcasecmp(aStr, "ms-tnef") == 0) { type = DwMime::kSubtypeMsTNEF; } break; case 'O': case 'o': if (DwStrcasecmp(aStr, "octet-stream") == 0) { type = DwMime::kSubtypeOctetStream; } break; case 'P': case 'p': if (DwStrcasecmp(aStr, "plain") == 0) { type = DwMime::kSubtypePlain; } else if (DwStrcasecmp(aStr, "parallel") == 0) { type = DwMime::kSubtypeParallel; } else if (DwStrcasecmp(aStr, "partial") == 0) { type = DwMime::kSubtypePartial; } else if (DwStrcasecmp(aStr, "postscript") == 0) { type = DwMime::kSubtypePostscript; } else if (DwStrcasecmp(aStr, "pgp-signature") == 0) { type = DwMime::kSubtypePgpSignature; } else if (DwStrcasecmp(aStr, "pgp-encrypted") == 0) { type = DwMime::kSubtypePgpEncrypted; } else if (DwStrcasecmp(aStr, "pgp") == 0) { type = DwMime::kSubtypePgpClearsigned; } else if (DwStrcasecmp(aStr, "pkcs7-signature") == 0) { type = DwMime::kSubtypePkcs7Signature; } else if (DwStrcasecmp(aStr, "pkcs7-mime") == 0) { type = DwMime::kSubtypePkcs7Mime; } break; case 'R': case 'r': if (DwStrcasecmp(aStr, "richtext") == 0) { type = DwMime::kSubtypeRichtext; } else if (DwStrcasecmp(aStr, "rfc822") == 0) { type = DwMime::kSubtypeRfc822; } else if (DwStrcasecmp(aStr, "report") == 0) { type = DwMime::kSubtypeReport; } else if (DwStrcasecmp(aStr, "rtf") == 0) { type = DwMime::kSubtypeRtf; } else if (DwStrcasecmp(aStr, "related") == 0) { type = DwMime::kSubtypeRelated; } break; case 'S': case 's': if (DwStrcasecmp(aStr, "signed") == 0) { type = DwMime::kSubtypeSigned; } break; case 'V': case 'v': if (DwStrcasecmp(aStr, "vnd.de.bund.bsi.chiasmus-text") == 0) { type = DwMime::kSubtypeChiasmusText; } break; case 'X': case 'x': if (DwStrcasecmp(aStr, "x-vcard") == 0) { type = DwMime::kSubtypeXVCard; } else if (DwStrcasecmp(aStr, "x-pkcs7-signature") == 0) { type = DwMime::kSubtypePkcs7Signature; } else if (DwStrcasecmp(aStr, "x-pkcs7-mime") == 0) { type = DwMime::kSubtypePkcs7Mime; } if (DwStrcasecmp(aStr, "x-diff") == 0) { type = DwMime::kSubtypeXDiff; } break; } return type; } void DwSubtypeEnumToStr(int aEnum, DwString& aStr) { switch (aEnum) { case DwMime::kSubtypeNull: aStr = ""; break; case DwMime::kSubtypeUnknown: default: aStr = "Unknown"; break; case DwMime::kSubtypePlain: aStr = "Plain"; break; case DwMime::kSubtypeRichtext: aStr = "Richtext"; break; case DwMime::kSubtypeEnriched: aStr = "Enriched"; break; case DwMime::kSubtypeHtml: aStr = "HTML"; break; case DwMime::kSubtypeVCal: aStr = "Calendar"; break; case DwMime::kSubtypeXVCard: aStr = "X-VCard"; break; case DwMime::kSubtypeXDiff: aStr = "X-Diff"; break; case DwMime::kSubtypeRtf: aStr = "RTF"; break; case DwMime::kSubtypeMixed: aStr = "Mixed"; break; case DwMime::kSubtypeSigned: aStr = "Signed"; break; case DwMime::kSubtypeEncrypted: aStr = "Encrypted"; break; case DwMime::kSubtypeAlternative: aStr = "Alternative"; break; case DwMime::kSubtypeDigest: aStr = "Digest"; break; case DwMime::kSubtypeParallel: aStr = "Parallel"; break; case DwMime::kSubtypeReport: aStr = "report"; break; case DwMime::kSubtypeRelated: aStr = "Related"; break; case DwMime::kSubtypeRfc822: aStr = "Rfc822"; break; case DwMime::kSubtypeDispositionNotification: aStr = "disposition-notification"; break; case DwMime::kSubtypePartial: aStr = "Partial"; break; case DwMime::kSubtypeExternalBody: aStr = "External-body"; break; case DwMime::kSubtypePostscript: aStr = "Postscript"; break; case DwMime::kSubtypeOctetStream: aStr = "Octet-stream"; break; case DwMime::kSubtypePgpSignature: aStr = "pgp-signature"; break; case DwMime::kSubtypePgpEncrypted: aStr = "pgp-encrypted"; break; case DwMime::kSubtypePgpClearsigned: aStr = "pgp"; break; case DwMime::kSubtypePkcs7Signature: aStr = "pkcs7-signature"; break; case DwMime::kSubtypePkcs7Mime: aStr = "pkcs7-mime"; break; case DwMime::kSubtypeMsTNEF: aStr = "ms-tnef"; break; case DwMime::kSubtypeChiasmusText: aStr = "vnd.de.bund.bsi.chiasmus-text"; break; case DwMime::kSubtypeJpeg: aStr = "jpeg"; break; case DwMime::kSubtypeGif: aStr = "gif"; break; case DwMime::kSubtypeBasic: aStr = "basic"; break; case DwMime::kSubtypeMpeg: aStr = "mpeg"; break; } } <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <fnordmetric/environment.h> #include <fnordmetric/adminui.h> #include <fnord/base/uri.h> namespace fnordmetric { std::unique_ptr<http::HTTPHandler> AdminUI::getHandler() { return std::unique_ptr<http::HTTPHandler>(new AdminUI()); } AdminUI::AdminUI() : webui_bundle_("FnordMetric"), webui_mount_(&webui_bundle_, "/admin") { webui_bundle_.addComponent("fnord/3rdparty/codemirror.js"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css"); webui_bundle_.addComponent("fnord/3rdparty/reset.css"); webui_bundle_.addComponent("fnord/fnord.js"); webui_bundle_.addComponent("fnord/themes/midnight-blue.css"); webui_bundle_.addComponent("fnord/components/fn-appbar.html"); webui_bundle_.addComponent("fnord/components/fn-button.html"); webui_bundle_.addComponent("fnord/components/fn-icon.html"); webui_bundle_.addComponent("fnord/components/fn-loader.html"); webui_bundle_.addComponent("fnord/components/fn-menu.html"); webui_bundle_.addComponent("fnord/components/fn-search.html"); webui_bundle_.addComponent("fnord/components/fn-table.html"); webui_bundle_.addComponent("fnord/components/fn-splitpane.html"); webui_bundle_.addComponent("fnord/components/fn-codeeditor.html"); webui_bundle_.addComponent("fnord/components/fn-dropdown.html"); webui_bundle_.addComponent("fnord/components/fn-datepicker.html"); webui_bundle_.addComponent("fnord/components/fn-timeinput.html"); webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html"); webui_bundle_.addComponent("fnord/components/fn-popup.html"); webui_bundle_.addComponent("fnord/components/fn-tabbar.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-metric-list.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-search.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-metric-preview.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-controls.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js"); webui_bundle_.addComponent( "fnordmetric-plugins/hosts/fnordmetric-plugin-hosts.html"); } bool AdminUI::handleHTTPRequest( http::HTTPRequest* request, http::HTTPResponse* response) { if (env()->verbose()) { fnord::util::LogEntry log_entry; log_entry.append("__severity__", "DEBUG"); log_entry.printf( "__message__", "HTTP request: %s %s", request->getMethod().c_str(), request->getUrl().c_str()); env()->logger()->log(log_entry); } if (webui_mount_.handleHTTPRequest(request, response)) { return true; } fnord::URI uri(request->getUrl()); auto path = uri.path(); if (path == "/") { response->setStatus(http::kStatusFound); response->addHeader("Content-Type", "text/html; charset=utf-8"); response->addHeader("Location", "/admin"); return true; } return false; } } <commit_msg>fix fn-table<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <fnordmetric/environment.h> #include <fnordmetric/adminui.h> #include <fnord/base/uri.h> namespace fnordmetric { std::unique_ptr<http::HTTPHandler> AdminUI::getHandler() { return std::unique_ptr<http::HTTPHandler>(new AdminUI()); } AdminUI::AdminUI() : webui_bundle_("FnordMetric"), webui_mount_(&webui_bundle_, "/admin") { webui_bundle_.addComponent("fnord/3rdparty/codemirror.js"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css"); webui_bundle_.addComponent("fnord/3rdparty/reset.css"); webui_bundle_.addComponent("fnord/fnord.js"); webui_bundle_.addComponent("fnord/themes/midnight-blue.css"); webui_bundle_.addComponent("fnord/components/fn-appbar.html"); webui_bundle_.addComponent("fnord/components/fn-button.html"); webui_bundle_.addComponent("fnord/components/fn-icon.html"); webui_bundle_.addComponent("fnord/components/fn-loader.html"); webui_bundle_.addComponent("fnord/components/fn-menu.html"); webui_bundle_.addComponent("fnord/components/fn-search.html"); webui_bundle_.addComponent("fnord/components/fn-table.html"); webui_bundle_.addComponent("fnord/components/fn-table.css"); webui_bundle_.addComponent("fnord/components/fn-splitpane.html"); webui_bundle_.addComponent("fnord/components/fn-codeeditor.html"); webui_bundle_.addComponent("fnord/components/fn-dropdown.html"); webui_bundle_.addComponent("fnord/components/fn-datepicker.html"); webui_bundle_.addComponent("fnord/components/fn-timeinput.html"); webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html"); webui_bundle_.addComponent("fnord/components/fn-popup.html"); webui_bundle_.addComponent("fnord/components/fn-tabbar.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-metric-list.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-search.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-metric-preview.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-controls.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js"); webui_bundle_.addComponent( "fnordmetric-plugins/hosts/fnordmetric-plugin-hosts.html"); } bool AdminUI::handleHTTPRequest( http::HTTPRequest* request, http::HTTPResponse* response) { if (env()->verbose()) { fnord::util::LogEntry log_entry; log_entry.append("__severity__", "DEBUG"); log_entry.printf( "__message__", "HTTP request: %s %s", request->getMethod().c_str(), request->getUrl().c_str()); env()->logger()->log(log_entry); } if (webui_mount_.handleHTTPRequest(request, response)) { return true; } fnord::URI uri(request->getUrl()); auto path = uri.path(); if (path == "/") { response->setStatus(http::kStatusFound); response->addHeader("Content-Type", "text/html; charset=utf-8"); response->addHeader("Location", "/admin"); return true; } return false; } } <|endoftext|>
<commit_before>/** * @file * @author Jason Lingle * @brief Implementation of src/control/ai/mod_attack/aim_select_weapon.hxx */ /* * aim_select_weapon.cxx * * Created on: 19.02.2011 * Author: jason */ #include <libconfig.h++> #include <cmath> #include <iostream> #include <cstdlib> #include "aim_select_weapon.hxx" #include "src/control/ai/aimod.hxx" #include "src/control/ai/aictrl.hxx" #include "src/ship/ship.hxx" #include "src/ship/sys/ship_system.hxx" #include "src/globals.hxx" #include "src/exit_conditions.hxx" using namespace std; #define WEAPON_CANT_USE (1 << (sizeof(int)*8-1)) AIM_SelectWeapon::AIM_SelectWeapon(AIControl* c, const libconfig::Setting& s) : AIModule(c), temperatureCaution(s.exists("temperature_caution")? s["temperature_caution"] : 0.95f), minMonophaseSize (s.exists("min_monophase_size" )? s["min_monophase_size" ] : 0.2f), magnetoCaution (s.exists("magneto_caution" )? s["magneto_caution" ] : 2.0f) { } void AIM_SelectWeapon::action() { if (!ship->target.ref) return; Ship* t = (Ship*)ship->target.ref; //Determine how wide an angle we have to hit the target float tx = t->getX() + controller.gstat("suggest_target_offset_x", 0.0f); float ty = t->getY() + controller.gstat("suggest_target_offset_y", 0.0f); float dx = tx - ship->getX(); float dy = ty - ship->getY(); float dist = sqrt(dx*dx + dy*dy); float maxAngleDiff = fabs(atan(t->getRadius() / dist)); float angle = atan2(dy, dx) - ship->getRotation(); float minAngle = angle - maxAngleDiff; float maxAngle = angle + maxAngleDiff; while (minAngle < 0) minAngle += 2*pi; while (maxAngle < 0) maxAngle += 2*pi; minAngle = fmod(minAngle, 2*pi); maxAngle = fmod(maxAngle, 2*pi); if (maxAngle < minAngle) maxAngle += 2*pi; /* Because of the above math, it is possible for * minAngle and maxAngle > 2*pi. To properly handle this, * angle checks should have the form * (angle > minAngle && angle < maxAngle) || * (angle+2*pi > minAngle && angle+2*pi < maxAngle) */ float ratings[AIControl::numWeapons] = {0}; //While going through the below, count how many launchers //are at each angle (rounded to the nearest 15 deg) unsigned angles[AIControl::numWeapons][360/15] = { /* init to zero */ }; //Inspect each weapon type for (unsigned i=0; i<AIControl::numWeapons; ++i) { float angleBonus, damageBonus; float accPenalty, distPenalty; switch ((Weapon)i) { case Weapon_EnergyCharge: angleBonus=0; damageBonus=1; accPenalty=0; distPenalty=0.2f; break; case Weapon_MagnetoBomb: angleBonus=pi/6; damageBonus=2; accPenalty=0.5f; distPenalty=0.5f; break; case Weapon_PlasmaBurst: angleBonus=0; damageBonus=4; accPenalty=0; distPenalty=0.1f; break; case Weapon_SGBomb: angleBonus=pi/4; damageBonus=3; accPenalty=0.9f; distPenalty=0.5f; break; case Weapon_GatlingPlasma: angleBonus=pi/6; damageBonus=6; accPenalty=0.1f; distPenalty=0.15f; break; case Weapon_Monophase: angleBonus=0; damageBonus=7; accPenalty=0; distPenalty=0.1f; break; case Weapon_Missile: angleBonus=pi/3; damageBonus=8; accPenalty=0.4f; distPenalty=0; break; case Weapon_ParticleBeam: cerr << "FATAL: AIM_SelectWeapon doesn't know how to handle Weapon_ParticleBeam" << endl; exit(EXIT_PROGRAM_BUG); } const AIControl::WeaponInfo& info(controller.getWeaponInfo(i)); if (info.empty()) { //Can't use, it doesn't exist ratings[i] = WEAPON_CANT_USE; continue; } //Check for possible hits for (unsigned j=0; j<info.size(); ++j) { if ((info[j].theta > minAngle-angleBonus && info[j].theta < maxAngle+angleBonus) || (info[j].theta+2*pi > minAngle-angleBonus && info[j].theta+2*pi < maxAngle+angleBonus)) ratings[i] += damageBonus; if ((info[j].theta > minAngle && info[j].theta < maxAngle) || (info[j].theta+2*pi > minAngle && info[j].theta+2*pi < maxAngle)) ratings[i] -= accPenalty*damageBonus; //Count angles with 45 degree grace if not forward-facing if (((info[j].theta > minAngle-pi/4 && info[j].theta < maxAngle+pi/4) || (info[j].theta+2*pi > minAngle-pi/4 && info[j].theta+2*pi < maxAngle+pi/4)) && (info[j].theta > pi/4 && info[j].theta < 7*pi/4)) { ++angles[i][(unsigned)(info[j].theta/pi*180/15 + 0.5f) % (360/15)]; ratings[i] += damageBonus/3; } ratings[i] *= max(0.0f, 1.0f - dist*distPenalty); } if (i == (int)Weapon_PlasmaBurst || i == (int)Weapon_GatlingPlasma) { float pct = ship->getHeatPercent(); if (pct > temperatureCaution) ratings[i] = (int)(ratings[i] * (1 - (pct-temperatureCaution)/(1-temperatureCaution))); } else if (i == (int)Weapon_Monophase) { if (t->getRadius()*2 < minMonophaseSize) ratings[i] /= 2; } else if (i == (int)Weapon_MagnetoBomb) { float f = t->getMass() / (float)ship->getMass() / dist; if (f < magnetoCaution) ratings[i] = 0; } } //Find the best weapon int maxScore = WEAPON_CANT_USE; unsigned best = 0; for (unsigned i=0; i<AIControl::numWeapons; ++i) { if (ratings[i] > maxScore) { maxScore = ratings[i]; best = i; } } controller.setCurrentWeapon(best); controller.sstat("no_appropriate_weapon", maxScore <= 0); //Find best angle unsigned bestAngle=0; unsigned bestAngleCount=0; for (unsigned i=0; i<360/15; ++i) if (angles[best][i] > bestAngleCount) { bestAngle = i; bestAngleCount = angles[best][i]; } controller.sstat("suggest_angle_offset", (float)(bestAngle/180.0f*15.0f*pi)); } static AIModuleRegistrar<AIM_SelectWeapon> registrar("attack/select_weapon"); <commit_msg>Fix broken temperature test in weapon selection.<commit_after>/** * @file * @author Jason Lingle * @brief Implementation of src/control/ai/mod_attack/aim_select_weapon.hxx */ /* * aim_select_weapon.cxx * * Created on: 19.02.2011 * Author: jason */ #include <libconfig.h++> #include <cmath> #include <iostream> #include <cstdlib> #include "aim_select_weapon.hxx" #include "src/control/ai/aimod.hxx" #include "src/control/ai/aictrl.hxx" #include "src/ship/ship.hxx" #include "src/ship/sys/ship_system.hxx" #include "src/globals.hxx" #include "src/exit_conditions.hxx" using namespace std; #define WEAPON_CANT_USE (1 << (sizeof(int)*8-1)) AIM_SelectWeapon::AIM_SelectWeapon(AIControl* c, const libconfig::Setting& s) : AIModule(c), temperatureCaution(s.exists("temperature_caution")? s["temperature_caution"] : 0.95f), minMonophaseSize (s.exists("min_monophase_size" )? s["min_monophase_size" ] : 0.2f), magnetoCaution (s.exists("magneto_caution" )? s["magneto_caution" ] : 2.0f) { } void AIM_SelectWeapon::action() { if (!ship->target.ref) return; Ship* t = (Ship*)ship->target.ref; //Determine how wide an angle we have to hit the target float tx = t->getX() + controller.gstat("suggest_target_offset_x", 0.0f); float ty = t->getY() + controller.gstat("suggest_target_offset_y", 0.0f); float dx = tx - ship->getX(); float dy = ty - ship->getY(); float dist = sqrt(dx*dx + dy*dy); float maxAngleDiff = fabs(atan(t->getRadius() / dist)); float angle = atan2(dy, dx) - ship->getRotation(); float minAngle = angle - maxAngleDiff; float maxAngle = angle + maxAngleDiff; while (minAngle < 0) minAngle += 2*pi; while (maxAngle < 0) maxAngle += 2*pi; minAngle = fmod(minAngle, 2*pi); maxAngle = fmod(maxAngle, 2*pi); if (maxAngle < minAngle) maxAngle += 2*pi; /* Because of the above math, it is possible for * minAngle and maxAngle > 2*pi. To properly handle this, * angle checks should have the form * (angle > minAngle && angle < maxAngle) || * (angle+2*pi > minAngle && angle+2*pi < maxAngle) */ float ratings[AIControl::numWeapons] = {0}; //While going through the below, count how many launchers //are at each angle (rounded to the nearest 15 deg) unsigned angles[AIControl::numWeapons][360/15] = { /* init to zero */ }; //Inspect each weapon type for (unsigned i=0; i<AIControl::numWeapons; ++i) { float angleBonus, damageBonus; float accPenalty, distPenalty; switch ((Weapon)i) { case Weapon_EnergyCharge: angleBonus=0; damageBonus=1; accPenalty=0; distPenalty=0.2f; break; case Weapon_MagnetoBomb: angleBonus=pi/6; damageBonus=2; accPenalty=0.5f; distPenalty=0.5f; break; case Weapon_PlasmaBurst: angleBonus=0; damageBonus=4; accPenalty=0; distPenalty=0.1f; break; case Weapon_SGBomb: angleBonus=pi/4; damageBonus=3; accPenalty=0.9f; distPenalty=0.5f; break; case Weapon_GatlingPlasma: angleBonus=pi/6; damageBonus=6; accPenalty=0.1f; distPenalty=0.15f; break; case Weapon_Monophase: angleBonus=0; damageBonus=7; accPenalty=0; distPenalty=0.1f; break; case Weapon_Missile: angleBonus=pi/3; damageBonus=8; accPenalty=0.4f; distPenalty=0; break; case Weapon_ParticleBeam: cerr << "FATAL: AIM_SelectWeapon doesn't know how to handle Weapon_ParticleBeam" << endl; exit(EXIT_PROGRAM_BUG); } const AIControl::WeaponInfo& info(controller.getWeaponInfo(i)); if (info.empty()) { //Can't use, it doesn't exist ratings[i] = WEAPON_CANT_USE; continue; } //Check for possible hits for (unsigned j=0; j<info.size(); ++j) { if ((info[j].theta > minAngle-angleBonus && info[j].theta < maxAngle+angleBonus) || (info[j].theta+2*pi > minAngle-angleBonus && info[j].theta+2*pi < maxAngle+angleBonus)) ratings[i] += damageBonus; if ((info[j].theta > minAngle && info[j].theta < maxAngle) || (info[j].theta+2*pi > minAngle && info[j].theta+2*pi < maxAngle)) ratings[i] -= accPenalty*damageBonus; //Count angles with 45 degree grace if not forward-facing if (((info[j].theta > minAngle-pi/4 && info[j].theta < maxAngle+pi/4) || (info[j].theta+2*pi > minAngle-pi/4 && info[j].theta+2*pi < maxAngle+pi/4)) && (info[j].theta > pi/4 && info[j].theta < 7*pi/4)) { ++angles[i][(unsigned)(info[j].theta/pi*180/15 + 0.5f) % (360/15)]; ratings[i] += damageBonus/3; } ratings[i] *= max(0.0f, 1.0f - dist*distPenalty); } if (i == (int)Weapon_PlasmaBurst || i == (int)Weapon_GatlingPlasma) { float pct = ship->getHeatPercent(); if (pct > temperatureCaution) ratings[i] = (int)(ratings[i] * (1 - pct/temperatureCaution)); } else if (i == (int)Weapon_Monophase) { if (t->getRadius()*2 < minMonophaseSize) ratings[i] /= 2; } else if (i == (int)Weapon_MagnetoBomb) { float f = t->getMass() / (float)ship->getMass() / dist; if (f < magnetoCaution) ratings[i] = 0; } } //Find the best weapon int maxScore = WEAPON_CANT_USE; unsigned best = 0; for (unsigned i=0; i<AIControl::numWeapons; ++i) { if (ratings[i] > maxScore) { maxScore = ratings[i]; best = i; } } controller.setCurrentWeapon(best); controller.sstat("no_appropriate_weapon", maxScore <= 0); //Find best angle unsigned bestAngle=0; unsigned bestAngleCount=0; for (unsigned i=0; i<360/15; ++i) if (angles[best][i] > bestAngleCount) { bestAngle = i; bestAngleCount = angles[best][i]; } controller.sstat("suggest_angle_offset", (float)(bestAngle/180.0f*15.0f*pi)); } static AIModuleRegistrar<AIM_SelectWeapon> registrar("attack/select_weapon"); <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarativeutilmodule_p.h" #include "qfxperf_p_p.h" #include "qdeclarativeanimation_p.h" #include "qdeclarativeanimation_p_p.h" #include "qdeclarativebehavior_p.h" #include "qdeclarativebind_p.h" #include "qdeclarativeconnections_p.h" #include "qdeclarativedatetimeformatter_p.h" #include "qdeclarativeeasefollow_p.h" #include "qdeclarativefontloader_p.h" #include "qdeclarativelistaccessor_p.h" #include "qdeclarativelistmodel_p.h" #include "qdeclarativenullablevalue_p_p.h" #include "qdeclarativenumberformatter_p.h" #include "qdeclarativeopenmetaobject_p.h" #include "qdeclarativepackage_p.h" #include "qdeclarativepixmapcache_p.h" #include "qdeclarativepropertychanges_p.h" #include "qdeclarativepropertymap.h" #include "qdeclarativespringfollow_p.h" #include "qdeclarativestategroup_p.h" #include "qdeclarativestateoperations_p.h" #include "qdeclarativestate_p.h" #include "qdeclarativestate_p_p.h" #include "qdeclarativestyledtext_p.h" #include "qdeclarativesystempalette_p.h" #include "qdeclarativetimeline_p_p.h" #include "qdeclarativetimer_p.h" #include "qdeclarativetransitionmanager_p_p.h" #include "qdeclarativetransition_p.h" #include "qdeclarativeview.h" #include "qdeclarativexmllistmodel_p.h" #include "qnumberformat_p.h" #include "qperformancelog_p_p.h" void QDeclarativeUtilModule::defineModule() { QML_REGISTER_TYPE(Qt,4,6,AnchorChanges,QDeclarativeAnchorChanges); QML_REGISTER_TYPE(Qt,4,6,Behavior,QDeclarativeBehavior); QML_REGISTER_TYPE(Qt,4,6,Binding,QDeclarativeBind); QML_REGISTER_TYPE(Qt,4,6,ColorAnimation,QDeclarativeColorAnimation); QML_REGISTER_TYPE(Qt,4,6,Connections,QDeclarativeConnections); QML_REGISTER_TYPE(Qt,4,6,DateTimeFormatter,QDeclarativeDateTimeFormatter); QML_REGISTER_TYPE(Qt,4,6,EaseFollow,QDeclarativeEaseFollow);; QML_REGISTER_TYPE(Qt,4,6,FontLoader,QDeclarativeFontLoader); QML_REGISTER_TYPE(Qt,4,6,ListElement,QDeclarativeListElement); QML_REGISTER_TYPE(Qt,4,6,NumberAnimation,QDeclarativeNumberAnimation); QML_REGISTER_TYPE(Qt,4,6,NumberFormatter,QDeclarativeNumberFormatter);; QML_REGISTER_TYPE(Qt,4,6,Package,QDeclarativePackage); QML_REGISTER_TYPE(Qt,4,6,ParallelAnimation,QDeclarativeParallelAnimation); QML_REGISTER_TYPE(Qt,4,6,ParentAction,QDeclarativeParentAction); QML_REGISTER_TYPE(Qt,4,6,ParentAnimation,QDeclarativeParentAnimation); QML_REGISTER_TYPE(Qt,4,6,ParentChange,QDeclarativeParentChange); QML_REGISTER_TYPE(Qt,4,6,PauseAnimation,QDeclarativePauseAnimation); QML_REGISTER_TYPE(Qt,4,6,PropertyAction,QDeclarativePropertyAction); QML_REGISTER_TYPE(Qt,4,6,PropertyAnimation,QDeclarativePropertyAnimation); QML_REGISTER_TYPE(Qt,4,6,RotationAnimation,QDeclarativeRotationAnimation); QML_REGISTER_TYPE(Qt,4,6,ScriptAction,QDeclarativeScriptAction); QML_REGISTER_TYPE(Qt,4,6,SequentialAnimation,QDeclarativeSequentialAnimation); QML_REGISTER_TYPE(Qt,4,6,SpringFollow,QDeclarativeSpringFollow); QML_REGISTER_TYPE(Qt,4,6,StateChangeScript,QDeclarativeStateChangeScript); QML_REGISTER_TYPE(Qt,4,6,StateGroup,QDeclarativeStateGroup); QML_REGISTER_TYPE(Qt,4,6,State,QDeclarativeState); QML_REGISTER_TYPE(Qt,4,6,SystemPalette,QDeclarativeSystemPalette); QML_REGISTER_TYPE(Qt,4,6,Timer,QDeclarativeTimer); QML_REGISTER_TYPE(Qt,4,6,Transition,QDeclarativeTransition); QML_REGISTER_TYPE(Qt,4,6,Vector3dAnimation,QDeclarativeVector3dAnimation); #ifndef QT_NO_XMLPATTERNS QML_REGISTER_TYPE(Qt,4,6,XmlListModel,QDeclarativeXmlListModel); QML_REGISTER_TYPE(Qt,4,6,XmlRole,QDeclarativeXmlListModelRole); #endif QML_REGISTER_NOCREATE_TYPE(QDeclarativeAnchors); QML_REGISTER_NOCREATE_TYPE(QDeclarativeAbstractAnimation); QML_REGISTER_NOCREATE_TYPE(QDeclarativeStateOperation); QML_REGISTER_NOCREATE_TYPE(QNumberFormat); QML_REGISTER_CUSTOM_TYPE(Qt, 4,6, ListModel, QDeclarativeListModel, QDeclarativeListModelParser); QML_REGISTER_CUSTOM_TYPE(Qt, 4,6, PropertyChanges, QDeclarativePropertyChanges, QDeclarativePropertyChangesParser); QML_REGISTER_CUSTOM_TYPE(Qt, 4,6, Connections, QDeclarativeConnections, QDeclarativeConnectionsParser); } <commit_msg>compile fix for WinCE<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarativeutilmodule_p.h" #include "qfxperf_p_p.h" #include "qdeclarativeanimation_p.h" #include "qdeclarativeanimation_p_p.h" #include "qdeclarativebehavior_p.h" #include "qdeclarativebind_p.h" #include "qdeclarativeconnections_p.h" #include "qdeclarativedatetimeformatter_p.h" #include "qdeclarativeeasefollow_p.h" #include "qdeclarativefontloader_p.h" #include "qdeclarativelistaccessor_p.h" #include "qdeclarativelistmodel_p.h" #include "qdeclarativenullablevalue_p_p.h" #include "qdeclarativenumberformatter_p.h" #include "qdeclarativeopenmetaobject_p.h" #include "qdeclarativepackage_p.h" #include "qdeclarativepixmapcache_p.h" #include "qdeclarativepropertychanges_p.h" #include "qdeclarativepropertymap.h" #include "qdeclarativespringfollow_p.h" #include "qdeclarativestategroup_p.h" #include "qdeclarativestateoperations_p.h" #include "qdeclarativestate_p.h" #include "qdeclarativestate_p_p.h" #include "qdeclarativestyledtext_p.h" #include "qdeclarativesystempalette_p.h" #include "qdeclarativetimeline_p_p.h" #include "qdeclarativetimer_p.h" #include "qdeclarativetransitionmanager_p_p.h" #include "qdeclarativetransition_p.h" #include "qdeclarativeview.h" #ifndef QT_NO_XMLPATTERNS #include "qdeclarativexmllistmodel_p.h" #endif #include "qnumberformat_p.h" #include "qperformancelog_p_p.h" void QDeclarativeUtilModule::defineModule() { QML_REGISTER_TYPE(Qt,4,6,AnchorChanges,QDeclarativeAnchorChanges); QML_REGISTER_TYPE(Qt,4,6,Behavior,QDeclarativeBehavior); QML_REGISTER_TYPE(Qt,4,6,Binding,QDeclarativeBind); QML_REGISTER_TYPE(Qt,4,6,ColorAnimation,QDeclarativeColorAnimation); QML_REGISTER_TYPE(Qt,4,6,Connections,QDeclarativeConnections); QML_REGISTER_TYPE(Qt,4,6,DateTimeFormatter,QDeclarativeDateTimeFormatter); QML_REGISTER_TYPE(Qt,4,6,EaseFollow,QDeclarativeEaseFollow);; QML_REGISTER_TYPE(Qt,4,6,FontLoader,QDeclarativeFontLoader); QML_REGISTER_TYPE(Qt,4,6,ListElement,QDeclarativeListElement); QML_REGISTER_TYPE(Qt,4,6,NumberAnimation,QDeclarativeNumberAnimation); QML_REGISTER_TYPE(Qt,4,6,NumberFormatter,QDeclarativeNumberFormatter);; QML_REGISTER_TYPE(Qt,4,6,Package,QDeclarativePackage); QML_REGISTER_TYPE(Qt,4,6,ParallelAnimation,QDeclarativeParallelAnimation); QML_REGISTER_TYPE(Qt,4,6,ParentAction,QDeclarativeParentAction); QML_REGISTER_TYPE(Qt,4,6,ParentAnimation,QDeclarativeParentAnimation); QML_REGISTER_TYPE(Qt,4,6,ParentChange,QDeclarativeParentChange); QML_REGISTER_TYPE(Qt,4,6,PauseAnimation,QDeclarativePauseAnimation); QML_REGISTER_TYPE(Qt,4,6,PropertyAction,QDeclarativePropertyAction); QML_REGISTER_TYPE(Qt,4,6,PropertyAnimation,QDeclarativePropertyAnimation); QML_REGISTER_TYPE(Qt,4,6,RotationAnimation,QDeclarativeRotationAnimation); QML_REGISTER_TYPE(Qt,4,6,ScriptAction,QDeclarativeScriptAction); QML_REGISTER_TYPE(Qt,4,6,SequentialAnimation,QDeclarativeSequentialAnimation); QML_REGISTER_TYPE(Qt,4,6,SpringFollow,QDeclarativeSpringFollow); QML_REGISTER_TYPE(Qt,4,6,StateChangeScript,QDeclarativeStateChangeScript); QML_REGISTER_TYPE(Qt,4,6,StateGroup,QDeclarativeStateGroup); QML_REGISTER_TYPE(Qt,4,6,State,QDeclarativeState); QML_REGISTER_TYPE(Qt,4,6,SystemPalette,QDeclarativeSystemPalette); QML_REGISTER_TYPE(Qt,4,6,Timer,QDeclarativeTimer); QML_REGISTER_TYPE(Qt,4,6,Transition,QDeclarativeTransition); QML_REGISTER_TYPE(Qt,4,6,Vector3dAnimation,QDeclarativeVector3dAnimation); #ifndef QT_NO_XMLPATTERNS QML_REGISTER_TYPE(Qt,4,6,XmlListModel,QDeclarativeXmlListModel); QML_REGISTER_TYPE(Qt,4,6,XmlRole,QDeclarativeXmlListModelRole); #endif QML_REGISTER_NOCREATE_TYPE(QDeclarativeAnchors); QML_REGISTER_NOCREATE_TYPE(QDeclarativeAbstractAnimation); QML_REGISTER_NOCREATE_TYPE(QDeclarativeStateOperation); QML_REGISTER_NOCREATE_TYPE(QNumberFormat); QML_REGISTER_CUSTOM_TYPE(Qt, 4,6, ListModel, QDeclarativeListModel, QDeclarativeListModelParser); QML_REGISTER_CUSTOM_TYPE(Qt, 4,6, PropertyChanges, QDeclarativePropertyChanges, QDeclarativePropertyChangesParser); QML_REGISTER_CUSTOM_TYPE(Qt, 4,6, Connections, QDeclarativeConnections, QDeclarativeConnectionsParser); } <|endoftext|>
<commit_before>// Copyright 2013 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 "extensions/browser/api/capture_web_contents_function.h" #include "base/base64.h" #include "base/strings/stringprintf.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_function.h" #include "extensions/common/constants.h" #include "ui/gfx/codec/jpeg_codec.h" #include "ui/gfx/codec/png_codec.h" using content::RenderViewHost; using content::RenderWidgetHost; using content::RenderWidgetHostView; using content::WebContents; namespace extensions { bool CaptureWebContentsFunction::HasPermission() { return true; } bool CaptureWebContentsFunction::RunAsync() { EXTENSION_FUNCTION_VALIDATE(args_); context_id_ = extension_misc::kCurrentWindowId; args_->GetInteger(0, &context_id_); scoped_ptr<ImageDetails> image_details; if (args_->GetSize() > 1) { base::Value* spec = NULL; EXTENSION_FUNCTION_VALIDATE(args_->Get(1, &spec) && spec); image_details = ImageDetails::FromValue(*spec); } if (!IsScreenshotEnabled()) return false; WebContents* contents = GetWebContentsForID(context_id_); if (!contents) return false; // The default format and quality setting used when encoding jpegs. const ImageDetails::Format kDefaultFormat = ImageDetails::FORMAT_JPEG; const int kDefaultQuality = 90; image_format_ = kDefaultFormat; image_quality_ = kDefaultQuality; if (image_details) { if (image_details->format != ImageDetails::FORMAT_NONE) image_format_ = image_details->format; if (image_details->quality.get()) image_quality_ = *image_details->quality; } RenderViewHost* render_view_host = contents->GetRenderViewHost(); RenderWidgetHostView* view = render_view_host->GetView(); if (!view) { OnCaptureFailure(FAILURE_REASON_VIEW_INVISIBLE); return false; } render_view_host->CopyFromBackingStore( gfx::Rect(), view->GetViewBounds().size(), base::Bind(&CaptureWebContentsFunction::CopyFromBackingStoreComplete, this), kN32_SkColorType); return true; } void CaptureWebContentsFunction::CopyFromBackingStoreComplete( bool succeeded, const SkBitmap& bitmap) { if (succeeded) { OnCaptureSuccess(bitmap); return; } OnCaptureFailure(FAILURE_REASON_UNKNOWN); } void CaptureWebContentsFunction::OnCaptureSuccess(const SkBitmap& bitmap) { std::vector<unsigned char> data; SkAutoLockPixels screen_capture_lock(bitmap); bool encoded = false; std::string mime_type; switch (image_format_) { case ImageDetails::FORMAT_JPEG: encoded = gfx::JPEGCodec::Encode( reinterpret_cast<unsigned char*>(bitmap.getAddr32(0, 0)), gfx::JPEGCodec::FORMAT_SkBitmap, bitmap.width(), bitmap.height(), static_cast<int>(bitmap.rowBytes()), image_quality_, &data); mime_type = kMimeTypeJpeg; break; case ImageDetails::FORMAT_PNG: encoded = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, true, // Discard transparency. &data); mime_type = kMimeTypePng; break; default: NOTREACHED() << "Invalid image format."; } if (!encoded) { OnCaptureFailure(FAILURE_REASON_ENCODING_FAILED); return; } std::string base64_result; base::StringPiece stream_as_string( reinterpret_cast<const char*>(vector_as_array(&data)), data.size()); base::Base64Encode(stream_as_string, &base64_result); base64_result.insert( 0, base::StringPrintf("data:%s;base64,", mime_type.c_str())); SetResult(new base::StringValue(base64_result)); SendResponse(true); } } // namespace extensions <commit_msg>Higher-detailed results from tabs.captureVisibleTab on high-DPI systems.<commit_after>// Copyright 2013 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 "extensions/browser/api/capture_web_contents_function.h" #include "base/base64.h" #include "base/strings/stringprintf.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_function.h" #include "extensions/common/constants.h" #include "ui/gfx/codec/jpeg_codec.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/display.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/screen.h" using content::RenderWidgetHost; using content::RenderWidgetHostView; using content::WebContents; namespace extensions { bool CaptureWebContentsFunction::HasPermission() { return true; } bool CaptureWebContentsFunction::RunAsync() { EXTENSION_FUNCTION_VALIDATE(args_); context_id_ = extension_misc::kCurrentWindowId; args_->GetInteger(0, &context_id_); scoped_ptr<ImageDetails> image_details; if (args_->GetSize() > 1) { base::Value* spec = NULL; EXTENSION_FUNCTION_VALIDATE(args_->Get(1, &spec) && spec); image_details = ImageDetails::FromValue(*spec); } if (!IsScreenshotEnabled()) return false; WebContents* contents = GetWebContentsForID(context_id_); if (!contents) return false; // The default format and quality setting used when encoding jpegs. const ImageDetails::Format kDefaultFormat = ImageDetails::FORMAT_JPEG; const int kDefaultQuality = 90; image_format_ = kDefaultFormat; image_quality_ = kDefaultQuality; if (image_details) { if (image_details->format != ImageDetails::FORMAT_NONE) image_format_ = image_details->format; if (image_details->quality.get()) image_quality_ = *image_details->quality; } // TODO(miu): Account for fullscreen render widget? http://crbug.com/419878 RenderWidgetHostView* const view = contents->GetRenderWidgetHostView(); RenderWidgetHost* const host = view ? view->GetRenderWidgetHost() : nullptr; if (!view || !host) { OnCaptureFailure(FAILURE_REASON_VIEW_INVISIBLE); return false; } // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. const gfx::Size view_size = view->GetViewBounds().size(); gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); gfx::Screen* const screen = gfx::Screen::GetScreenFor(native_view); if (screen->IsDIPEnabled()) { const float scale = screen->GetDisplayNearestWindow(native_view).device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ToCeiledSize(gfx::ScaleSize(view_size, scale)); } host->CopyFromBackingStore( gfx::Rect(view_size), bitmap_size, base::Bind(&CaptureWebContentsFunction::CopyFromBackingStoreComplete, this), kN32_SkColorType); return true; } void CaptureWebContentsFunction::CopyFromBackingStoreComplete( bool succeeded, const SkBitmap& bitmap) { if (succeeded) { OnCaptureSuccess(bitmap); return; } OnCaptureFailure(FAILURE_REASON_UNKNOWN); } void CaptureWebContentsFunction::OnCaptureSuccess(const SkBitmap& bitmap) { std::vector<unsigned char> data; SkAutoLockPixels screen_capture_lock(bitmap); bool encoded = false; std::string mime_type; switch (image_format_) { case ImageDetails::FORMAT_JPEG: encoded = gfx::JPEGCodec::Encode( reinterpret_cast<unsigned char*>(bitmap.getAddr32(0, 0)), gfx::JPEGCodec::FORMAT_SkBitmap, bitmap.width(), bitmap.height(), static_cast<int>(bitmap.rowBytes()), image_quality_, &data); mime_type = kMimeTypeJpeg; break; case ImageDetails::FORMAT_PNG: encoded = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, true, // Discard transparency. &data); mime_type = kMimeTypePng; break; default: NOTREACHED() << "Invalid image format."; } if (!encoded) { OnCaptureFailure(FAILURE_REASON_ENCODING_FAILED); return; } std::string base64_result; base::StringPiece stream_as_string( reinterpret_cast<const char*>(vector_as_array(&data)), data.size()); base::Base64Encode(stream_as_string, &base64_result); base64_result.insert( 0, base::StringPrintf("data:%s;base64,", mime_type.c_str())); SetResult(new base::StringValue(base64_result)); SendResponse(true); } } // namespace extensions <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Time.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: obo $ $Date: 2007-03-09 13:32:11 $ * * 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 _FORMS_TIME_HXX_ #define _FORMS_TIME_HXX_ #ifndef _FORMS_EDITBASE_HXX_ #include "EditBase.hxx" #endif #ifndef _FORMS_LIMITED_FORMATS_HXX_ #include "limitedformats.hxx" #endif //......................................................................... namespace frm { //......................................................................... //================================================================== //= OTimeModel //================================================================== class OTimeModel :public OEditBaseModel ,public OLimitedFormats { private: ::com::sun::star::uno::Any m_aSaveValue; sal_Bool m_bDateTimeField; protected: virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); public: DECLARE_DEFAULT_LEAF_XTOR( OTimeModel ); // stario::XPersistObject virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::beans::XPropertySet virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::lang::IllegalArgumentException); virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OTimeModel); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // OControlModel's property handling virtual void describeFixedProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps ) const; // prevent method hiding using OBoundControlModel::getFastPropertyValue; protected: // OBoundControlModel overridables virtual ::com::sun::star::uno::Any translateDbColumnToControlValue( ); virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset ); virtual ::com::sun::star::uno::Any translateControlValueToExternalValue( ) const; virtual ::com::sun::star::uno::Any translateExternalValueToControlValue( ) const; virtual ::com::sun::star::uno::Any translateControlValueToValidatableValue( ) const; virtual ::com::sun::star::uno::Any getDefaultForReset() const; virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm ); virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding ); protected: DECLARE_XCLONEABLE(); private: /** translates the control value (the VCL-internal integer representation of a date) into a UNO-Date. */ void impl_translateControlValueToUNOTime( ::com::sun::star::uno::Any& _rUNOValue ) const; }; //================================================================== //= OTimeControl //================================================================== class OTimeControl: public OBoundControl { protected: virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); public: OTimeControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); DECLARE_UNO3_AGG_DEFAULTS(OTimeControl, OBoundControl); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OTimeControl); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); }; //......................................................................... } // namespace frm //......................................................................... #endif // _FORMS_TIME_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.14.82); FILE MERGED 2008/04/01 12:30:25 thb 1.14.82.2: #i85898# Stripping all external header guards 2008/03/31 13:11:34 rt 1.14.82.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Time.hxx,v $ * $Revision: 1.15 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _FORMS_TIME_HXX_ #define _FORMS_TIME_HXX_ #include "EditBase.hxx" #include "limitedformats.hxx" //......................................................................... namespace frm { //......................................................................... //================================================================== //= OTimeModel //================================================================== class OTimeModel :public OEditBaseModel ,public OLimitedFormats { private: ::com::sun::star::uno::Any m_aSaveValue; sal_Bool m_bDateTimeField; protected: virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); public: DECLARE_DEFAULT_LEAF_XTOR( OTimeModel ); // stario::XPersistObject virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::beans::XPropertySet virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::lang::IllegalArgumentException); virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OTimeModel); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // OControlModel's property handling virtual void describeFixedProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps ) const; // prevent method hiding using OBoundControlModel::getFastPropertyValue; protected: // OBoundControlModel overridables virtual ::com::sun::star::uno::Any translateDbColumnToControlValue( ); virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset ); virtual ::com::sun::star::uno::Any translateControlValueToExternalValue( ) const; virtual ::com::sun::star::uno::Any translateExternalValueToControlValue( ) const; virtual ::com::sun::star::uno::Any translateControlValueToValidatableValue( ) const; virtual ::com::sun::star::uno::Any getDefaultForReset() const; virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm ); virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding ); protected: DECLARE_XCLONEABLE(); private: /** translates the control value (the VCL-internal integer representation of a date) into a UNO-Date. */ void impl_translateControlValueToUNOTime( ::com::sun::star::uno::Any& _rUNOValue ) const; }; //================================================================== //= OTimeControl //================================================================== class OTimeControl: public OBoundControl { protected: virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); public: OTimeControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); DECLARE_UNO3_AGG_DEFAULTS(OTimeControl, OBoundControl); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OTimeControl); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); }; //......................................................................... } // namespace frm //......................................................................... #endif // _FORMS_TIME_HXX_ <|endoftext|>
<commit_before>/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/experimental/exception_tracer/ExceptionTracer.h> #include <exception> #include <iostream> #include <dlfcn.h> #include <glog/logging.h> #include <folly/String.h> #include <folly/experimental/exception_tracer/ExceptionAbi.h> #include <folly/experimental/exception_tracer/StackTrace.h> #include <folly/experimental/symbolizer/Symbolizer.h> namespace { using namespace ::folly::exception_tracer; using namespace ::folly::symbolizer; using namespace __cxxabiv1; extern "C" { StackTraceStack* getExceptionStackTraceStack(void) __attribute__((__weak__)); typedef StackTraceStack* (*GetExceptionStackTraceStackType)(); GetExceptionStackTraceStackType getExceptionStackTraceStackFn; } } // namespace namespace folly { namespace exception_tracer { std::ostream& operator<<(std::ostream& out, const ExceptionInfo& info) { printExceptionInfo(out, info, SymbolizePrinter::COLOR_IF_TTY); return out; } void printExceptionInfo( std::ostream& out, const ExceptionInfo& info, int options) { out << "Exception type: "; if (info.type) { out << folly::demangle(*info.type); } else { out << "(unknown type)"; } out << " (" << info.frames.size() << (info.frames.size() == 1 ? " frame" : " frames") << ")\n"; try { size_t frameCount = info.frames.size(); // Skip our own internal frames static constexpr size_t kInternalFramesNumber = 3; if (frameCount > kInternalFramesNumber) { auto addresses = info.frames.data() + kInternalFramesNumber; frameCount -= kInternalFramesNumber; std::vector<SymbolizedFrame> frames; frames.resize(frameCount); Symbolizer symbolizer( (options & SymbolizePrinter::NO_FILE_AND_LINE) ? Dwarf::LocationInfoMode::DISABLED : Symbolizer::kDefaultLocationInfoMode); symbolizer.symbolize(addresses, frames.data(), frameCount); OStreamSymbolizePrinter osp(out, options); osp.println(addresses, frames.data(), frameCount); } } catch (const std::exception& e) { out << "\n !! caught " << folly::exceptionStr(e) << "\n"; } catch (...) { out << "\n !!! caught unexpected exception\n"; } } namespace { /** * Is this a standard C++ ABI exception? * * Dependent exceptions (thrown via std::rethrow_exception) aren't -- * exc doesn't actually point to a __cxa_exception structure, but * the offset of unwindHeader is correct, so exc->unwindHeader actually * returns a _Unwind_Exception object. Yeah, it's ugly like that. */ bool isAbiCppException(const __cxa_exception* exc) { // The least significant four bytes must be "C++\0" static const uint64_t cppClass = ((uint64_t)'C' << 24) | ((uint64_t)'+' << 16) | ((uint64_t)'+' << 8); return (exc->unwindHeader.exception_class & 0xffffffff) == cppClass; } } // namespace std::vector<ExceptionInfo> getCurrentExceptions() { struct Once { Once() { // See if linked in with us (getExceptionStackTraceStack is weak) getExceptionStackTraceStackFn = getExceptionStackTraceStack; if (!getExceptionStackTraceStackFn) { // Nope, see if it's in a shared library getExceptionStackTraceStackFn = (GetExceptionStackTraceStackType)dlsym( RTLD_NEXT, "getExceptionStackTraceStack"); } } }; static Once once; std::vector<ExceptionInfo> exceptions; auto currentException = __cxa_get_globals()->caughtExceptions; if (!currentException) { return exceptions; } StackTraceStack* traceStack = nullptr; if (!getExceptionStackTraceStackFn) { static bool logged = false; if (!logged) { LOG(WARNING) << "Exception tracer library not linked, stack traces not available"; logged = true; } } else if ((traceStack = getExceptionStackTraceStackFn()) == nullptr) { static bool logged = false; if (!logged) { LOG(WARNING) << "Exception stack trace invalid, stack traces not available"; logged = true; } } StackTrace* trace = traceStack ? traceStack->top() : nullptr; while (currentException) { ExceptionInfo info; // Dependent exceptions (thrown via std::rethrow_exception) aren't // standard ABI __cxa_exception objects, and are correctly labeled as // such in the exception_class field. We could try to extract the // primary exception type in horribly hacky ways, but, for now, nullptr. info.type = isAbiCppException(currentException) ? currentException->exceptionType : nullptr; if (traceStack) { LOG_IF(DFATAL, !trace) << "Invalid trace stack for exception of type: " << (info.type ? folly::demangle(*info.type) : "null"); if (!trace) { return {}; } info.frames.assign( trace->addresses, trace->addresses + trace->frameCount); trace = traceStack->next(trace); } currentException = currentException->nextException; exceptions.push_back(std::move(info)); } LOG_IF(DFATAL, trace) << "Invalid trace stack!"; return exceptions; } namespace { std::terminate_handler origTerminate = abort; std::unexpected_handler origUnexpected = abort; void dumpExceptionStack(const char* prefix) { auto exceptions = getCurrentExceptions(); if (exceptions.empty()) { return; } LOG(ERROR) << prefix << ", exception stack follows"; for (auto& exc : exceptions) { LOG(ERROR) << exc << "\n"; } LOG(ERROR) << "exception stack complete"; } void terminateHandler() { dumpExceptionStack("terminate() called"); origTerminate(); } void unexpectedHandler() { dumpExceptionStack("Unexpected exception"); origUnexpected(); } } // namespace void installHandlers() { struct Once { Once() { origTerminate = std::set_terminate(terminateHandler); origUnexpected = std::set_unexpected(unexpectedHandler); } }; static Once once; } } // namespace exception_tracer } // namespace folly <commit_msg>fix compilation of ExceptionTracer on ARM<commit_after>/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/experimental/exception_tracer/ExceptionTracer.h> #include <exception> #include <iostream> #include <dlfcn.h> #include <glog/logging.h> #include <folly/Portability.h> #include <folly/String.h> #include <folly/experimental/exception_tracer/ExceptionAbi.h> #include <folly/experimental/exception_tracer/StackTrace.h> #include <folly/experimental/symbolizer/Symbolizer.h> namespace { using namespace ::folly::exception_tracer; using namespace ::folly::symbolizer; using namespace __cxxabiv1; extern "C" { StackTraceStack* getExceptionStackTraceStack(void) __attribute__((__weak__)); typedef StackTraceStack* (*GetExceptionStackTraceStackType)(); GetExceptionStackTraceStackType getExceptionStackTraceStackFn; } } // namespace namespace folly { namespace exception_tracer { std::ostream& operator<<(std::ostream& out, const ExceptionInfo& info) { printExceptionInfo(out, info, SymbolizePrinter::COLOR_IF_TTY); return out; } void printExceptionInfo( std::ostream& out, const ExceptionInfo& info, int options) { out << "Exception type: "; if (info.type) { out << folly::demangle(*info.type); } else { out << "(unknown type)"; } out << " (" << info.frames.size() << (info.frames.size() == 1 ? " frame" : " frames") << ")\n"; try { size_t frameCount = info.frames.size(); // Skip our own internal frames static constexpr size_t kInternalFramesNumber = 3; if (frameCount > kInternalFramesNumber) { auto addresses = info.frames.data() + kInternalFramesNumber; frameCount -= kInternalFramesNumber; std::vector<SymbolizedFrame> frames; frames.resize(frameCount); Symbolizer symbolizer( (options & SymbolizePrinter::NO_FILE_AND_LINE) ? Dwarf::LocationInfoMode::DISABLED : Symbolizer::kDefaultLocationInfoMode); symbolizer.symbolize(addresses, frames.data(), frameCount); OStreamSymbolizePrinter osp(out, options); osp.println(addresses, frames.data(), frameCount); } } catch (const std::exception& e) { out << "\n !! caught " << folly::exceptionStr(e) << "\n"; } catch (...) { out << "\n !!! caught unexpected exception\n"; } } namespace { /** * Is this a standard C++ ABI exception? * * Dependent exceptions (thrown via std::rethrow_exception) aren't -- * exc doesn't actually point to a __cxa_exception structure, but * the offset of unwindHeader is correct, so exc->unwindHeader actually * returns a _Unwind_Exception object. Yeah, it's ugly like that. * * Type of exception_class depends on ABI: on some it is defined as a * native endian uint64_t, on others a big endian char[8]. */ struct ArmAbiTag {}; struct AnyAbiTag {}; bool isAbiCppException(ArmAbiTag, const char (&klazz)[8]) { return klazz[4] == 'C' && klazz[5] == '+' && klazz[6] == '+' && klazz[7] == '\0'; } bool isAbiCppException(AnyAbiTag, const uint64_t& klazz) { // The least significant four bytes must be "C++\0" static const uint64_t cppClass = ((uint64_t)'C' << 24) | ((uint64_t)'+' << 16) | ((uint64_t)'+' << 8); return (klazz & 0xffffffff) == cppClass; } bool isAbiCppException(const __cxa_exception* exc) { using tag = std::conditional_t<kIsArchArm, ArmAbiTag, AnyAbiTag>; return isAbiCppException(tag{}, exc->unwindHeader.exception_class); } } // namespace std::vector<ExceptionInfo> getCurrentExceptions() { struct Once { Once() { // See if linked in with us (getExceptionStackTraceStack is weak) getExceptionStackTraceStackFn = getExceptionStackTraceStack; if (!getExceptionStackTraceStackFn) { // Nope, see if it's in a shared library getExceptionStackTraceStackFn = (GetExceptionStackTraceStackType)dlsym( RTLD_NEXT, "getExceptionStackTraceStack"); } } }; static Once once; std::vector<ExceptionInfo> exceptions; auto currentException = __cxa_get_globals()->caughtExceptions; if (!currentException) { return exceptions; } StackTraceStack* traceStack = nullptr; if (!getExceptionStackTraceStackFn) { static bool logged = false; if (!logged) { LOG(WARNING) << "Exception tracer library not linked, stack traces not available"; logged = true; } } else if ((traceStack = getExceptionStackTraceStackFn()) == nullptr) { static bool logged = false; if (!logged) { LOG(WARNING) << "Exception stack trace invalid, stack traces not available"; logged = true; } } StackTrace* trace = traceStack ? traceStack->top() : nullptr; while (currentException) { ExceptionInfo info; // Dependent exceptions (thrown via std::rethrow_exception) aren't // standard ABI __cxa_exception objects, and are correctly labeled as // such in the exception_class field. We could try to extract the // primary exception type in horribly hacky ways, but, for now, nullptr. info.type = isAbiCppException(currentException) ? currentException->exceptionType : nullptr; if (traceStack) { LOG_IF(DFATAL, !trace) << "Invalid trace stack for exception of type: " << (info.type ? folly::demangle(*info.type) : "null"); if (!trace) { return {}; } info.frames.assign( trace->addresses, trace->addresses + trace->frameCount); trace = traceStack->next(trace); } currentException = currentException->nextException; exceptions.push_back(std::move(info)); } LOG_IF(DFATAL, trace) << "Invalid trace stack!"; return exceptions; } namespace { std::terminate_handler origTerminate = abort; std::unexpected_handler origUnexpected = abort; void dumpExceptionStack(const char* prefix) { auto exceptions = getCurrentExceptions(); if (exceptions.empty()) { return; } LOG(ERROR) << prefix << ", exception stack follows"; for (auto& exc : exceptions) { LOG(ERROR) << exc << "\n"; } LOG(ERROR) << "exception stack complete"; } void terminateHandler() { dumpExceptionStack("terminate() called"); origTerminate(); } void unexpectedHandler() { dumpExceptionStack("Unexpected exception"); origUnexpected(); } } // namespace void installHandlers() { struct Once { Once() { origTerminate = std::set_terminate(terminateHandler); origUnexpected = std::set_unexpected(unexpectedHandler); } }; static Once once; } } // namespace exception_tracer } // namespace folly <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cstring> #include <iostream> #include <ostream> #include <vector> #include <visionaray/gl/compositing.h> #include <visionaray/gl/handle.h> #include <visionaray/gl/program.h> #include <visionaray/gl/shader.h> #include <visionaray/gl/util.h> #include <visionaray/pixel_format.h> namespace visionaray { namespace gl { //------------------------------------------------------------------------------------------------- // depth compositor private implementation // struct depth_compositor::impl { #if !defined(VSNRAY_OPENGL_LEGACY) impl() : prog(glCreateProgram()) , frag(glCreateShader(GL_FRAGMENT_SHADER)) { frag.set_source(R"( uniform sampler2D color_tex; uniform sampler2D depth_tex; void main(void) { gl_FragColor = texture2D(color_tex, gl_TexCoord[0].xy); gl_FragDepth = texture2D(depth_tex, gl_TexCoord[0].xy).x; } )"); frag.compile(); if (!frag.check_compiled()) { return; } prog.attach_shader(frag); prog.link(); if (!prog.check_linked()) { return; } color_loc = glGetUniformLocation(prog.get(), "color_tex"); depth_loc = glGetUniformLocation(prog.get(), "depth_tex"); } ~impl() { prog.detach_shader(frag); } // GL color texture handle gl::texture color_texture; // GL color texture handle gl::texture depth_texture; // The program gl::program prog; // The fragment shader gl::shader frag; // Uniform location of color texture GLint color_loc; // Uniform location of depth texture GLint depth_loc; void enable_program() const; void disable_program() const; void set_texture_params() const; #else pixel_format_info color_info; pixel_format_info depth_info; GLvoid const* depth_buffer = nullptr; GLvoid const* color_buffer = nullptr; int width; int height; #endif }; #if !defined(VSNRAY_OPENGL_LEGACY) void depth_compositor::impl::enable_program() const { prog.enable(); glUniform1i(color_loc, 0); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, color_texture.get()); glUniform1i(depth_loc, 1); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, depth_texture.get()); } void depth_compositor::impl::disable_program() const { prog.disable(); } void depth_compositor::impl::set_texture_params() const { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } #endif //------------------------------------------------------------------------------------------------- // depth compositor public interface // depth_compositor::depth_compositor() : impl_(new impl) { } depth_compositor::~depth_compositor() { } void depth_compositor::composite_textures() const { #if !defined(VSNRAY_OPENGL_LEGACY) // Store OpenGL state GLint active_texture = GL_TEXTURE0; GLboolean depth_test = GL_FALSE; glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture); glGetBooleanv(GL_DEPTH_TEST, &depth_test); glEnable(GL_DEPTH_TEST); impl_->enable_program(); gl::draw_full_screen_quad(); impl_->disable_program(); // Restore OpenGL state glActiveTexture(active_texture); if (depth_test) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } #else glPushAttrib( GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_ENABLE_BIT ); glEnable(GL_STENCIL_TEST); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glStencilFunc(GL_ALWAYS, 1, 1); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); gl::blend_pixels( impl_->width, impl_->height, impl_->depth_info.format, impl_->depth_info.type, impl_->depth_buffer ); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glStencilFunc(GL_EQUAL, 1, 1); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glDisable(GL_DEPTH_TEST); gl::blend_pixels( impl_->width, impl_->height, impl_->color_info.format, impl_->color_info.type, impl_->color_buffer ); glPopAttrib(); #endif } void depth_compositor::display_color_texture() const { #if !defined(VSNRAY_OPENGL_LEGACY) gl::blend_texture(impl_->color_texture.get()); #else gl::blend_pixels( impl_->width, impl_->height, impl_->color_info.format, impl_->color_info.type, impl_->color_buffer ); #endif } void depth_compositor::setup_color_texture(pixel_format_info info, GLsizei w, GLsizei h) { #if !defined(VSNRAY_OPENGL_LEGACY) impl_->color_texture.reset( create_texture() ); glBindTexture(GL_TEXTURE_2D, impl_->color_texture.get()); impl_->set_texture_params(); alloc_texture(info, w, h); #else impl_->color_info = info; impl_->width = w; impl_->height = h; #endif } void depth_compositor::setup_depth_texture(pixel_format_info info, GLsizei w, GLsizei h) { #if !defined(VSNRAY_OPENGL_LEGACY) impl_->depth_texture.reset( create_texture() ); glBindTexture(GL_TEXTURE_2D, impl_->depth_texture.get()); impl_->set_texture_params(); alloc_texture(info, w, h); #else impl_->depth_info = info; impl_->width = w; impl_->height = h; #endif } void depth_compositor::update_color_texture( pixel_format_info info, GLsizei w, GLsizei h, GLvoid const* data ) const { #if !defined(VSNRAY_OPENGL_LEGACY) glBindTexture(GL_TEXTURE_2D, impl_->color_texture.get()); gl::update_texture( info, w, h, data ); #else impl_->color_info = info; impl_->width = w; impl_->height = h; impl_->color_buffer = data; #endif } void depth_compositor::update_depth_texture( pixel_format_info info, GLsizei w, GLsizei h, GLvoid const* data ) const { #if !defined(VSNRAY_OPENGL_LEGACY) glBindTexture(GL_TEXTURE_2D, impl_->depth_texture.get()); gl::update_texture( info, w, h, data ); #else impl_->depth_info = info; impl_->width = w; impl_->height = h; impl_->depth_buffer = data; #endif } } // gl } // visionaray <commit_msg>Draw color texture in a shader<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cstring> #include <iostream> #include <ostream> #include <vector> #include <visionaray/gl/compositing.h> #include <visionaray/gl/handle.h> #include <visionaray/gl/program.h> #include <visionaray/gl/shader.h> #include <visionaray/gl/util.h> #include <visionaray/pixel_format.h> namespace visionaray { namespace gl { #if !defined(VSNRAY_OPENGL_LEGACY) //------------------------------------------------------------------------------------------------- // Shader program to display color texture w/o depth compositing // struct color_program { color_program(); ~color_program(); // The program gl::program prog; // The fragment shader gl::shader frag; // Uniform location of color texture GLint color_loc; void enable(gl::texture const& color_texture) const; void disable() const; }; //------------------------------------------------------------------------------------------------- // color program implementation // color_program::color_program() : prog(glCreateProgram()) , frag(glCreateShader(GL_FRAGMENT_SHADER)) { frag.set_source(R"( uniform sampler2D color_tex; void main(void) { gl_FragColor = texture2D(color_tex, gl_TexCoord[0].xy); } )"); frag.compile(); if (!frag.check_compiled()) { return; } prog.attach_shader(frag); prog.link(); if (!prog.check_linked()) { return; } color_loc = glGetUniformLocation(prog.get(), "color_tex"); } color_program::~color_program() { prog.detach_shader(frag); } void color_program::enable(gl::texture const& color_texture) const { prog.enable(); glUniform1i(color_loc, 0); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, color_texture.get()); } void color_program::disable() const { prog.disable(); } //------------------------------------------------------------------------------------------------- // Shader program to composite depth textures // struct depth_program { depth_program(); ~depth_program(); // The program gl::program prog; // The fragment shader gl::shader frag; // Uniform location of color texture GLint color_loc; // Uniform location of depth texture GLint depth_loc; void enable(gl::texture const& color_texture, gl::texture const& depth_texture) const; void disable() const; }; //------------------------------------------------------------------------------------------------- // depth program implementation // depth_program::depth_program() : prog(glCreateProgram()) , frag(glCreateShader(GL_FRAGMENT_SHADER)) { frag.set_source(R"( uniform sampler2D color_tex; uniform sampler2D depth_tex; void main(void) { gl_FragColor = texture2D(color_tex, gl_TexCoord[0].xy); gl_FragDepth = texture2D(depth_tex, gl_TexCoord[0].xy).x; } )"); frag.compile(); if (!frag.check_compiled()) { return; } prog.attach_shader(frag); prog.link(); if (!prog.check_linked()) { return; } color_loc = glGetUniformLocation(prog.get(), "color_tex"); depth_loc = glGetUniformLocation(prog.get(), "depth_tex"); } depth_program::~depth_program() { prog.detach_shader(frag); } void depth_program::enable( gl::texture const& color_texture, gl::texture const& depth_texture ) const { prog.enable(); glUniform1i(color_loc, 0); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, color_texture.get()); glUniform1i(depth_loc, 1); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, depth_texture.get()); } void depth_program::disable() const { prog.disable(); } #endif // !VSNRAY_OPENGL_LEGACY //------------------------------------------------------------------------------------------------- // depth compositor private implementation // struct depth_compositor::impl { #if !defined(VSNRAY_OPENGL_LEGACY) // Shader program to only display color texture w/o depth compositing color_program color_prog; // Shader program for depth compositing depth_program depth_prog; // GL color texture handle gl::texture color_texture; // GL color texture handle gl::texture depth_texture; void set_texture_params() const; #else pixel_format_info color_info; pixel_format_info depth_info; GLvoid const* depth_buffer = nullptr; GLvoid const* color_buffer = nullptr; int width; int height; #endif }; #if !defined(VSNRAY_OPENGL_LEGACY) void depth_compositor::impl::set_texture_params() const { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } #endif //------------------------------------------------------------------------------------------------- // depth compositor public interface // depth_compositor::depth_compositor() : impl_(new impl) { } depth_compositor::~depth_compositor() { } void depth_compositor::composite_textures() const { #if !defined(VSNRAY_OPENGL_LEGACY) // Store OpenGL state GLint active_texture = GL_TEXTURE0; GLboolean depth_test = GL_FALSE; glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture); glGetBooleanv(GL_DEPTH_TEST, &depth_test); glEnable(GL_DEPTH_TEST); impl_->depth_prog.enable(impl_->color_texture, impl_->depth_texture); gl::draw_full_screen_quad(); impl_->depth_prog.disable(); // Restore OpenGL state glActiveTexture(active_texture); if (depth_test) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } #else glPushAttrib( GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_ENABLE_BIT ); glEnable(GL_STENCIL_TEST); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glStencilFunc(GL_ALWAYS, 1, 1); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); gl::blend_pixels( impl_->width, impl_->height, impl_->depth_info.format, impl_->depth_info.type, impl_->depth_buffer ); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glStencilFunc(GL_EQUAL, 1, 1); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glDisable(GL_DEPTH_TEST); gl::blend_pixels( impl_->width, impl_->height, impl_->color_info.format, impl_->color_info.type, impl_->color_buffer ); glPopAttrib(); #endif } void depth_compositor::display_color_texture() const { #if !defined(VSNRAY_OPENGL_LEGACY) // Store OpenGL state GLint active_texture = GL_TEXTURE0; glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture); impl_->color_prog.enable(impl_->color_texture); gl::draw_full_screen_quad(); impl_->color_prog.disable(); // Restore OpenGL state glActiveTexture(active_texture); #else gl::blend_pixels( impl_->width, impl_->height, impl_->color_info.format, impl_->color_info.type, impl_->color_buffer ); #endif } void depth_compositor::setup_color_texture(pixel_format_info info, GLsizei w, GLsizei h) { #if !defined(VSNRAY_OPENGL_LEGACY) impl_->color_texture.reset( create_texture() ); glBindTexture(GL_TEXTURE_2D, impl_->color_texture.get()); impl_->set_texture_params(); alloc_texture(info, w, h); #else impl_->color_info = info; impl_->width = w; impl_->height = h; #endif } void depth_compositor::setup_depth_texture(pixel_format_info info, GLsizei w, GLsizei h) { #if !defined(VSNRAY_OPENGL_LEGACY) impl_->depth_texture.reset( create_texture() ); glBindTexture(GL_TEXTURE_2D, impl_->depth_texture.get()); impl_->set_texture_params(); alloc_texture(info, w, h); #else impl_->depth_info = info; impl_->width = w; impl_->height = h; #endif } void depth_compositor::update_color_texture( pixel_format_info info, GLsizei w, GLsizei h, GLvoid const* data ) const { #if !defined(VSNRAY_OPENGL_LEGACY) glBindTexture(GL_TEXTURE_2D, impl_->color_texture.get()); gl::update_texture( info, w, h, data ); #else impl_->color_info = info; impl_->width = w; impl_->height = h; impl_->color_buffer = data; #endif } void depth_compositor::update_depth_texture( pixel_format_info info, GLsizei w, GLsizei h, GLvoid const* data ) const { #if !defined(VSNRAY_OPENGL_LEGACY) glBindTexture(GL_TEXTURE_2D, impl_->depth_texture.get()); gl::update_texture( info, w, h, data ); #else impl_->depth_info = info; impl_->width = w; impl_->height = h; impl_->depth_buffer = data; #endif } } // gl } // visionaray <|endoftext|>
<commit_before>// read the standard input a line at a time. #include <iostream> #include <string> using std::string; using std::cin; using std::cout; using std::endl; using std::getline; int main() { string input; while (getline(cin, input)) cout << input << endl; return 0; } <commit_msg>Update ex3_2a.cpp<commit_after>// read the standard input a line at a time. #include <iostream> #include <string> using std::string; using std::cin; using std::cout; using std::endl; using std::getline; int main() { for (string str; getline(cin, str); cout << str << endl); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <stdexcept> using std::cin; using std::cout; using std::endl; using std::runtime_error; int main(void) { int a, b; cout << "Input two integers: "; while (cin >> a >> b) { try { if (b == 0) throw runtime_error("divisor is 0"); cout << static_cast<double>(a) / b << endl; cout << "Input two integers: "; } catch (runtime_error err) { cout << err.what() ; cout << "\nTry Again? Enter y or n:" << endl; char c; cin >> c; if (!cin || c == 'n') break; } } return 0; } <commit_msg>Update ex5_25.cpp<commit_after>#include <iostream> #include <stdexcept> using std::cin; using std::cout; using std::endl; using std::runtime_error; int main(void) { int a, b; cout << "Input two integers: "; while (cin >> a >> b) { try { if (b == 0) throw runtime_error("divisor is 0"); cout << static_cast<double>(a) / b << endl; cout << "Input two integers: "; } catch (runtime_error err) { cout << err.what() ; cout << "\nTry Again? Enter y or n:" << endl; char c; cin >> c; if (!cin || c == 'n') break; else cout << "Input two integers: "; } } return 0; } <|endoftext|>
<commit_before>//! @Alan //! //! Exercise 6.44: Rewrite the isShorter function from § 6.2.2 (p. 211) to be inline. //! #include <iostream> #include <string> #include <vector> #include <iterator> using namespace std; inline bool isShorter(const string &s1, const string &s2) { return s1.size() < s2.size(); } int main() { } <commit_msg>Update ex6_44.cpp<commit_after>//! @Alan //! //! Exercise 6.44: Rewrite the isShorter function from § 6.2.2 (p. 211) to be inline. //! #include <iostream> #include <string> using std::string; inline bool isShorter(const string &s1, const string &s2) // defining in the header more better. { return s1.size() < s2.size(); } int main() { std::cout << isShorter("pezy", "mooophy") << std::endl; } <|endoftext|>
<commit_before>// // ex9_20.cpp // Exercise 9.20 // // Created by pezy on 12/3/14. // Copyright (c) 2014 pezy. All rights reserved. // // @Brief Write a program to copy elements from a list<int> into two deques. // The even-valued elements should go into one deque and the odd ones // into the other. #include <iostream> #include <deque> #include <list> using std::deque; using std::list; using std::cout; using std::cin; using std::endl; int main() { list<int> l{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; deque<int> odd, even; for (auto i : l) (i & 0x1 ? odd : even).push_back(i); for (auto i : odd) cout << i << " "; cout << endl; for (auto i : even) cout << i << " "; cout << endl; return 0; } <commit_msg>Update ex9_20.cpp<commit_after>// // ex9_20.cpp // Exercise 9.20 // // Created by pezy on 12/3/14. // Copyright (c) 2014 pezy. All rights reserved. // // @Brief Write a program to copy elements from a list<int> into two deques. // The even-valued elements should go into one deque and the odd ones // into the other. #include <iostream> #include <list> #include <deque> using std::cin; using std::cout; using std::endl; using std::list; using std::deque; int main() { list<int> ilst{1,2,3,4,5,6,7,8,9,10}; deque<int> odd, even; for(auto i:ilst) ((i & 0x1) ? odd : even).push_back(i); for(auto i: odd) cout<<i<<" "; cout<<endl; for(auto i: even) cout<<i<<" "; cout<<endl; } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * 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 <assert.h> #include <string.h> #include <getopt.h> #include <iostream> #include <memory> #include "cli.hpp" #include <brotli/encode.h> #include <zlib.h> // for crc32 #include "trace_file.hpp" #include "trace_ostream.hpp" static const char *synopsis = "Repack a trace file with different compression."; static void usage(void) { std::cout << "usage: apitrace repack [options] <in-trace-file> <out-trace-file>\n" << synopsis << "\n" << "\n" << "Snappy compression allows for faster replay and smaller memory footprint,\n" << "at the expense of a slightly smaller compression ratio than zlib\n" << "\n" << " -b,--brotli[=QUALITY] Use Brotli compression (quality 0-11, default 9)\n" << " -z,--zlib Use ZLib compression\n" << "\n"; } const static char * shortOptions = "hbz"; const static struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"brotli", optional_argument, 0, 'b'}, {"zlib", no_argument, 0, 'z'}, {0, 0, 0, 0} }; enum Format { FORMAT_SNAPPY = 0, FORMAT_ZLIB, FORMAT_BROTLI, }; static int repack_generic(trace::File *inFile, trace::OutStream *outFile) { const size_t size = 8192; char *buf = new char[size]; size_t read; while ((read = inFile->read(buf, size)) != 0) { outFile->write(buf, read); } delete [] buf; return EXIT_SUCCESS; } static int repack_brotli(trace::File *inFile, const char *outFileName, int quality) { BrotliEncoderState *s = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); if (!s) { return EXIT_FAILURE; } // Brotli default quality is 11, but there are problems using quality // higher than 9: // // - Some traces cause compression to be extremely slow. Possibly the same // issue as https://github.com/google/brotli/issues/330 // - Some traces get lower compression ratio with 11 than 9. Possibly the // same issue as https://github.com/google/brotli/issues/222 BrotliEncoderSetParameter(s, BROTLI_PARAM_QUALITY, 9); // The larger the window, the higher the compression ratio and // decompression speeds, so choose the maximum. BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, 24); if (quality > 0) { BrotliEncoderSetParameter(s, BROTLI_PARAM_QUALITY, quality); } FILE *fout = fopen(outFileName, "wb"); if (!fout) { return EXIT_FAILURE; } uLong inCrc = crc32(0L, Z_NULL, 0); static const size_t kFileBufferSize = 1 << 16; uint8_t *input = (uint8_t *)malloc(kFileBufferSize * 2); uint8_t *output = input + kFileBufferSize; size_t available_in = 0; const uint8_t *next_in = nullptr; size_t available_out = kFileBufferSize; uint8_t *next_out = output; bool is_eof = false; do { if (available_in == 0 && !is_eof) { available_in = inFile->read(input, kFileBufferSize); next_in = input; if (available_in == 0) { is_eof = true; } else { crc32(inCrc, reinterpret_cast<const Bytef *>(input), available_in); } } if (!BrotliEncoderCompressStream(s, is_eof ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS, &available_in, &next_in, &available_out, &next_out, nullptr)) { std::cerr << "error: failed to compress data\n"; return EXIT_FAILURE; } if (available_out != kFileBufferSize) { size_t out_size = kFileBufferSize - available_out; fwrite(output, 1, out_size, fout); if (ferror(fout)) { std::cerr << "error: failed to write to " << outFileName << "\n"; return EXIT_FAILURE; } available_out = kFileBufferSize; next_out = output; } } while(!BrotliEncoderIsFinished(s)); fclose(fout); BrotliEncoderDestroyInstance(s); // Do a CRC check std::unique_ptr<trace::File> outFileIn(trace::File::createBrotli()); if (!outFileIn->open(outFileName)) { std::cerr << "error: failed to open " << outFileName << " for reading\n"; return EXIT_FAILURE; } uLong outCrc = crc32(0L, Z_NULL, 0); do { available_in = inFile->read(input, kFileBufferSize); crc32(inCrc, reinterpret_cast<const Bytef *>(input), available_in); } while (available_in > 0); if (inCrc != outCrc) { std::cerr << "error: CRC mismatch reading " << outFileName << "\n"; return EXIT_FAILURE; } free(input); return EXIT_SUCCESS; } static int repack(const char *inFileName, const char *outFileName, Format format, int quality) { int ret = EXIT_FAILURE; trace::File *inFile = trace::File::createForRead(inFileName); if (!inFile) { return 1; } trace::OutStream *outFile = nullptr; if (format == FORMAT_SNAPPY) { outFile = trace::createSnappyStream(outFileName); } else if (format == FORMAT_BROTLI) { ret = repack_brotli(inFile, outFileName, quality); delete inFile; return ret; } else if (format == FORMAT_ZLIB) { outFile = trace::createZLibStream(outFileName); } if (outFile) { ret = repack_generic(inFile, outFile); delete outFile; } delete inFile; return ret; } static int command(int argc, char *argv[]) { Format format = FORMAT_SNAPPY; int opt; int quality = -1; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) { switch (opt) { case 'h': usage(); return 0; case 'b': format = FORMAT_BROTLI; if (optarg) { quality = atoi(optarg); } break; case 'z': format = FORMAT_ZLIB; break; default: std::cerr << "error: unexpected option `" << (char)opt << "`\n"; usage(); return 1; } } if (argc != optind + 2) { std::cerr << "error: insufficient number of arguments\n"; usage(); return 1; } return repack(argv[optind], argv[optind + 1], format, quality); } const Command repack_command = { "repack", synopsis, usage, command }; <commit_msg>cli: Use default brotli quality level (11).<commit_after>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * 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 <assert.h> #include <string.h> #include <getopt.h> #include <iostream> #include <memory> #include "cli.hpp" #include <brotli/encode.h> #include <zlib.h> // for crc32 #include "trace_file.hpp" #include "trace_ostream.hpp" static const char *synopsis = "Repack a trace file with different compression."; static void usage(void) { std::cout << "usage: apitrace repack [options] <in-trace-file> <out-trace-file>\n" << synopsis << "\n" << "\n" << "Snappy compression allows for faster replay and smaller memory footprint,\n" << "at the expense of a slightly smaller compression ratio than zlib\n" << "\n" << " -b,--brotli[=QUALITY] Use Brotli compression (quality " << BROTLI_MIN_QUALITY << "-" << BROTLI_MAX_QUALITY << ", default " << BROTLI_DEFAULT_QUALITY << ")\n" << " -z,--zlib Use ZLib compression\n" << "\n"; } const static char * shortOptions = "hbz"; const static struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"brotli", optional_argument, 0, 'b'}, {"zlib", no_argument, 0, 'z'}, {0, 0, 0, 0} }; enum Format { FORMAT_SNAPPY = 0, FORMAT_ZLIB, FORMAT_BROTLI, }; static int repack_generic(trace::File *inFile, trace::OutStream *outFile) { const size_t size = 8192; char *buf = new char[size]; size_t read; while ((read = inFile->read(buf, size)) != 0) { outFile->write(buf, read); } delete [] buf; return EXIT_SUCCESS; } static int repack_brotli(trace::File *inFile, const char *outFileName, int quality) { BrotliEncoderState *s = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); if (!s) { return EXIT_FAILURE; } // Brotli default quality is 11. There used to be problems using quality // higher than 9: // // - Some traces cause compression to be extremely slow. Possibly the same // issue as https://github.com/google/brotli/issues/330 // - Some traces get lower compression ratio with 11 than 9. Possibly the // same issue as https://github.com/google/brotli/issues/222 // // but not any more. BrotliEncoderSetParameter(s, BROTLI_PARAM_QUALITY, quality); // The larger the window, the higher the compression ratio and // decompression speeds, so choose the maximum. BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, 24); FILE *fout = fopen(outFileName, "wb"); if (!fout) { return EXIT_FAILURE; } uLong inCrc = crc32(0L, Z_NULL, 0); static const size_t kFileBufferSize = 1 << 16; uint8_t *input = (uint8_t *)malloc(kFileBufferSize * 2); uint8_t *output = input + kFileBufferSize; size_t available_in = 0; const uint8_t *next_in = nullptr; size_t available_out = kFileBufferSize; uint8_t *next_out = output; bool is_eof = false; do { if (available_in == 0 && !is_eof) { available_in = inFile->read(input, kFileBufferSize); next_in = input; if (available_in == 0) { is_eof = true; } else { crc32(inCrc, reinterpret_cast<const Bytef *>(input), available_in); } } if (!BrotliEncoderCompressStream(s, is_eof ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS, &available_in, &next_in, &available_out, &next_out, nullptr)) { std::cerr << "error: failed to compress data\n"; return EXIT_FAILURE; } if (available_out != kFileBufferSize) { size_t out_size = kFileBufferSize - available_out; fwrite(output, 1, out_size, fout); if (ferror(fout)) { std::cerr << "error: failed to write to " << outFileName << "\n"; return EXIT_FAILURE; } available_out = kFileBufferSize; next_out = output; } } while(!BrotliEncoderIsFinished(s)); fclose(fout); BrotliEncoderDestroyInstance(s); // Do a CRC check std::unique_ptr<trace::File> outFileIn(trace::File::createBrotli()); if (!outFileIn->open(outFileName)) { std::cerr << "error: failed to open " << outFileName << " for reading\n"; return EXIT_FAILURE; } uLong outCrc = crc32(0L, Z_NULL, 0); do { available_in = inFile->read(input, kFileBufferSize); crc32(inCrc, reinterpret_cast<const Bytef *>(input), available_in); } while (available_in > 0); if (inCrc != outCrc) { std::cerr << "error: CRC mismatch reading " << outFileName << "\n"; return EXIT_FAILURE; } free(input); return EXIT_SUCCESS; } static int repack(const char *inFileName, const char *outFileName, Format format, int quality) { int ret = EXIT_FAILURE; trace::File *inFile = trace::File::createForRead(inFileName); if (!inFile) { return 1; } trace::OutStream *outFile = nullptr; if (format == FORMAT_SNAPPY) { outFile = trace::createSnappyStream(outFileName); } else if (format == FORMAT_BROTLI) { ret = repack_brotli(inFile, outFileName, quality); delete inFile; return ret; } else if (format == FORMAT_ZLIB) { outFile = trace::createZLibStream(outFileName); } if (outFile) { ret = repack_generic(inFile, outFile); delete outFile; } delete inFile; return ret; } static int command(int argc, char *argv[]) { Format format = FORMAT_SNAPPY; int opt; int quality = BROTLI_DEFAULT_QUALITY; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) { switch (opt) { case 'h': usage(); return 0; case 'b': format = FORMAT_BROTLI; if (optarg) { quality = atoi(optarg); if (quality < BROTLI_MIN_QUALITY || quality > BROTLI_MAX_QUALITY) { std::cerr << "error: brotli quality must be between " << BROTLI_MIN_QUALITY << " and " << BROTLI_MAX_QUALITY << std::endl; return 1; } } break; case 'z': format = FORMAT_ZLIB; break; default: std::cerr << "error: unexpected option `" << (char)opt << "`\n"; usage(); return 1; } } if (argc != optind + 2) { std::cerr << "error: insufficient number of arguments\n"; usage(); return 1; } return repack(argv[optind], argv[optind + 1], format, quality); } const Command repack_command = { "repack", synopsis, usage, command }; <|endoftext|>
<commit_before>#include "Communicator.hpp" #include "Addressing.hpp" #include "GlobalAllocator.hpp" #include "LocaleSharedMemory.hpp" #include "ParallelLoop.hpp" #include <utility> #include <queue> DECLARE_bool(flat_combining); namespace Grappa { /// Mixin for adding common global data structure functionality, such as mirrored /// allocation on all cores. template< typename Base, Core MASTER = 0 > class MirroredGlobal : public Base { char pad[block_size - sizeof(Base)]; public: template <typename... Args> explicit MirroredGlobal(Args&&... args): Base(std::forward<Args...>(args...)) {} explicit MirroredGlobal(): Base() {} /// Allocate and call init() on all instances of Base /// /// @param init Lambda of the form: void init(Base*) /// /// @b Example: /// @code /// auto c = MirroredGlobal<Counter>::create([](Counter* c){ new (c) Counter(0); }); /// @endcode template< typename F > static GlobalAddress<MirroredGlobal<Base>> create(F init) { auto a = mirrored_global_alloc<MirroredGlobal<Base>>(); call_on_all_cores([a,init]{ init(static_cast<Base*>(a.localize())); }); return a; } /// Allocate an instance on all cores and initialize with default constructor. /// /// @note Requires Base class to have a default constructor. static GlobalAddress<MirroredGlobal<Base>> create() { auto a = mirrored_global_alloc<MirroredGlobal>(); call_on_all_cores([a]{ new (a.localize()) MirroredGlobal<Base>(); }); return a; } void destroy() { auto a = this->self; call_on_all_cores([a]{ a->~MirroredGlobal<Base>(); }); global_free(a); } }; template <typename T> class FlatCombiner { struct Flusher { Flusher * inflight; T * id; Worker * sender; ConditionVariable cv; Flusher(T * id): id(id), sender(nullptr), inflight(nullptr) { VLOG(3) << "created (" << this << ")"; } ~Flusher() { locale_free(id); } }; Flusher * current; // std::queue<Flusher*> inflight; public: FlatCombiner(T * initial): current(new Flusher(initial)) {} ~FlatCombiner() { auto h = current; while (h != nullptr) { auto t = h->inflight; delete h; h = t; } } // template <typename... Args> // explicit FlatCombiner(Args&&... args) // : current(new Flusher(new T(std::forward<Args...>(args...)))) // , inflight(nullptr) // , sender(nullptr) // { } // // // in case it's a no-arg constructor // explicit FlatCombiner(): FlatCombiner() {} // for arbitrary return type defined by base class // auto operator()(Args&&... args) -> decltype(this->T::operator()(std::forward<Args...>(args...))) { template< typename F > void combine(F func) { auto s = current; func(*s->id); if (s->id->is_full()) { current = new Flusher(s->id->clone_fresh()); current->inflight = s; if (s->sender == nullptr) { VLOG(3) << "flushing on full"; flush(s); return; } // otherwise someone else assigned to send... } else if (current->inflight == nullptr) { // always need at least one in flight current->inflight = s; if (s->sender == nullptr) { current = new Flusher(s->id->clone_fresh()); current->inflight = s; VLOG(3) << "flush because none inflight"; flush(s); return; } } // not my turn yet Grappa::wait(&s->cv); // on wake... if (&current_worker() == s->sender) { // I was assigned to send if (s == current) { current = new Flusher(s->id->clone_fresh()); current->inflight = s; } VLOG(3) << "flush by waken worker"; flush(s); return; } } void flush(Flusher * s) { s->sender = &current_worker(); // (if not set already) VLOG(3) << "flushing (" << s->sender << "), s(" << s << ")"; s->id->sync(); broadcast(&s->cv); // wake our people if (current->cv.waiters_ != 0 && current->sender == nullptr) { // atomically claim it so no one else tries to send in the meantime current->inflight = current; // wake someone and tell them to send current->sender = impl::get_waiters(&current->cv); signal(&current->cv); VLOG(3) << "signaled " << current->sender; } else { current->inflight = nullptr; } // auto t = current; // while (t->inflight != s) t = t->inflight; // t->inflight = s->inflight; // s->inflight = nullptr; s->sender = nullptr; delete s; } }; // template< T > // class ProxiedGlobal : public T { // using Master = typename T::Master; // using Proxy = typename T::Proxy; // public: // GlobalAddress<ProxiedGlobal<T>> self; // // template< typename... Args > // static GlobalAddress<ProxiedGlobal<T>> create(Args&&... args) { // static_assert(sizeof(ProxiedGlobal<T>) % block_size == 0, // "must pad global proxy to multiple of block_size"); // // allocate enough space that we are guaranteed to get one on each core at same location // auto qac = global_alloc<char>(cores()*(sizeof(ProxiedGlobal<T>)+block_size)); // while (qac.core() != MASTER_CORE) qac++; // auto qa = static_cast<GlobalAddress<ProxiedGlobal<T>>>(qac); // CHECK_EQ(qa, qa.block_min()); // CHECK_EQ(qa.core(), MASTER_CORE); // // // intialize all cores' local versions // call_on_all_cores([=]{ // new (s.self.localize()) ProxiedGlobal<T>(args...); // }); // // return qa; // } // // void destroy() { // auto q = shared.self; // global_free(q->shared.base); // call_on_all_cores([q]{ q->~GlobalVector(); }); // global_free(q); // } // // }; // } // namespace Grappa <commit_msg>Actually only need an inflight count, also some cleanup<commit_after>#include "Communicator.hpp" #include "Addressing.hpp" #include "GlobalAllocator.hpp" #include "LocaleSharedMemory.hpp" #include "ParallelLoop.hpp" #include <utility> #include <queue> DECLARE_bool(flat_combining); namespace Grappa { /// Mixin for adding common global data structure functionality, such as mirrored /// allocation on all cores. template< typename Base, Core MASTER = 0 > class MirroredGlobal : public Base { char pad[block_size - sizeof(Base)]; public: template <typename... Args> explicit MirroredGlobal(Args&&... args): Base(std::forward<Args...>(args...)) {} explicit MirroredGlobal(): Base() {} /// Allocate and call init() on all instances of Base /// /// @param init Lambda of the form: void init(Base*) /// /// @b Example: /// @code /// auto c = MirroredGlobal<Counter>::create([](Counter* c){ new (c) Counter(0); }); /// @endcode template< typename F > static GlobalAddress<MirroredGlobal<Base>> create(F init) { auto a = mirrored_global_alloc<MirroredGlobal<Base>>(); call_on_all_cores([a,init]{ init(static_cast<Base*>(a.localize())); }); return a; } /// Allocate an instance on all cores and initialize with default constructor. /// /// @note Requires Base class to have a default constructor. static GlobalAddress<MirroredGlobal<Base>> create() { auto a = mirrored_global_alloc<MirroredGlobal>(); call_on_all_cores([a]{ new (a.localize()) MirroredGlobal<Base>(); }); return a; } void destroy() { auto a = this->self; call_on_all_cores([a]{ a->~MirroredGlobal<Base>(); }); global_free(a); } }; template <typename T> class FlatCombiner { struct Flusher { T * id; Worker * sender; ConditionVariable cv; Flusher(T * id): id(id), sender(nullptr) {} ~Flusher() { locale_free(id); } }; Flusher * current; size_t inflight; public: FlatCombiner(T * initial): current(new Flusher(initial)), inflight(0) {} ~FlatCombiner() { delete current; } // template <typename... Args> // explicit FlatCombiner(Args&&... args) // : current(new Flusher(new T(std::forward<Args...>(args...)))) // , inflight(nullptr) // , sender(nullptr) // { } // // // in case it's a no-arg constructor // explicit FlatCombiner(): FlatCombiner() {} // for arbitrary return type defined by base class // auto operator()(Args&&... args) -> decltype(this->T::operator()(std::forward<Args...>(args...))) { template< typename F > void combine(F func) { auto s = current; func(*s->id); if (s->id->is_full()) { current = new Flusher(s->id->clone_fresh()); if (s->sender == nullptr) { inflight++; DVLOG(3) << "flushing on full"; flush(s); return; } // otherwise someone else assigned to send... } else if (inflight == 0) { inflight++; // always need at least one in flight if (s->sender == nullptr) { current = new Flusher(s->id->clone_fresh()); DVLOG(3) << "flush because none in flight"; flush(s); return; } } // not my turn yet Grappa::wait(&s->cv); // on wake... if (&current_worker() == s->sender) { // I was assigned to send if (s == current) { current = new Flusher(s->id->clone_fresh()); } DVLOG(3) << "flush by waken worker"; flush(s); return; } } void flush(Flusher * s) { s->sender = &current_worker(); // (if not set already) DVLOG(3) << "flushing (" << s->sender << "), s(" << s << ")"; s->id->sync(); broadcast(&s->cv); // wake our people if (current->cv.waiters_ != 0 && current->sender == nullptr) { // atomically claim it so no one else tries to send in the meantime // wake someone and tell them to send current->sender = impl::get_waiters(&current->cv); signal(&current->cv); DVLOG(3) << "signaled " << current->sender; } else { inflight--; } s->sender = nullptr; delete s; } }; // template< T > // class ProxiedGlobal : public T { // using Master = typename T::Master; // using Proxy = typename T::Proxy; // public: // GlobalAddress<ProxiedGlobal<T>> self; // // template< typename... Args > // static GlobalAddress<ProxiedGlobal<T>> create(Args&&... args) { // static_assert(sizeof(ProxiedGlobal<T>) % block_size == 0, // "must pad global proxy to multiple of block_size"); // // allocate enough space that we are guaranteed to get one on each core at same location // auto qac = global_alloc<char>(cores()*(sizeof(ProxiedGlobal<T>)+block_size)); // while (qac.core() != MASTER_CORE) qac++; // auto qa = static_cast<GlobalAddress<ProxiedGlobal<T>>>(qac); // CHECK_EQ(qa, qa.block_min()); // CHECK_EQ(qa.core(), MASTER_CORE); // // // intialize all cores' local versions // call_on_all_cores([=]{ // new (s.self.localize()) ProxiedGlobal<T>(args...); // }); // // return qa; // } // // void destroy() { // auto q = shared.self; // global_free(q->shared.base); // call_on_all_cores([q]{ q->~GlobalVector(); }); // global_free(q); // } // // }; // } // namespace Grappa <|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 "otbExtendedFilenameHelper.h" #include <boost/algorithm/string.hpp> namespace otb { void ExtendedFilenameHelper ::SetExtendedFileName(const char *extFname) { this->m_ExtendedFileName = extFname; std::vector<std::string> tmp1; std::vector<std::string> tmp2; if (!m_ExtendedFileName.empty()) { boost::split(tmp1, m_ExtendedFileName, boost::is_any_of("?"), boost::token_compress_on); this->SetSimpleFileName(tmp1[0]); if (tmp1.size()>1) { boost::split(tmp2, tmp1[1], boost::is_any_of("&"), boost::token_compress_on); for (unsigned int i=0; i<tmp2.size(); i++) { std::vector<std::string> tmp; boost::split(tmp, tmp2[i], boost::is_any_of("="), boost::token_compress_on); if (tmp.size()>1) { m_OptionMap[tmp[0]]=tmp[1]; } } } } } ExtendedFilenameHelper::OptionMapType ExtendedFilenameHelper ::GetOptionMap(void) const { return this->m_OptionMap; } } // end namespace otb <commit_msg>ENH: added duplicated option detection in extended filename<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 "otbExtendedFilenameHelper.h" #include <boost/algorithm/string.hpp> namespace otb { void ExtendedFilenameHelper ::SetExtendedFileName(const char *extFname) { this->m_ExtendedFileName = extFname; std::vector<std::string> tmp1; std::vector<std::string> tmp2; if (!m_ExtendedFileName.empty()) { boost::split(tmp1, m_ExtendedFileName, boost::is_any_of("?"), boost::token_compress_on); this->SetSimpleFileName(tmp1[0]); if (tmp1.size()>1) { boost::split(tmp2, tmp1[1], boost::is_any_of("&"), boost::token_compress_on); for (unsigned int i=0; i<tmp2.size(); i++) { std::vector<std::string> tmp; boost::split(tmp, tmp2[i], boost::is_any_of("="), boost::token_compress_on); if (tmp.size()>1) { if (m_OptionMap[tmp[0]].empty()) { m_OptionMap[tmp[0]]=tmp[1]; } else { itkWarningMacro("Duplicate option detected: " << tmp[0] << ". Using value " << tmp[1] << "."); } } } } } } ExtendedFilenameHelper::OptionMapType ExtendedFilenameHelper ::GetOptionMap(void) const { return this->m_OptionMap; } } // end namespace otb <|endoftext|>
<commit_before>/* * Copyright 2010 Utkin Dmitry * * 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. */ /* * This file is part of the WSF Staff project. * Please, visit http://code.google.com/p/staff for more information. */ #include <rise/common/ExceptionTemplate.h> #include <rise/common/exmacros.h> #include <axiom_soap_const.h> #include <axis2_options.h> #include <staff/common/Runtime.h> #include "Options.h" namespace staff { COptions::COptions(): m_pEnv(CRuntime::Inst().GetAxis2Env("staff_client")), m_bOwner(true) { m_pOptions = axis2_options_create(m_pEnv); } COptions::COptions(axis2_options_t* pOptions): m_pOptions(pOptions), m_pEnv(CRuntime::Inst().GetAxis2Env("staff_client")), m_bOwner(false) { } COptions::~COptions() { if (m_bOwner) { axis2_options_free(m_pOptions, m_pEnv); } CRuntime::Inst().FreeAxis2Env("staff_client"); } bool COptions::IsOwner() const { return m_bOwner; } void COptions::SetOwner(bool bOwner /*= true*/) { m_bOwner = bOwner; } std::string COptions::GetAction() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); const axis2_char_t* szAction = axis2_options_get_action(m_pOptions, m_pEnv); RISE_ASSERTS(szAction, "Can't get action"); return reinterpret_cast<const char*>(szAction); } void COptions::SetAction(const std::string& sAction) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_action(m_pOptions, m_pEnv, sAction.c_str()); } std::string COptions::GetFromAddress() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_from(m_pOptions, m_pEnv); RISE_ASSERTS(pEndpointRef, "Can't get WSA endpoint"); const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv); RISE_ASSERTS(szAddress, "Can't get WSA from address"); return reinterpret_cast<const char*>(szAddress); } void COptions::SetFromAddress(const std::string& sAddress) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str()); RISE_ASSERTS(pEndpointRef, "Can't create WSA endpoint"); axis2_options_set_from(m_pOptions, m_pEnv, pEndpointRef); } std::string COptions::GetToAddress() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_to(m_pOptions, m_pEnv); RISE_ASSERTS(pEndpointRef, "Can't get WSA endpoint"); const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv); RISE_ASSERTS(szAddress, "Can't get WSA to address"); return reinterpret_cast<const char*>(szAddress); } void COptions::SetToAddress(const std::string& sAddress) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str()); RISE_ASSERTS(pEndpointRef, "Can't create WSA endpoint"); axis2_options_set_to(m_pOptions, m_pEnv, pEndpointRef); } std::string COptions::GetReplyToAddress() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_reply_to(m_pOptions, m_pEnv); RISE_ASSERTS(pEndpointRef, "Can't get WSA endpoint"); const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv); RISE_ASSERTS(szAddress, "Can't get WSA reply to address"); return reinterpret_cast<const char*>(szAddress); } void COptions::SetReplyToAddress(const std::string& sAddress) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str()); RISE_ASSERTS(pEndpointRef, "Can't create WSA endpoint"); axis2_options_set_reply_to(m_pOptions, m_pEnv, pEndpointRef); } std::string COptions::GetFaultToAddress() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_fault_to(m_pOptions, m_pEnv); RISE_ASSERTS(pEndpointRef, "Can't get WSA endpoint"); const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv); RISE_ASSERTS(szAddress, "Can't get WSA address"); return reinterpret_cast<const char*>(szAddress); } void COptions::SetFaultToAddress(const std::string& sAddress) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str()); RISE_ASSERTS(pEndpointRef, "Can't create WSA endpoint"); axis2_options_set_fault_to(m_pOptions, m_pEnv, pEndpointRef); } void COptions::UseSeparateListener(bool bUseSeparateListener) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_use_separate_listener(m_pOptions, m_pEnv, bUseSeparateListener ? AXIS2_TRUE : AXIS2_FALSE); } bool COptions::IsUsingSeparateListener() { RISE_ASSERTS(m_pOptions, "Options is not initialized"); return axis2_options_get_use_separate_listener(m_pOptions, m_pEnv) == AXIS2_TRUE; } void COptions::SetHttpAuthInfo(const std::string& sUserName, const std::string& sPassword, const std::string& sAuthType) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_status_t nResult = axis2_options_set_http_auth_info(m_pOptions, m_pEnv, sUserName.c_str(), sPassword.c_str(), sAuthType.c_str()); RISE_ASSERTS(nResult == AXIS2_SUCCESS, "Failed to setup http auth info"); } void COptions::SetTestHttpAuth(bool bAuth) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_test_http_auth(m_pOptions, m_pEnv, bAuth ? AXIS2_TRUE : AXIS2_FALSE); } void COptions::SetProxyAuthInfo(const std::string& sUserName, const std::string& sPassword, const std::string& sAuthType) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_status_t nResult = axis2_options_set_proxy_auth_info(m_pOptions, m_pEnv, sUserName.c_str(), sPassword.c_str(), sAuthType.c_str()); RISE_ASSERTS(nResult == AXIS2_SUCCESS, "Failed to setup proxy auth info"); } void COptions::SetTestProxyAuth(bool bAuth) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_test_proxy_auth(m_pOptions, m_pEnv, bAuth ? AXIS2_TRUE : AXIS2_FALSE); } void COptions::SetTimeout(long lTimeout) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_timeout_in_milli_seconds(m_pOptions, m_pEnv, lTimeout); } std::string COptions::GetSoapVersionUri() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); const axis2_char_t* szUri = axis2_options_get_soap_version_uri(m_pOptions, m_pEnv); RISE_ASSERTS(szUri, "Can't get SOAP version URI"); return reinterpret_cast<const char*>(szUri); } void COptions::SetSoapVersionUri(const std::string& sSoapVersionUri) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_soap_version_uri(m_pOptions, m_pEnv, sSoapVersionUri.c_str()); } COptions::SoapVersion COptions::GetSoapVersion() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); int nVersion = axis2_options_get_soap_version(m_pOptions, m_pEnv); switch (nVersion) { case AXIOM_SOAP11: return Soap11; case AXIOM_SOAP12: return Soap12; default: return static_cast<SoapVersion>(nVersion); } } void COptions::SetSoapVersion(SoapVersion nSoapVersion) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); int nAxiomSoapVersion = 0; switch (nSoapVersion) { case Soap11: nAxiomSoapVersion = AXIOM_SOAP11; break; case Soap12: nAxiomSoapVersion = AXIOM_SOAP12; break; default: nAxiomSoapVersion = static_cast<soap_version>(nSoapVersion); } axis2_options_set_soap_version(m_pOptions, m_pEnv, nAxiomSoapVersion); } std::string COptions::GetSoapAction() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); const axutil_string_t* psAction = axis2_options_get_soap_action(m_pOptions, m_pEnv); RISE_ASSERTS(psAction, "Can't get SOAP action"); return reinterpret_cast<const char*>(axutil_string_get_buffer(psAction, m_pEnv)); } void COptions::SetSoapAction(const std::string& sSoapAction) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axutil_string_t* psSoapAction = axutil_string_create(m_pEnv, sSoapAction.c_str()); axis2_options_set_soap_action(m_pOptions, m_pEnv, psSoapAction); axutil_string_free(psSoapAction, m_pEnv); } void COptions::EnableRest(bool bEnable) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_enable_rest(m_pOptions, m_pEnv, bEnable ? AXIS2_TRUE : AXIS2_FALSE); } void COptions::SetHttpMethod(const std::string& sHttpMethod) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_http_method(m_pOptions, m_pEnv, sHttpMethod.c_str()); } bool COptions::IsMtomEnabled() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); return axis2_options_get_enable_mtom(m_pOptions, m_pEnv) == AXIS2_TRUE; } void COptions::EnableMtom(bool bEnable) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_enable_mtom(m_pOptions, m_pEnv, bEnable ? AXIS2_TRUE : AXIS2_FALSE); } COptions& COptions::operator=(axis2_options_t* pOptions) { if (m_bOwner && m_pOptions) { axis2_options_free(m_pOptions, m_pEnv); } m_pOptions = pOptions; m_bOwner = false; return *this; } COptions::operator axis2_options_t*() { return m_pOptions; } const std::string& COptions::GetSessionId() const { return m_sSessionId; } void COptions::SetSessionId(const std::string& sSessionId) { m_sSessionId = sSessionId; } const std::string& COptions::GetInstanceId() const { return m_sInstanceId; } void COptions::SetInstanceId(const std::string& sInstanceId) { m_sInstanceId = sInstanceId; } void COptions::SetDefaultNamespace(const std::string& sUri, const std::string& sPrefix /*= ""*/) { m_sDefaultNsUri = sUri; m_sDefaultNsPrefix = sPrefix; } const std::string& COptions::GetDefaultNamespaceUri() const { return m_sDefaultNsUri; } const std::string& COptions::GetDefaultNamespacePrefix() const { return m_sDefaultNsPrefix; } } <commit_msg>fixed gccv2 compatability<commit_after>/* * Copyright 2010 Utkin Dmitry * * 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. */ /* * This file is part of the WSF Staff project. * Please, visit http://code.google.com/p/staff for more information. */ #include <rise/common/ExceptionTemplate.h> #include <rise/common/exmacros.h> #include <axiom_soap_const.h> #include <axis2_options.h> #include <staff/common/Runtime.h> #include "Options.h" namespace staff { COptions::COptions(): m_pEnv(CRuntime::Inst().GetAxis2Env("staff_client")), m_bOwner(true) { m_pOptions = axis2_options_create(m_pEnv); } COptions::COptions(axis2_options_t* pOptions): m_pOptions(pOptions), m_pEnv(CRuntime::Inst().GetAxis2Env("staff_client")), m_bOwner(false) { } COptions::~COptions() { if (m_bOwner) { axis2_options_free(m_pOptions, m_pEnv); } CRuntime::Inst().FreeAxis2Env("staff_client"); } bool COptions::IsOwner() const { return m_bOwner; } void COptions::SetOwner(bool bOwner /*= true*/) { m_bOwner = bOwner; } std::string COptions::GetAction() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); const axis2_char_t* szAction = axis2_options_get_action(m_pOptions, m_pEnv); RISE_ASSERTS(szAction, "Can't get action"); return reinterpret_cast<const char*>(szAction); } void COptions::SetAction(const std::string& sAction) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_action(m_pOptions, m_pEnv, sAction.c_str()); } std::string COptions::GetFromAddress() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_from(m_pOptions, m_pEnv); RISE_ASSERTS(pEndpointRef, "Can't get WSA endpoint"); const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv); RISE_ASSERTS(szAddress, "Can't get WSA from address"); return reinterpret_cast<const char*>(szAddress); } void COptions::SetFromAddress(const std::string& sAddress) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str()); RISE_ASSERTS(pEndpointRef, "Can't create WSA endpoint"); axis2_options_set_from(m_pOptions, m_pEnv, pEndpointRef); } std::string COptions::GetToAddress() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_to(m_pOptions, m_pEnv); RISE_ASSERTS(pEndpointRef, "Can't get WSA endpoint"); const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv); RISE_ASSERTS(szAddress, "Can't get WSA to address"); return reinterpret_cast<const char*>(szAddress); } void COptions::SetToAddress(const std::string& sAddress) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str()); RISE_ASSERTS(pEndpointRef, "Can't create WSA endpoint"); axis2_options_set_to(m_pOptions, m_pEnv, pEndpointRef); } std::string COptions::GetReplyToAddress() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_reply_to(m_pOptions, m_pEnv); RISE_ASSERTS(pEndpointRef, "Can't get WSA endpoint"); const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv); RISE_ASSERTS(szAddress, "Can't get WSA reply to address"); return reinterpret_cast<const char*>(szAddress); } void COptions::SetReplyToAddress(const std::string& sAddress) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str()); RISE_ASSERTS(pEndpointRef, "Can't create WSA endpoint"); axis2_options_set_reply_to(m_pOptions, m_pEnv, pEndpointRef); } std::string COptions::GetFaultToAddress() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_fault_to(m_pOptions, m_pEnv); RISE_ASSERTS(pEndpointRef, "Can't get WSA endpoint"); const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv); RISE_ASSERTS(szAddress, "Can't get WSA address"); return reinterpret_cast<const char*>(szAddress); } void COptions::SetFaultToAddress(const std::string& sAddress) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str()); RISE_ASSERTS(pEndpointRef, "Can't create WSA endpoint"); axis2_options_set_fault_to(m_pOptions, m_pEnv, pEndpointRef); } void COptions::UseSeparateListener(bool bUseSeparateListener) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_use_separate_listener(m_pOptions, m_pEnv, bUseSeparateListener ? AXIS2_TRUE : AXIS2_FALSE); } bool COptions::IsUsingSeparateListener() { RISE_ASSERTS(m_pOptions, "Options is not initialized"); return axis2_options_get_use_separate_listener(m_pOptions, m_pEnv) == AXIS2_TRUE; } void COptions::SetHttpAuthInfo(const std::string& sUserName, const std::string& sPassword, const std::string& sAuthType) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_status_t nResult = axis2_options_set_http_auth_info(m_pOptions, m_pEnv, sUserName.c_str(), sPassword.c_str(), sAuthType.c_str()); RISE_ASSERTS(nResult == AXIS2_SUCCESS, "Failed to setup http auth info"); } void COptions::SetTestHttpAuth(bool bAuth) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_test_http_auth(m_pOptions, m_pEnv, bAuth ? AXIS2_TRUE : AXIS2_FALSE); } void COptions::SetProxyAuthInfo(const std::string& sUserName, const std::string& sPassword, const std::string& sAuthType) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_status_t nResult = axis2_options_set_proxy_auth_info(m_pOptions, m_pEnv, sUserName.c_str(), sPassword.c_str(), sAuthType.c_str()); RISE_ASSERTS(nResult == AXIS2_SUCCESS, "Failed to setup proxy auth info"); } void COptions::SetTestProxyAuth(bool bAuth) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_test_proxy_auth(m_pOptions, m_pEnv, bAuth ? AXIS2_TRUE : AXIS2_FALSE); } void COptions::SetTimeout(long lTimeout) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_timeout_in_milli_seconds(m_pOptions, m_pEnv, lTimeout); } std::string COptions::GetSoapVersionUri() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); const axis2_char_t* szUri = axis2_options_get_soap_version_uri(m_pOptions, m_pEnv); RISE_ASSERTS(szUri, "Can't get SOAP version URI"); return reinterpret_cast<const char*>(szUri); } void COptions::SetSoapVersionUri(const std::string& sSoapVersionUri) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_soap_version_uri(m_pOptions, m_pEnv, sSoapVersionUri.c_str()); } COptions::SoapVersion COptions::GetSoapVersion() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); int nVersion = axis2_options_get_soap_version(m_pOptions, m_pEnv); switch (nVersion) { case AXIOM_SOAP11: return Soap11; case AXIOM_SOAP12: return Soap12; default: return static_cast<SoapVersion>(nVersion); } } void COptions::SetSoapVersion(SoapVersion nSoapVersion) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); int nAxiomSoapVersion = 0; switch (nSoapVersion) { case Soap11: nAxiomSoapVersion = AXIOM_SOAP11; break; case Soap12: nAxiomSoapVersion = AXIOM_SOAP12; break; default: nAxiomSoapVersion = static_cast<soap_version>(static_cast<int>(nSoapVersion)); } axis2_options_set_soap_version(m_pOptions, m_pEnv, nAxiomSoapVersion); } std::string COptions::GetSoapAction() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); const axutil_string_t* psAction = axis2_options_get_soap_action(m_pOptions, m_pEnv); RISE_ASSERTS(psAction, "Can't get SOAP action"); return reinterpret_cast<const char*>(axutil_string_get_buffer(psAction, m_pEnv)); } void COptions::SetSoapAction(const std::string& sSoapAction) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axutil_string_t* psSoapAction = axutil_string_create(m_pEnv, sSoapAction.c_str()); axis2_options_set_soap_action(m_pOptions, m_pEnv, psSoapAction); axutil_string_free(psSoapAction, m_pEnv); } void COptions::EnableRest(bool bEnable) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_enable_rest(m_pOptions, m_pEnv, bEnable ? AXIS2_TRUE : AXIS2_FALSE); } void COptions::SetHttpMethod(const std::string& sHttpMethod) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_http_method(m_pOptions, m_pEnv, sHttpMethod.c_str()); } bool COptions::IsMtomEnabled() const { RISE_ASSERTS(m_pOptions, "Options is not initialized"); return axis2_options_get_enable_mtom(m_pOptions, m_pEnv) == AXIS2_TRUE; } void COptions::EnableMtom(bool bEnable) { RISE_ASSERTS(m_pOptions, "Options is not initialized"); axis2_options_set_enable_mtom(m_pOptions, m_pEnv, bEnable ? AXIS2_TRUE : AXIS2_FALSE); } COptions& COptions::operator=(axis2_options_t* pOptions) { if (m_bOwner && m_pOptions) { axis2_options_free(m_pOptions, m_pEnv); } m_pOptions = pOptions; m_bOwner = false; return *this; } COptions::operator axis2_options_t*() { return m_pOptions; } const std::string& COptions::GetSessionId() const { return m_sSessionId; } void COptions::SetSessionId(const std::string& sSessionId) { m_sSessionId = sSessionId; } const std::string& COptions::GetInstanceId() const { return m_sInstanceId; } void COptions::SetInstanceId(const std::string& sInstanceId) { m_sInstanceId = sInstanceId; } void COptions::SetDefaultNamespace(const std::string& sUri, const std::string& sPrefix /*= ""*/) { m_sDefaultNsUri = sUri; m_sDefaultNsPrefix = sPrefix; } const std::string& COptions::GetDefaultNamespaceUri() const { return m_sDefaultNsUri; } const std::string& COptions::GetDefaultNamespacePrefix() const { return m_sDefaultNsPrefix; } } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCSceneProcessModule.cpp // @Author : LvSheng.Huang // @Date : 2013-04-14 // @Module : NFCSceneProcessModule // // ------------------------------------------------------------------------- #include "NFCSceneProcessModule.h" #include "NFComm/Config/NFConfig.h" #include "NFComm/NFCore/NFTimer.h" bool NFCSceneProcessModule::Init() { return true; } bool NFCSceneProcessModule::Shut() { return true; } bool NFCSceneProcessModule::Execute() { return true; } bool NFCSceneProcessModule::AfterInit() { m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>( "NFCKernelModule" ); m_pElementInfoModule = pPluginManager->FindModule<NFIElementInfoModule>( "NFCElementInfoModule" ); m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>( "NFCLogicClassModule" ); m_pLogModule = pPluginManager->FindModule<NFILogModule>("NFCLogModule"); assert( NULL != m_pKernelModule ); assert( NULL != m_pElementInfoModule ); assert( NULL != m_pLogicClassModule ); assert( NULL != m_pLogModule ); m_pKernelModule->AddClassCallBack( NFrame::Player::ThisName(), this, &NFCSceneProcessModule::OnObjectClassEvent ); ////////////////////////////////////////////////////////////////////////// //ʼ // #ifdef NF_USE_ACTOR // int nSelfActorID = pPluginManager->GetActorID(); // #endif NF_SHARE_PTR<NFILogicClass> pLogicClass = m_pLogicClassModule->GetElement("Scene"); if (pLogicClass.get()) { NFList<std::string>& list = pLogicClass->GetConfigNameList(); std::string strData; bool bRet = list.First(strData); while (bRet) { int nSceneID = boost::lexical_cast<int>(strData); LoadSceneResource( nSceneID ); m_pKernelModule->CreateScene( nSceneID ); bRet = list.Next(strData); } } return true; } bool NFCSceneProcessModule::CreateSceneObject( const int nSceneID, const int nGroupID) { NF_SHARE_PTR<NFMapEx<std::string, SceneSeedResource>> pSceneResource = mtSceneResourceConfig.GetElement( nSceneID ); if ( pSceneResource.get() ) { NF_SHARE_PTR<SceneSeedResource> pResource = pSceneResource->First( ); while ( pResource.get() ) { const std::string& strClassName = m_pElementInfoModule->GetPropertyString(pResource->strConfigID, NFrame::NPC::ClassName()); NFCDataList arg; arg << NFrame::NPC::X() << pResource->fSeedX; arg << NFrame::NPC::Y() << pResource->fSeedY; arg << NFrame::NPC::Z() << pResource->fSeedZ; arg << NFrame::NPC::SeedID() << pResource->strSeedID; m_pKernelModule->CreateObject( NFGUID(), nSceneID, nGroupID, strClassName, pResource->strConfigID, arg ); pResource = pSceneResource->Next(); } } return true; } int NFCSceneProcessModule::CreateCloneScene( const int& nSceneID) { const E_SCENE_TYPE eType = GetCloneSceneType( nSceneID ); int nTargetGroupID = m_pKernelModule->RequestGroupScene( nSceneID ); if ( nTargetGroupID > 0 && eType == SCENE_TYPE_CLONE_SCENE) { CreateSceneObject( nSceneID, nTargetGroupID); } return nTargetGroupID; } int NFCSceneProcessModule::OnEnterSceneEvent( const NFGUID& self, const int nEventID, const NFIDataList& var ) { if ( var.GetCount() != 4 || !var.TypeEx(TDATA_TYPE::TDATA_OBJECT, TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_UNKNOWN)) { return 0; } const NFGUID ident = var.Object( 0 ); const int nType = var.Int( 1 ); const int nTargetScene = var.Int( 2 ); //const int nTargetGroupID = var.Int( 3 ); const int nNowSceneID = m_pKernelModule->GetPropertyInt( self, NFrame::Player::SceneID()); const int nNowGroupID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::GroupID()); if ( self != ident ) { m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, ident, "you are not you self, but you want to entry this scene", nTargetScene); return 1; } if (nNowSceneID == nTargetScene) { //ͱл m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, ident, "in same scene and group but it not a clone scene", nTargetScene); return 1; } NFINT64 nTargetGroupID = CreateCloneScene( nTargetScene ); if ( nTargetGroupID <= 0 ) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, ident, "CreateCloneScene failed", nTargetScene); return 0; } //õ double fX = 0.0; double fY = 0.0; double fZ = 0.0; const std::string strSceneID = boost::lexical_cast<std::string>(nTargetScene); const std::string& strRelivePosList = m_pElementInfoModule->GetPropertyString(strSceneID, NFrame::Scene::RelivePos()); NFCDataList valueRelivePosList( strRelivePosList.c_str(), ";" ); if ( valueRelivePosList.GetCount() >= 1 ) { NFCDataList valueRelivePos( valueRelivePosList.String( 0 ).c_str(), "," ); if ( valueRelivePos.GetCount() == 3 ) { fX = boost::lexical_cast<double>( valueRelivePos.String( 0 ) ); fY = boost::lexical_cast<double>( valueRelivePos.String( 1 ) ); fZ = boost::lexical_cast<double>( valueRelivePos.String( 2 ) ); } } NFCDataList xSceneResult( var ); xSceneResult.Add( fX ); xSceneResult.Add( fY ); xSceneResult.Add( fZ ); m_pKernelModule->DoEvent( self, NFED_ON_OBJECT_ENTER_SCENE_BEFORE, xSceneResult ); if(!m_pKernelModule->SwitchScene( self, nTargetScene, nTargetGroupID, fX, fY, fZ, 0.0f, var )) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, ident, "SwitchScene failed", nTargetScene); return 0; } xSceneResult.Add( nTargetGroupID ); m_pKernelModule->DoEvent( self, NFED_ON_OBJECT_ENTER_SCENE_RESULT, xSceneResult ); return 0; } int NFCSceneProcessModule::OnLeaveSceneEvent( const NFGUID& object, const int nEventID, const NFIDataList& var ) { if (1 != var.GetCount() || !var.TypeEx(TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_UNKNOWN)) { return -1; } NFINT32 nOldGroupID = var.Int(0); if (nOldGroupID > 0) { int nContainerID = m_pKernelModule->GetPropertyInt(object, NFrame::Player::SceneID()); if (GetCloneSceneType(nContainerID) == SCENE_TYPE_CLONE_SCENE) { m_pKernelModule->ReleaseGroupScene(nContainerID, nOldGroupID); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, object, "DestroyCloneSceneGroup", nOldGroupID); } } return 0; } int NFCSceneProcessModule::OnObjectClassEvent( const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var ) { if ( strClassName == "Player" ) { if ( CLASS_OBJECT_EVENT::COE_DESTROY == eClassEvent ) { //ڸ,ɾǸ int nContainerID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::SceneID()); if (GetCloneSceneType(nContainerID) == SCENE_TYPE_CLONE_SCENE) { int nGroupID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::GroupID()); m_pKernelModule->ReleaseGroupScene(nContainerID, nGroupID); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, self, "DestroyCloneSceneGroup", nGroupID); } } else if ( CLASS_OBJECT_EVENT::COE_CREATE_HASDATA == eClassEvent ) { m_pKernelModule->AddEventCallBack( self, NFED_ON_CLIENT_ENTER_SCENE, this, &NFCSceneProcessModule::OnEnterSceneEvent ); m_pKernelModule->AddEventCallBack( self, NFED_ON_CLIENT_LEAVE_SCENE, this, &NFCSceneProcessModule::OnLeaveSceneEvent ); } } return 0; } E_SCENE_TYPE NFCSceneProcessModule::GetCloneSceneType( const int nContainerID ) { char szSceneIDName[MAX_PATH] = { 0 }; sprintf( szSceneIDName, "%d", nContainerID ); if (m_pElementInfoModule->ExistElement(szSceneIDName)) { return (E_SCENE_TYPE)m_pElementInfoModule->GetPropertyInt(szSceneIDName, NFrame::Scene::CanClone()); } return SCENE_TYPE_ERROR; } bool NFCSceneProcessModule::IsCloneScene(const int nSceneID) { return GetCloneSceneType(nSceneID) == 1; } bool NFCSceneProcessModule::LoadSceneResource( const int nContainerID ) { char szSceneIDName[MAX_PATH] = { 0 }; sprintf( szSceneIDName, "%d", nContainerID ); const std::string& strSceneFilePath = m_pElementInfoModule->GetPropertyString( szSceneIDName, NFrame::Scene::FilePath() ); const int nCanClone = m_pElementInfoModule->GetPropertyInt( szSceneIDName, NFrame::Scene::CanClone() ); //ӦԴ NF_SHARE_PTR<NFMapEx<std::string, SceneSeedResource>> pSceneResourceMap = mtSceneResourceConfig.GetElement( nContainerID ); if ( !pSceneResourceMap.get() ) { pSceneResourceMap = NF_SHARE_PTR<NFMapEx<std::string, SceneSeedResource>>(NF_NEW NFMapEx<std::string, SceneSeedResource>()); mtSceneResourceConfig.AddElement( nContainerID, pSceneResourceMap ); } rapidxml::file<> xFileSource( strSceneFilePath.c_str() ); rapidxml::xml_document<> xFileDoc; xFileDoc.parse<0>( xFileSource.data() ); //Դļб rapidxml::xml_node<>* pSeedFileRoot = xFileDoc.first_node(); for ( rapidxml::xml_node<>* pSeedFileNode = pSeedFileRoot->first_node(); pSeedFileNode; pSeedFileNode = pSeedFileNode->next_sibling() ) { //ӾϢ std::string strSeedID = pSeedFileNode->first_attribute( "ID" )->value(); std::string strConfigID = pSeedFileNode->first_attribute( "NPCConfigID" )->value(); float fSeedX = boost::lexical_cast<float>(pSeedFileNode->first_attribute( "SeedX" )->value()); float fSeedY = boost::lexical_cast<float>(pSeedFileNode->first_attribute( "SeedY" )->value()); float fSeedZ = boost::lexical_cast<float>(pSeedFileNode->first_attribute( "SeedZ" )->value()); if (!m_pElementInfoModule->ExistElement(strConfigID)) { assert(0); } NF_SHARE_PTR<SceneSeedResource> pSeedResource = pSceneResourceMap->GetElement(strSeedID); if ( !pSeedResource.get() ) { pSeedResource = NF_SHARE_PTR<SceneSeedResource>(NF_NEW SceneSeedResource()); pSceneResourceMap->AddElement( strSeedID, pSeedResource ); } pSeedResource->strSeedID = strSeedID; pSeedResource->strConfigID = strConfigID; pSeedResource->fSeedX = fSeedX; pSeedResource->fSeedY = fSeedY; pSeedResource->fSeedZ = fSeedZ; } return true; } <commit_msg>fixed bug for switch scene<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCSceneProcessModule.cpp // @Author : LvSheng.Huang // @Date : 2013-04-14 // @Module : NFCSceneProcessModule // // ------------------------------------------------------------------------- #include "NFCSceneProcessModule.h" #include "NFComm/Config/NFConfig.h" #include "NFComm/NFCore/NFTimer.h" bool NFCSceneProcessModule::Init() { return true; } bool NFCSceneProcessModule::Shut() { return true; } bool NFCSceneProcessModule::Execute() { return true; } bool NFCSceneProcessModule::AfterInit() { m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>( "NFCKernelModule" ); m_pElementInfoModule = pPluginManager->FindModule<NFIElementInfoModule>( "NFCElementInfoModule" ); m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>( "NFCLogicClassModule" ); m_pLogModule = pPluginManager->FindModule<NFILogModule>("NFCLogModule"); assert( NULL != m_pKernelModule ); assert( NULL != m_pElementInfoModule ); assert( NULL != m_pLogicClassModule ); assert( NULL != m_pLogModule ); m_pKernelModule->AddClassCallBack( NFrame::Player::ThisName(), this, &NFCSceneProcessModule::OnObjectClassEvent ); ////////////////////////////////////////////////////////////////////////// //ʼ // #ifdef NF_USE_ACTOR // int nSelfActorID = pPluginManager->GetActorID(); // #endif NF_SHARE_PTR<NFILogicClass> pLogicClass = m_pLogicClassModule->GetElement("Scene"); if (pLogicClass.get()) { NFList<std::string>& list = pLogicClass->GetConfigNameList(); std::string strData; bool bRet = list.First(strData); while (bRet) { int nSceneID = boost::lexical_cast<int>(strData); LoadSceneResource( nSceneID ); m_pKernelModule->CreateScene( nSceneID ); bRet = list.Next(strData); } } return true; } bool NFCSceneProcessModule::CreateSceneObject( const int nSceneID, const int nGroupID) { NF_SHARE_PTR<NFMapEx<std::string, SceneSeedResource>> pSceneResource = mtSceneResourceConfig.GetElement( nSceneID ); if ( pSceneResource.get() ) { NF_SHARE_PTR<SceneSeedResource> pResource = pSceneResource->First( ); while ( pResource.get() ) { const std::string& strClassName = m_pElementInfoModule->GetPropertyString(pResource->strConfigID, NFrame::NPC::ClassName()); NFCDataList arg; arg << NFrame::NPC::X() << pResource->fSeedX; arg << NFrame::NPC::Y() << pResource->fSeedY; arg << NFrame::NPC::Z() << pResource->fSeedZ; arg << NFrame::NPC::SeedID() << pResource->strSeedID; m_pKernelModule->CreateObject( NFGUID(), nSceneID, nGroupID, strClassName, pResource->strConfigID, arg ); pResource = pSceneResource->Next(); } } return true; } int NFCSceneProcessModule::CreateCloneScene( const int& nSceneID) { const E_SCENE_TYPE eType = GetCloneSceneType( nSceneID ); int nTargetGroupID = m_pKernelModule->RequestGroupScene( nSceneID ); if ( nTargetGroupID > 0 && eType == SCENE_TYPE_CLONE_SCENE) { CreateSceneObject( nSceneID, nTargetGroupID); } return nTargetGroupID; } int NFCSceneProcessModule::OnEnterSceneEvent( const NFGUID& self, const int nEventID, const NFIDataList& var ) { if ( var.GetCount() != 4 || !var.TypeEx(TDATA_TYPE::TDATA_OBJECT, TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_UNKNOWN)) { return 0; } const NFGUID ident = var.Object( 0 ); const int nType = var.Int( 1 ); const int nTargetScene = var.Int( 2 ); const int nTargetGroupID = var.Int( 3 ); const int nNowSceneID = m_pKernelModule->GetPropertyInt( self, NFrame::Player::SceneID()); const int nNowGroupID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::GroupID()); if ( self != ident ) { m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, ident, "you are not you self, but you want to entry this scene", nTargetScene); return 1; } if (nNowSceneID == nTargetScene && nTargetGroupID == nNowGroupID) { //ͱл m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, ident, "in same scene and group but it not a clone scene", nTargetScene); return 1; } //ÿңһ NFINT64 nNewGroupID = CreateCloneScene( nTargetScene ); if ( nNewGroupID <= 0 ) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, ident, "CreateCloneScene failed", nTargetScene); return 0; } //õ double fX = 0.0; double fY = 0.0; double fZ = 0.0; const std::string strSceneID = boost::lexical_cast<std::string>(nTargetScene); const std::string& strRelivePosList = m_pElementInfoModule->GetPropertyString(strSceneID, NFrame::Scene::RelivePos()); NFCDataList valueRelivePosList( strRelivePosList.c_str(), ";" ); if ( valueRelivePosList.GetCount() >= 1 ) { NFCDataList valueRelivePos( valueRelivePosList.String( 0 ).c_str(), "," ); if ( valueRelivePos.GetCount() == 3 ) { fX = boost::lexical_cast<double>( valueRelivePos.String( 0 ) ); fY = boost::lexical_cast<double>( valueRelivePos.String( 1 ) ); fZ = boost::lexical_cast<double>( valueRelivePos.String( 2 ) ); } } NFCDataList xSceneResult( var ); xSceneResult.Add( fX ); xSceneResult.Add( fY ); xSceneResult.Add( fZ ); m_pKernelModule->DoEvent( self, NFED_ON_OBJECT_ENTER_SCENE_BEFORE, xSceneResult ); if(!m_pKernelModule->SwitchScene( self, nTargetScene, nNewGroupID, fX, fY, fZ, 0.0f, var )) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, ident, "SwitchScene failed", nTargetScene); return 0; } xSceneResult.Add( nNewGroupID ); m_pKernelModule->DoEvent( self, NFED_ON_OBJECT_ENTER_SCENE_RESULT, xSceneResult ); return 0; } int NFCSceneProcessModule::OnLeaveSceneEvent( const NFGUID& object, const int nEventID, const NFIDataList& var ) { if (1 != var.GetCount() || !var.TypeEx(TDATA_TYPE::TDATA_INT, TDATA_TYPE::TDATA_UNKNOWN)) { return -1; } NFINT32 nOldGroupID = var.Int(0); if (nOldGroupID > 0) { int nContainerID = m_pKernelModule->GetPropertyInt(object, NFrame::Player::SceneID()); if (GetCloneSceneType(nContainerID) == SCENE_TYPE_CLONE_SCENE) { m_pKernelModule->ReleaseGroupScene(nContainerID, nOldGroupID); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, object, "DestroyCloneSceneGroup", nOldGroupID); } } return 0; } int NFCSceneProcessModule::OnObjectClassEvent( const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var ) { if ( strClassName == "Player" ) { if ( CLASS_OBJECT_EVENT::COE_DESTROY == eClassEvent ) { //ڸ,ɾǸ int nContainerID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::SceneID()); if (GetCloneSceneType(nContainerID) == SCENE_TYPE_CLONE_SCENE) { int nGroupID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::GroupID()); m_pKernelModule->ReleaseGroupScene(nContainerID, nGroupID); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, self, "DestroyCloneSceneGroup", nGroupID); } } else if ( CLASS_OBJECT_EVENT::COE_CREATE_HASDATA == eClassEvent ) { m_pKernelModule->AddEventCallBack( self, NFED_ON_CLIENT_ENTER_SCENE, this, &NFCSceneProcessModule::OnEnterSceneEvent ); m_pKernelModule->AddEventCallBack( self, NFED_ON_CLIENT_LEAVE_SCENE, this, &NFCSceneProcessModule::OnLeaveSceneEvent ); } } return 0; } E_SCENE_TYPE NFCSceneProcessModule::GetCloneSceneType( const int nContainerID ) { char szSceneIDName[MAX_PATH] = { 0 }; sprintf( szSceneIDName, "%d", nContainerID ); if (m_pElementInfoModule->ExistElement(szSceneIDName)) { return (E_SCENE_TYPE)m_pElementInfoModule->GetPropertyInt(szSceneIDName, NFrame::Scene::CanClone()); } return SCENE_TYPE_ERROR; } bool NFCSceneProcessModule::IsCloneScene(const int nSceneID) { return GetCloneSceneType(nSceneID) == 1; } bool NFCSceneProcessModule::LoadSceneResource( const int nContainerID ) { char szSceneIDName[MAX_PATH] = { 0 }; sprintf( szSceneIDName, "%d", nContainerID ); const std::string& strSceneFilePath = m_pElementInfoModule->GetPropertyString( szSceneIDName, NFrame::Scene::FilePath() ); const int nCanClone = m_pElementInfoModule->GetPropertyInt( szSceneIDName, NFrame::Scene::CanClone() ); //ӦԴ NF_SHARE_PTR<NFMapEx<std::string, SceneSeedResource>> pSceneResourceMap = mtSceneResourceConfig.GetElement( nContainerID ); if ( !pSceneResourceMap.get() ) { pSceneResourceMap = NF_SHARE_PTR<NFMapEx<std::string, SceneSeedResource>>(NF_NEW NFMapEx<std::string, SceneSeedResource>()); mtSceneResourceConfig.AddElement( nContainerID, pSceneResourceMap ); } rapidxml::file<> xFileSource( strSceneFilePath.c_str() ); rapidxml::xml_document<> xFileDoc; xFileDoc.parse<0>( xFileSource.data() ); //Դļб rapidxml::xml_node<>* pSeedFileRoot = xFileDoc.first_node(); for ( rapidxml::xml_node<>* pSeedFileNode = pSeedFileRoot->first_node(); pSeedFileNode; pSeedFileNode = pSeedFileNode->next_sibling() ) { //ӾϢ std::string strSeedID = pSeedFileNode->first_attribute( "ID" )->value(); std::string strConfigID = pSeedFileNode->first_attribute( "NPCConfigID" )->value(); float fSeedX = boost::lexical_cast<float>(pSeedFileNode->first_attribute( "SeedX" )->value()); float fSeedY = boost::lexical_cast<float>(pSeedFileNode->first_attribute( "SeedY" )->value()); float fSeedZ = boost::lexical_cast<float>(pSeedFileNode->first_attribute( "SeedZ" )->value()); if (!m_pElementInfoModule->ExistElement(strConfigID)) { assert(0); } NF_SHARE_PTR<SceneSeedResource> pSeedResource = pSceneResourceMap->GetElement(strSeedID); if ( !pSeedResource.get() ) { pSeedResource = NF_SHARE_PTR<SceneSeedResource>(NF_NEW SceneSeedResource()); pSceneResourceMap->AddElement( strSeedID, pSeedResource ); } pSeedResource->strSeedID = strSeedID; pSeedResource->strConfigID = strConfigID; pSeedResource->fSeedX = fSeedX; pSeedResource->fSeedY = fSeedY; pSeedResource->fSeedZ = fSeedZ; } return true; } <|endoftext|>
<commit_before>/************************************************************************** * The MIT License * * Copyright (c) 2013 Antony Arciuolo. * * arciuolo@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. * **************************************************************************/ #include <oSurface/codec.h> #include <oSurface/fill.h> #include <oBase/colors.h> #include <oBase/throw.h> #include <oBase/timer.h> #include <oBase/fixed_string.h> #include <oCore/filesystem.h> #include "../../test_services.h" namespace ouro { namespace tests { static bool kSaveToDesktop = false; void save_bmp_to_desktop(const surface::texel_buffer& b, const char* _path) { auto encoded = surface::encode(b , surface::file_format::bmp , default_allocator , default_allocator , surface::as_noax(b.get_info().format) , surface::compression::none); filesystem::save(filesystem::desktop_path() / path(_path), encoded, encoded.size()); } static void compare_checkboards(const int2& dimensions, const surface::format& format, const surface::file_format& file_format, float max_rms) { oTRACE("testing codec %s -> %s", as_string(format), as_string(file_format)); // Create a buffer with a known format surface::info si; si.format = format; si.mip_layout = surface::mip_layout::none; si.dimensions = int3(dimensions, 1); surface::texel_buffer known(si); size_t knownSize = known.size(); { surface::lock_guard lock(known); surface::fill_checkerboard((color*)lock.mapped.data, lock.mapped.row_pitch, si.dimensions.xy(), si.dimensions.xy() / 2, blue, red); } size_t EncodedSize = 0; scoped_allocation encoded; { scoped_timer("encode"); encoded = surface::encode(known , file_format , surface::as_noax(known.get_info().format) , surface::compression::none); } #if 0 sstring buf; format_bytes(buf, EncodedSize, 2); oTRACE("encoded %s", buf.c_str()); if (kSaveToDesktop) { mstring fname; snprintf(fname, "encoded_from_known_%s.%s", as_string(file_format), as_string(file_format)); filesystem::save(path(fname), encoded, encoded.size()); } surface::texel_buffer decoded; { scoped_timer("decode"); decoded = surface::decode(encoded, encoded.size(), format); } { size_t decodedSize = decoded.size(); if (known.size() != decoded.size()) oTHROW(io_error, "encoded %u but got %u on decode", knownSize, decodedSize); if (kSaveToDesktop) { mstring fname; snprintf(fname, "encoded_from_decoded_%s.%s", as_string(file_format), as_string(surface::file_format::bmp)); save_bmp_to_desktop(decoded, fname); } float rms = surface::calc_rms(known, decoded); if (rms > max_rms) oTHROW(io_error, "encoded/decoded bytes mismatch for %s", as_string(file_format)); } #endif } void compare_load(test_services& services, const char* path, const char* desktop_filename_prefix) { auto encoded = services.load_buffer(path); surface::texel_buffer decoded; { scoped_timer("decode"); decoded = surface::decode(encoded, encoded.size(), surface::format::b8g8r8a8_unorm); } auto ff = surface::get_file_format(path); mstring fname; snprintf(fname, "%s_%s.%s", desktop_filename_prefix, as_string(ff), as_string(surface::file_format::bmp)); save_bmp_to_desktop(decoded, fname); } void TESTsurface_codec(test_services& _Services) { // still a WIP //compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::psd, 1.0f); //compare_load(_Services, "Test/Textures/lena_1.psd", "lena_1"); compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::bmp, 1.0f); compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::dds, 1.0f); compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::jpg, 4.0f); compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::png, 1.0f); compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::tga, 1.0f); } } // namespace tests } // namespace ouro <commit_msg>Reenable code in codec test<commit_after>/************************************************************************** * The MIT License * * Copyright (c) 2013 Antony Arciuolo. * * arciuolo@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. * **************************************************************************/ #include <oSurface/codec.h> #include <oSurface/fill.h> #include <oBase/colors.h> #include <oBase/throw.h> #include <oBase/timer.h> #include <oBase/fixed_string.h> #include <oCore/filesystem.h> #include "../../test_services.h" namespace ouro { namespace tests { static bool kSaveToDesktop = false; void save_bmp_to_desktop(const surface::texel_buffer& b, const char* _path) { auto encoded = surface::encode(b , surface::file_format::bmp , default_allocator , default_allocator , surface::as_noax(b.get_info().format) , surface::compression::none); filesystem::save(filesystem::desktop_path() / path(_path), encoded, encoded.size()); } static void compare_checkboards(const int2& dimensions, const surface::format& format, const surface::file_format& file_format, float max_rms) { oTRACE("testing codec %s -> %s", as_string(format), as_string(file_format)); // Create a buffer with a known format surface::info si; si.format = format; si.mip_layout = surface::mip_layout::none; si.dimensions = int3(dimensions, 1); surface::texel_buffer known(si); size_t knownSize = known.size(); { surface::lock_guard lock(known); surface::fill_checkerboard((color*)lock.mapped.data, lock.mapped.row_pitch, si.dimensions.xy(), si.dimensions.xy() / 2, blue, red); } size_t EncodedSize = 0; scoped_allocation encoded; { scoped_timer("encode"); encoded = surface::encode(known , file_format , surface::as_noax(known.get_info().format) , surface::compression::none); } sstring buf; format_bytes(buf, EncodedSize, 2); oTRACE("encoded %s", buf.c_str()); if (kSaveToDesktop) { mstring fname; snprintf(fname, "encoded_from_known_%s.%s", as_string(file_format), as_string(file_format)); filesystem::save(path(fname), encoded, encoded.size()); } surface::texel_buffer decoded; { scoped_timer("decode"); decoded = surface::decode(encoded, encoded.size(), format); } { size_t decodedSize = decoded.size(); if (known.size() != decoded.size()) oTHROW(io_error, "encoded %u but got %u on decode", knownSize, decodedSize); if (kSaveToDesktop) { mstring fname; snprintf(fname, "encoded_from_decoded_%s.%s", as_string(file_format), as_string(surface::file_format::bmp)); save_bmp_to_desktop(decoded, fname); } float rms = surface::calc_rms(known, decoded); if (rms > max_rms) oTHROW(io_error, "encoded/decoded bytes mismatch for %s", as_string(file_format)); } } void compare_load(test_services& services, const char* path, const char* desktop_filename_prefix) { auto encoded = services.load_buffer(path); surface::texel_buffer decoded; { scoped_timer("decode"); decoded = surface::decode(encoded, encoded.size(), surface::format::b8g8r8a8_unorm); } auto ff = surface::get_file_format(path); mstring fname; snprintf(fname, "%s_%s.%s", desktop_filename_prefix, as_string(ff), as_string(surface::file_format::bmp)); save_bmp_to_desktop(decoded, fname); } void TESTsurface_codec(test_services& _Services) { // still a WIP //compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::psd, 1.0f); //compare_load(_Services, "Test/Textures/lena_1.psd", "lena_1"); compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::bmp, 1.0f); compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::dds, 1.0f); compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::jpg, 4.0f); compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::png, 1.0f); compare_checkboards(uint2(11,21), surface::format::b8g8r8a8_unorm, surface::file_format::tga, 1.0f); } } // namespace tests } // namespace ouro <|endoftext|>
<commit_before>AliAnalysisTask *AddTask_cbaumann_LMEEpp(){ //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_cbaumann", "No analysis manager found."); return 0; } Bool_t RunEMCtrigger = 0; Bool_t RunHighMulttrigger = 0; Bool_t RunMBtrigger = 1; //Do we have an MC handler? Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0); //Get the current train configuration //Directories for GSI train: TString configBasePath("$TRAIN_ROOT/cbaumann_dielectron/"); TString trainRoot=gSystem->Getenv("TRAIN_ROOT"); //Base Directory for GRID / LEGO Train if (trainRoot.IsNull()) configBasePath= "$ALICE_ROOT/PWGDQ/dielectron/macrosLMEE/"; TString configFile("Config_lowmasspp.C"); TString configFilePath(configBasePath+configFile); if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data())) gROOT->LoadMacro(configFilePath.Data()); //create task and add it to the manager (MB) AliAnalysisTaskMultiDielectron *taskMB = new AliAnalysisTaskMultiDielectron("MultiDieMB"); if (!hasMC) taskMB->UsePhysicsSelection(); //taskMB->SelectCollisionCandidates(AliVEvent::kMB); taskMB->SelectCollisionCandidates(AliVEvent::kINT7); taskMB->SetRejectPileup(); //Add event filter AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0"); eventCuts->SetRequireVertex(); eventCuts->SetVertexZ(-10.,10.); eventCuts->SetMinVtxContributors(1); taskMB->SetEventFilter(eventCuts); mgr->AddTask(taskMB); for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file //MB AliDielectron *diel_lowMB = Config_lowmasspp(i); if(!diel_lowMB)continue; taskMB->AddDielectron(diel_lowMB); }//loop //create output container AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("tree_lowmass", TTree::Class(), AliAnalysisManager::kExchangeContainer, "default"); AliAnalysisDataContainer *cOutputHist1 = mgr->CreateContainer("Histos_diel_lowmass", TList::Class(), AliAnalysisManager::kOutputContainer, "cbaumann_lowmass.root"); AliAnalysisDataContainer *cOutputHist2 = mgr->CreateContainer("CF_diel_lowmass", TList::Class(), AliAnalysisManager::kOutputContainer, "cbaumann_lowmass.root"); AliAnalysisDataContainer *cOutputHist3 = mgr->CreateContainer("cbauman_lowmass_EventStat", TList::Class(), AliAnalysisManager::kOutputContainer, "cbaumann_lowmass.root"); mgr->ConnectInput(taskMB, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskMB, 0, coutput1 ); mgr->ConnectOutput(taskMB, 1, cOutputHist1); mgr->ConnectOutput(taskMB, 2, cOutputHist2); mgr->ConnectOutput(taskMB, 3, cOutputHist3); return taskMB; } <commit_msg>adjust trigger string<commit_after>AliAnalysisTask *AddTask_cbaumann_LMEEpp(){ //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_cbaumann", "No analysis manager found."); return 0; } Bool_t RunEMCtrigger = 0; Bool_t RunHighMulttrigger = 0; Bool_t RunMBtrigger = 1; //Do we have an MC handler? Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0); //Get the current train configuration //Directories for GSI train: TString configBasePath("$TRAIN_ROOT/cbaumann_dielectron/"); TString trainRoot=gSystem->Getenv("TRAIN_ROOT"); //Base Directory for GRID / LEGO Train if (trainRoot.IsNull()) configBasePath= "$ALICE_ROOT/PWGDQ/dielectron/macrosLMEE/"; TString configFile("Config_lowmasspp.C"); TString configFilePath(configBasePath+configFile); if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data())) gROOT->LoadMacro(configFilePath.Data()); //create task and add it to the manager (MB) AliAnalysisTaskMultiDielectron *taskMB = new AliAnalysisTaskMultiDielectron("MultiDieMB"); if (!hasMC) taskMB->UsePhysicsSelection(); //taskMB->SelectCollisionCandidates(AliVEvent::kMB); taskMB->SelectCollisionCandidates(AliVEvent::kINT8); taskMB->SetRejectPileup(); //Add event filter AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0"); eventCuts->SetRequireVertex(); eventCuts->SetVertexZ(-10.,10.); eventCuts->SetMinVtxContributors(1); taskMB->SetEventFilter(eventCuts); mgr->AddTask(taskMB); for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file //MB AliDielectron *diel_lowMB = Config_lowmasspp(i); if(!diel_lowMB)continue; taskMB->AddDielectron(diel_lowMB); }//loop //create output container AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("tree_lowmass", TTree::Class(), AliAnalysisManager::kExchangeContainer, "default"); AliAnalysisDataContainer *cOutputHist1 = mgr->CreateContainer("Histos_diel_lowmass", TList::Class(), AliAnalysisManager::kOutputContainer, "cbaumann_lowmass.root"); AliAnalysisDataContainer *cOutputHist2 = mgr->CreateContainer("CF_diel_lowmass", TList::Class(), AliAnalysisManager::kOutputContainer, "cbaumann_lowmass.root"); AliAnalysisDataContainer *cOutputHist3 = mgr->CreateContainer("cbauman_lowmass_EventStat", TList::Class(), AliAnalysisManager::kOutputContainer, "cbaumann_lowmass.root"); mgr->ConnectInput(taskMB, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskMB, 0, coutput1 ); mgr->ConnectOutput(taskMB, 1, cOutputHist1); mgr->ConnectOutput(taskMB, 2, cOutputHist2); mgr->ConnectOutput(taskMB, 3, cOutputHist3); return taskMB; } <|endoftext|>
<commit_before>AliAnalysisTask *AddTaskEMCALPi0V2hardCodeEP(Double_t EvtMthod=1) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskEMCALPi0V2hardCodeEP", "No analysis manager found."); return NULL; } if (!mgr->GetInputEventHandler()) { ::Error("AddTaskEMCALPi0V2hardCodeEP", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" if (type=="AOD"){ ::Error("AddTaskEMCALPi0V2hardCodeEP", "The tasks exits because AODs are in input"); return NULL; } //Event plane task AliEPSelectionTask *eventplaneTask = new AliEPSelectionTask("EventplaneSelection"); eventplaneTask->SetTrackType("TPC"); eventplaneTask->SetUsePtWeight(); eventplaneTask->SetUsePhiWeight(); eventplaneTask->SetSaveTrackContribution(); AliESDtrackCuts* epTrackCuts = new AliESDtrackCuts("AliESDtrackCuts", "Standard"); epTrackCuts->SetRequireTPCStandAlone(kTRUE); // to get chi2 and ncls of kTPCin epTrackCuts->SetMinNClustersTPC(50); epTrackCuts->SetMaxChi2PerClusterTPC(4); epTrackCuts->SetAcceptKinkDaughters(kFALSE); epTrackCuts->SetRequireTPCRefit(kTRUE); epTrackCuts->SetMaxDCAToVertexZ(3.2); epTrackCuts->SetMaxDCAToVertexXY(2.4); epTrackCuts->SetPtRange(0.15, 20); eventplaneTask->SetPersonalESDtrackCuts(epTrackCuts); mgr->AddTask(eventplaneTask); TString containerName3 = mgr->GetCommonFileName(); containerName3 += ":PWGGA_pi0v2CalEventPlane"; AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("EPStatTPC",TList::Class(), AliAnalysisManager::kOutputContainer,containerName3.Data()); mgr->ConnectInput(eventplaneTask, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(eventplaneTask,1,coutput1); //analysis task AliAnalysisTaskSE* taskMB = new AliAnalysisTaskPi0V2("Pi0v2Task"); taskMB->SetEventMethod(EvtMthod); TString containerName = mgr->GetCommonFileName(); containerName += ":PWGGA_pi0v2CalSemiCentral"; AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("histv2task", TList::Class(),AliAnalysisManager::kOutputContainer, containerName.Data()); mgr->ConnectInput(taskMB, 0, cinput); mgr->ConnectOutput(taskMB, 1, coutput2); return NULL; } <commit_msg>changes from fzhou<commit_after>AliAnalysisTask *AddTaskEMCALPi0V2hardCodeEP(Double_t EvtMthod=1) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskEMCALPi0V2hardCodeEP", "No analysis manager found."); return NULL; } if (!mgr->GetInputEventHandler()) { ::Error("AddTaskEMCALPi0V2hardCodeEP", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" if (type=="AOD"){ ::Error("AddTaskEMCALPi0V2hardCodeEP", "The tasks exits because AODs are in input"); return NULL; } //Event plane task AliEPSelectionTask *eventplaneTask = new AliEPSelectionTask("EventplaneSelection"); eventplaneTask->SetTrackType("TPC"); eventplaneTask->SetUsePtWeight(); eventplaneTask->SetUsePhiWeight(); eventplaneTask->SetSaveTrackContribution(); AliESDtrackCuts* epTrackCuts = new AliESDtrackCuts("AliESDtrackCuts", "Standard"); epTrackCuts->SetRequireTPCStandAlone(kTRUE); // to get chi2 and ncls of kTPCin epTrackCuts->SetMinNClustersTPC(50); epTrackCuts->SetMaxChi2PerClusterTPC(4); epTrackCuts->SetAcceptKinkDaughters(kFALSE); epTrackCuts->SetRequireTPCRefit(kTRUE); epTrackCuts->SetMaxDCAToVertexZ(3.2); epTrackCuts->SetMaxDCAToVertexXY(2.4); epTrackCuts->SetPtRange(0.15, 20); eventplaneTask->SetPersonalESDtrackCuts(epTrackCuts); mgr->AddTask(eventplaneTask); TString containerName3 = mgr->GetCommonFileName(); containerName3 += ":PWGGA_pi0v2CalEventPlane"; AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("EPStatTPC",TList::Class(), AliAnalysisManager::kOutputContainer,containerName3.Data()); mgr->ConnectInput(eventplaneTask, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(eventplaneTask,1,coutput1); //analysis task AliAnalysisTaskPi0V2* taskMB = new AliAnalysisTaskPi0V2("Pi0v2Task"); taskMB->SetEventMethod(EvtMthod); TString containerName = mgr->GetCommonFileName(); containerName += ":PWGGA_pi0v2CalSemiCentral"; AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("histv2task", TList::Class(),AliAnalysisManager::kOutputContainer, containerName.Data()); mgr->ConnectInput(taskMB, 0, cinput); mgr->ConnectOutput(taskMB, 1, coutput2); return NULL; } <|endoftext|>
<commit_before>/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis Modified 28 September 2010 by Mark Sproul Modified 14 August 2012 by Alarus */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Arduino.h" #include "HardwareSerial.h" #include "HardwareSerial_private.h" // this next line disables the entire HardwareSerial.cpp, // this is so I can support Attiny series and any other chip without a uart #if defined(HAVE_HWSERIAL0) || defined(HAVE_HWSERIAL1) || defined(HAVE_HWSERIAL2) || defined(HAVE_HWSERIAL3) // SerialEvent functions are weak, so when the user doesn't define them, // the linker just sets their address to 0 (which is checked below). // The Serialx_available is just a wrapper around Serialx.available(), // but we can refer to it weakly so we don't pull in the entire // HardwareSerial instance if the user doesn't also refer to it. #if defined(HAVE_HWSERIAL0) void serialEvent() __attribute__((weak)); bool Serial0_available() __attribute__((weak)); #endif #if defined(HAVE_HWSERIAL1) void serialEvent1() __attribute__((weak)); bool Serial1_available() __attribute__((weak)); #endif #if defined(HAVE_HWSERIAL2) void serialEvent2() __attribute__((weak)); bool Serial2_available() __attribute__((weak)); #endif #if defined(HAVE_HWSERIAL3) void serialEvent3() __attribute__((weak)); bool Serial3_available() __attribute__((weak)); #endif void serialEventRun(void) { #if defined(HAVE_HWSERIAL0) if (Serial0_available && serialEvent && Serial0_available()) serialEvent(); #endif #if defined(HAVE_HWSERIAL1) if (Serial1_available && serialEvent1 && Serial1_available()) serialEvent1(); #endif #if defined(HAVE_HWSERIAL2) if (Serial2_available && serialEvent2 && Serial2_available()) serialEvent2(); #endif #if defined(HAVE_HWSERIAL3) if (Serial3_available && serialEvent2 && Serial3_available()) serialEvent3(); #endif } // Actual interrupt handlers ////////////////////////////////////////////////////////////// void HardwareSerial::_tx_udr_empty_irq(void) { // If interrupts are enabled, there must be more data in the output // buffer. Send the next byte unsigned char c = _tx_buffer[_tx_buffer_tail]; _tx_buffer_tail = (_tx_buffer_tail + 1) % SERIAL_BUFFER_SIZE; *_udr = c; // clear the TXC bit -- "can be cleared by writing a one to its bit // location". This makes sure flush() won't return until the bytes // actually got written sbi(*_ucsra, TXC0); if (_tx_buffer_head == _tx_buffer_tail) { // Buffer empty, so disable interrupts cbi(*_ucsrb, UDRIE0); } } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(unsigned long baud, byte config) { // Try u2x mode first uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2; *_ucsra = 1 << U2X0; // hardcoded exception for 57600 for compatibility with the bootloader // shipped with the Duemilanove and previous boards and the firmware // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot // be > 4095, so switch back to non-u2x mode if the baud rate is too // low. if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095)) { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; _written = false; //set the data bits, parity, and stop bits #if defined(__AVR_ATmega8__) config |= 0x80; // select UCSRC register (shared with UBRRH) #endif *_ucsrc = config; sbi(*_ucsrb, RXEN0); sbi(*_ucsrb, TXEN0); sbi(*_ucsrb, RXCIE0); cbi(*_ucsrb, UDRIE0); } void HardwareSerial::end() { // wait for transmission of outgoing data while (_tx_buffer_head != _tx_buffer_tail) ; cbi(*_ucsrb, RXEN0); cbi(*_ucsrb, TXEN0); cbi(*_ucsrb, RXCIE0); cbi(*_ucsrb, UDRIE0); // clear any received data _rx_buffer_head = _rx_buffer_tail; } int HardwareSerial::available(void) { return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer_head - _rx_buffer_tail) % SERIAL_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer_head == _rx_buffer_tail) { return -1; } else { return _rx_buffer[_rx_buffer_tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer_head == _rx_buffer_tail) { return -1; } else { unsigned char c = _rx_buffer[_rx_buffer_tail]; _rx_buffer_tail = (unsigned int)(_rx_buffer_tail + 1) % SERIAL_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { // If we have never written a byte, no need to flush. This special // case is needed since there is no way to force the TXC (transmit // complete) bit to 1 during initialization if (!_written) return; while (bit_is_set(*_ucsrb, UDRIE0) || bit_is_clear(*_ucsra, TXC0)) { if (bit_is_clear(SREG, SREG_I) && bit_is_set(*_ucsrb, UDRIE0)) // Interrupts are globally disabled, but the DR empty // interrupt should be enabled, so poll the DR empty flag to // prevent deadlock if (bit_is_set(*_ucsra, UDRE0)) _tx_udr_empty_irq(); } // If we get here, nothing is queued anymore (DRIE is disabled) and // the hardware finished tranmission (TXC is set). } size_t HardwareSerial::write(uint8_t c) { int i = (_tx_buffer_head + 1) % SERIAL_BUFFER_SIZE; // If the output buffer is full, there's nothing for it other than to // wait for the interrupt handler to empty it a bit while (i == _tx_buffer_tail) { if (bit_is_clear(SREG, SREG_I)) { // Interrupts are disabled, so we'll have to poll the data // register empty flag ourselves. If it is set, pretend an // interrupt has happened and call the handler to free up // space for us. if(bit_is_set(*_ucsra, UDRE0)) _tx_udr_empty_irq(); } else { // nop, the interrupt handler will free up space for us } } _tx_buffer[_tx_buffer_head] = c; _tx_buffer_head = i; sbi(*_ucsrb, UDRIE0); _written = true; return 1; } #endif // whole file <commit_msg>In HardwareSerial::write, bypass the queue when it's empty<commit_after>/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis Modified 28 September 2010 by Mark Sproul Modified 14 August 2012 by Alarus */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Arduino.h" #include "HardwareSerial.h" #include "HardwareSerial_private.h" // this next line disables the entire HardwareSerial.cpp, // this is so I can support Attiny series and any other chip without a uart #if defined(HAVE_HWSERIAL0) || defined(HAVE_HWSERIAL1) || defined(HAVE_HWSERIAL2) || defined(HAVE_HWSERIAL3) // SerialEvent functions are weak, so when the user doesn't define them, // the linker just sets their address to 0 (which is checked below). // The Serialx_available is just a wrapper around Serialx.available(), // but we can refer to it weakly so we don't pull in the entire // HardwareSerial instance if the user doesn't also refer to it. #if defined(HAVE_HWSERIAL0) void serialEvent() __attribute__((weak)); bool Serial0_available() __attribute__((weak)); #endif #if defined(HAVE_HWSERIAL1) void serialEvent1() __attribute__((weak)); bool Serial1_available() __attribute__((weak)); #endif #if defined(HAVE_HWSERIAL2) void serialEvent2() __attribute__((weak)); bool Serial2_available() __attribute__((weak)); #endif #if defined(HAVE_HWSERIAL3) void serialEvent3() __attribute__((weak)); bool Serial3_available() __attribute__((weak)); #endif void serialEventRun(void) { #if defined(HAVE_HWSERIAL0) if (Serial0_available && serialEvent && Serial0_available()) serialEvent(); #endif #if defined(HAVE_HWSERIAL1) if (Serial1_available && serialEvent1 && Serial1_available()) serialEvent1(); #endif #if defined(HAVE_HWSERIAL2) if (Serial2_available && serialEvent2 && Serial2_available()) serialEvent2(); #endif #if defined(HAVE_HWSERIAL3) if (Serial3_available && serialEvent2 && Serial3_available()) serialEvent3(); #endif } // Actual interrupt handlers ////////////////////////////////////////////////////////////// void HardwareSerial::_tx_udr_empty_irq(void) { // If interrupts are enabled, there must be more data in the output // buffer. Send the next byte unsigned char c = _tx_buffer[_tx_buffer_tail]; _tx_buffer_tail = (_tx_buffer_tail + 1) % SERIAL_BUFFER_SIZE; *_udr = c; // clear the TXC bit -- "can be cleared by writing a one to its bit // location". This makes sure flush() won't return until the bytes // actually got written sbi(*_ucsra, TXC0); if (_tx_buffer_head == _tx_buffer_tail) { // Buffer empty, so disable interrupts cbi(*_ucsrb, UDRIE0); } } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(unsigned long baud, byte config) { // Try u2x mode first uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2; *_ucsra = 1 << U2X0; // hardcoded exception for 57600 for compatibility with the bootloader // shipped with the Duemilanove and previous boards and the firmware // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot // be > 4095, so switch back to non-u2x mode if the baud rate is too // low. if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095)) { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; _written = false; //set the data bits, parity, and stop bits #if defined(__AVR_ATmega8__) config |= 0x80; // select UCSRC register (shared with UBRRH) #endif *_ucsrc = config; sbi(*_ucsrb, RXEN0); sbi(*_ucsrb, TXEN0); sbi(*_ucsrb, RXCIE0); cbi(*_ucsrb, UDRIE0); } void HardwareSerial::end() { // wait for transmission of outgoing data while (_tx_buffer_head != _tx_buffer_tail) ; cbi(*_ucsrb, RXEN0); cbi(*_ucsrb, TXEN0); cbi(*_ucsrb, RXCIE0); cbi(*_ucsrb, UDRIE0); // clear any received data _rx_buffer_head = _rx_buffer_tail; } int HardwareSerial::available(void) { return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer_head - _rx_buffer_tail) % SERIAL_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer_head == _rx_buffer_tail) { return -1; } else { return _rx_buffer[_rx_buffer_tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer_head == _rx_buffer_tail) { return -1; } else { unsigned char c = _rx_buffer[_rx_buffer_tail]; _rx_buffer_tail = (unsigned int)(_rx_buffer_tail + 1) % SERIAL_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { // If we have never written a byte, no need to flush. This special // case is needed since there is no way to force the TXC (transmit // complete) bit to 1 during initialization if (!_written) return; while (bit_is_set(*_ucsrb, UDRIE0) || bit_is_clear(*_ucsra, TXC0)) { if (bit_is_clear(SREG, SREG_I) && bit_is_set(*_ucsrb, UDRIE0)) // Interrupts are globally disabled, but the DR empty // interrupt should be enabled, so poll the DR empty flag to // prevent deadlock if (bit_is_set(*_ucsra, UDRE0)) _tx_udr_empty_irq(); } // If we get here, nothing is queued anymore (DRIE is disabled) and // the hardware finished tranmission (TXC is set). } size_t HardwareSerial::write(uint8_t c) { // If the buffer and the data register is empty, just write the byte // to the data register and be done. This shortcut helps // significantly improve the effective datarate at high (> // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown. if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) { *_udr = c; sbi(*_ucsra, TXC0); return 1; } int i = (_tx_buffer_head + 1) % SERIAL_BUFFER_SIZE; // If the output buffer is full, there's nothing for it other than to // wait for the interrupt handler to empty it a bit while (i == _tx_buffer_tail) { if (bit_is_clear(SREG, SREG_I)) { // Interrupts are disabled, so we'll have to poll the data // register empty flag ourselves. If it is set, pretend an // interrupt has happened and call the handler to free up // space for us. if(bit_is_set(*_ucsra, UDRE0)) _tx_udr_empty_irq(); } else { // nop, the interrupt handler will free up space for us } } _tx_buffer[_tx_buffer_head] = c; _tx_buffer_head = i; sbi(*_ucsrb, UDRIE0); _written = true; return 1; } #endif // whole file <|endoftext|>
<commit_before>#include "SummaryDrawer.C" /** * Class to draw a summary of the AOD production * * @par Input: * - The merged <tt>forward.root</tt> file. * If the file isn't merged, it should still work. * * @par Output: * - A PDF file named after the input, but with <tt>.root</tt> * replaced with <tt>pdf</tt> * */ class SummaryMCCorrDrawer : public SummaryDrawer { public: enum EFlags { kEventInspector = 0x001, kTrackDensity = 0x002, kVertexBins = 0x004, kResults = 0x008, kCentral = 0x010, kNormal = 0x01F }; SummaryMCCorrDrawer() : SummaryDrawer(), fSums(0), fResults(0) {} virtual ~SummaryMCCorrDrawer() {} //__________________________________________________________________ /** * * * @param fname * @param what */ void Run(const char* fname, UShort_t what=kNormal) { // --- Open the file --------------------------------------------- TString filename(fname); TFile* file = TFile::Open(filename, "READ"); if (!file) { Error("Run", "Failed to open \"%s\"", filename.Data()); return; } // --- Get top-level collection ---------------------------------- fSums = GetCollection(file, "ForwardCorrSums"); if (!fSums) return; // --- Make our canvas ------------------------------------------- TString pdfName(filename); pdfName.ReplaceAll(".root", ".pdf"); CreateCanvas(pdfName, what & kLandscape); // --- Make a Title page ------------------------------------------- DrawTitlePage(file); // --- Possibly make a chapter here ------------------------------ if (what & kCentral && GetCollection(file, "CentralCorrSums")) MakeChapter("Forward"); // --- Set pause flag -------------------------------------------- fPause = what & kPause; // --- Do each sub-algorithm ------------------------------------- if (what & kEventInspector) DrawEventInspector(fSums); if (what & kTrackDensity) DrawTrackDensity(fSums); if (what & kVertexBins) DrawVertexBins(true); // --- Do the results ---------------------------------------------- fResults = GetCollection(file, "ForwardCorrResults"); if (!fResults) fResults = fSums; // Old-style if (what & kResults) DrawResults(true); // --- SPD clusters ---------------------------------------------- if (what & kCentral) { // --- Get top-level collection -------------------------------- fSums = GetCollection(file, "CentralCorrSums"); if (fSums) { MakeChapter("Central"); if (what & kEventInspector) DrawEventInspector(fSums); if (what & kTrackDensity) DrawTrackDensity(fSums); if (what & kVertexBins) DrawVertexBins(false); } else Warning("", "No CentralCorrSums found"); fResults = GetCollection(file, "CentralCorrResults"); if (!fResults) fResults = fSums; // Old-style if (!fResults) Warning("", "No CentralCorrResults found"); if (what & kResults) DrawResults(false); } CloseCanvas(); } protected: //____________________________________________________________________ void DrawTitlePage(TFile* file) { TCollection* c = GetCollection(file, "ForwardCorrSums"); fBody->cd(); Double_t y = .9; TLatex* ltx = new TLatex(.5, y, "ESD+MC #rightarrow Corrections"); ltx->SetTextSize(0.07); ltx->SetTextFont(62); ltx->SetTextAlign(22); ltx->SetNDC(); ltx->Draw(); y -= .075; TCollection* ei = GetCollection(c, "fmdEventInspector"); if (ei) { UShort_t sys=0; UShort_t sNN=0; Int_t field=0; ULong_t runNo=0; GetParameter(ei, "sys", sys); GetParameter(ei, "sNN", sNN); GetParameter(ei, "field", field); GetParameter(ei, "runNo", runNo); TString tS; SysString(sys, tS); DrawParameter(y, "System", tS); TString tE; SNNString(sNN, tE); DrawParameter(y, "#sqrt{s_{NN}}", tE); DrawParameter(y, "L3 B field", Form("%+2dkG", field)); DrawParameter(y, "Run #", Form("%6lu", runNo)); } PrintCanvas("MC Corrections"); } //____________________________________________________________________ TCollection* GetVertexList(TCollection* parent, const TAxis& axis, Int_t bin) { TString folder = TString::Format("vtx%+05.1f_%+05.1f", axis.GetBinLowEdge(bin), axis.GetBinUpEdge(bin)); folder.ReplaceAll(".", "d"); folder.ReplaceAll("+", "p"); folder.ReplaceAll("-", "m"); TCollection* c = GetCollection(parent, folder); if (!c) Warning("DrawVertexBins", "List %s not found", folder.Data()); return c; } //____________________________________________________________________ void DrawVertexBins(Bool_t forward) { TH1* vtxHist = GetH1(fSums, "vtxAxis"); if (!vtxHist) return; Info("DrawVertexBins", "Drawing %s vertex bins - %d bins", forward ? "Forward" : "Central", vtxHist->GetNbinsX()); TAxis* vtxAxis = vtxHist->GetXaxis(); for (Int_t i = 1; i <= vtxAxis->GetNbins(); i++) { Info("DrawVertexBins", " - Bin %d (%+5.1f - %+5.1f)", i, vtxAxis->GetBinLowEdge(i), vtxAxis->GetBinUpEdge(i)); TCollection* c = GetVertexList(fSums, *vtxAxis, i); if (!c) continue; if (forward) { DivideForRings(true, true); for (UShort_t d = 1; d <= 3; d++) { for (UShort_t q = 0; q < (d == 1 ? 1 : 2); q++) { Char_t r = q == 0 ? 'I' : 'O'; DrawInRingPad(d,r, GetH2(c, Form("FMD%d%c_cache",d,r)), "colz"); } } DrawInPad(fBody, (fLandscape ? 4: 2), GetH2(c, "primary"), "colz"); } else { fBody->Divide(1,3, 0, 0); DrawInPad(fBody, 1, GetH2(c, "hits"), "colz"); DrawInPad(fBody, 2, GetH2(c, "clusters"), "colz"); DrawInPad(fBody, 3, GetH2(c, "primary"), "colz"); } PrintCanvas(Form("%s sums - IP_{z} bin %+5.1f - %+5.1f", (forward ? "Forward" : "Central"), vtxAxis->GetBinLowEdge(i), vtxAxis->GetBinUpEdge(i))); } } //____________________________________________________________________ void DrawResults(Bool_t forward) { Info("DrawResults", "Drawing resulting %s vertex bins", forward ? "Forward" : "Central"); TH1* vtxHist = GetH1(fSums, "vtxAxis"); if (!vtxHist) return; TAxis* vtxAxis = vtxHist->GetXaxis(); for (Int_t i = 1; i <= vtxAxis->GetNbins(); i++) { Info("DrawResults", " - Bin %d (%+5.1f - %+5.1f)", i, vtxAxis->GetBinLowEdge(i), vtxAxis->GetBinUpEdge(i)); TCollection* c = GetVertexList(fResults, *vtxAxis, i); if (!c) continue; if (forward) { THStack* all = new THStack("all", "2^{nd} correction averaged over #phi"); DivideForRings(true, true); for (UShort_t d = 1; d <= 3; d++) { for (UShort_t q = 0; q < (d == 1 ? 1 : 2); q++) { Char_t r = q == 0 ? 'I' : 'O'; // TVirtualPad* p = RingPad(d, r); // p->cd(); // p->Divide(1,2,0,0); TH2* h = GetH2(c, Form("FMD%d%c_vtxbin%03d",d,r,i)); DrawInRingPad(d,r, h,"colz"); // TVirtualPad* pp = p->cd(1); // TVirtualPad* ppp = p->cd(2); // ppp->SetRightMargin(pp->GetRightMargin()); TH1* hh = h->ProjectionX(); hh->Scale(1./ h->GetNbinsY()); hh->SetFillColor(RingColor(d,r)); hh->SetLineColor(RingColor(d,r)); hh->SetMarkerColor(RingColor(d,r)); hh->SetFillStyle(3001); hh->SetTitle(Form("#LT%s#GT", hh->GetTitle())); // DrawInPad(p,2, hh, "hist e"); all->Add(hh, "hist e"); } TVirtualPad* p = RingPad(0, '0'); p->SetBottomMargin(0.10); p->SetLeftMargin(0.10); p->SetRightMargin(0.05); DrawInRingPad(0, 'O', all, "nostack"); } } else { fBody->Divide(2,4,0,0); TH2* secMap = GetH2(c, "secMap"); TH2* secMapAlt = GetH2(c, "secMapEff"); if (!secMapAlt) secMapAlt = GetH2(c, "secMapHit"); TH1* acc = GetH1(c, "acc"); TH1* accAlt = GetH1(c, "accEff"); if (!accAlt) accAlt = GetH1(c, "accHit"); TH1* secMapProj = secMap->ProjectionX(); secMapProj->Scale(1./ secMap->GetNbinsY()); secMapProj->Divide(acc); secMapProj->SetFillColor(kRed+1); secMapProj->SetFillStyle(3001); secMapProj->SetTitle(Form("#LT%s#GT/Acceptance", secMap->GetTitle())); TH1* secMapAltProj = secMapAlt->ProjectionX(); secMapAltProj->Scale(1./ secMapAlt->GetNbinsY()); secMapAltProj->Divide(accAlt); secMapAltProj->SetFillColor(kBlue+1); secMapAltProj->SetFillStyle(3001); secMapAltProj->SetTitle(Form("#LT%s#GT/Acceptance", secMapAlt->GetTitle())); Double_t secMapMax = TMath::Max(secMap->GetMaximum(), secMapAlt->GetMaximum()); secMap->SetMaximum(secMapMax); secMapAlt->SetMaximum(secMapMax); Double_t secMapProjMax = TMath::Max(secMapProj->GetMaximum(), secMapAltProj->GetMaximum()); secMapProj->SetMaximum(secMapProjMax); secMapAltProj->SetMaximum(secMapProjMax); acc->SetFillColor(kRed+1); acc->SetFillStyle(3001); accAlt->SetFillColor(kBlue+1); accAlt->SetFillStyle(3001); Double_t accMax = TMath::Max(acc->GetMaximum(),accAlt->GetMaximum()); acc->SetMaximum(accMax); accAlt->SetMaximum(accMax); DrawInPad(fBody, 1, secMap, "colz", kGridx); DrawInPad(fBody, 2, secMapAlt, "colz", kGridx); TVirtualPad* p = fBody; TVirtualPad* pp = p->cd(1); TVirtualPad* ppp = p->cd(3); ppp->SetRightMargin(pp->GetRightMargin()); DrawInPad(p,3, secMapProj, "hist", kGridx|kGridy); ppp = p->cd(5); ppp->SetRightMargin(pp->GetRightMargin()); DrawInPad(fBody, 5, acc, "", kGridx|kGridy); pp = p->cd(2); pp->SetLeftMargin(0.10); ppp = p->cd(4); ppp->SetRightMargin(pp->GetRightMargin()); ppp->SetLeftMargin(0.10); DrawInPad(p,4, secMapAltProj, "hist", kGridx|kGridy); pp = p->cd(4); pp->SetLeftMargin(0.10); ppp = p->cd(6); ppp->SetRightMargin(pp->GetRightMargin()); ppp->SetLeftMargin(0.10); DrawInPad(fBody, 6, accAlt, "", kGridx|kGridy); DrawInPad(fBody, 7, GetH2(c, "diagnostics"), "colz"); TH2* ratio = static_cast<TH2*>(secMap->Clone("ratio")); ratio->Add(secMapAlt, -1); ratio->Divide(secMapAlt); ratio->SetTitle("Relative difference between maps"); ratio->SetZTitle("#frac{S - S_{alt}}{S_{alt}}"); pp = p->cd(8); pp->SetLeftMargin(0.10); DrawInPad(fBody, 8, ratio, "colz"); } PrintCanvas(Form("%s results - IP_{z} bin %+5.1f - %+5.1f", (forward ? "Forward" : "Central"), vtxAxis->GetBinLowEdge(i), vtxAxis->GetBinUpEdge(i))); } } TCollection* fSums; TCollection* fResults; }; // #endif <commit_msg>Fixes for bad data input<commit_after>#include "SummaryDrawer.C" /** * Class to draw a summary of the AOD production * * @par Input: * - The merged <tt>forward.root</tt> file. * If the file isn't merged, it should still work. * * @par Output: * - A PDF file named after the input, but with <tt>.root</tt> * replaced with <tt>pdf</tt> * */ class SummaryMCCorrDrawer : public SummaryDrawer { public: enum EFlags { kEventInspector = 0x001, kTrackDensity = 0x002, kVertexBins = 0x004, kResults = 0x008, kCentral = 0x010, kNormal = 0x01F }; SummaryMCCorrDrawer() : SummaryDrawer(), fSums(0), fResults(0) {} virtual ~SummaryMCCorrDrawer() {} //__________________________________________________________________ /** * * * @param fname * @param what */ void Run(const char* fname, UShort_t what=kNormal) { // --- Open the file --------------------------------------------- TString filename(fname); TFile* file = TFile::Open(filename, "READ"); if (!file) { Error("Run", "Failed to open \"%s\"", filename.Data()); return; } // --- Get top-level collection ---------------------------------- fSums = GetCollection(file, "ForwardCorrSums"); if (!fSums) return; // --- Make our canvas ------------------------------------------- TString pdfName(filename); pdfName.ReplaceAll(".root", ".pdf"); CreateCanvas(pdfName, what & kLandscape); // --- Make a Title page ------------------------------------------- DrawTitlePage(file); // --- Possibly make a chapter here ------------------------------ if (what & kCentral && GetCollection(file, "CentralCorrSums")) MakeChapter("Forward"); // --- Set pause flag -------------------------------------------- fPause = what & kPause; // --- Do each sub-algorithm ------------------------------------- if (what & kEventInspector) DrawEventInspector(fSums); if (what & kTrackDensity) DrawTrackDensity(fSums); if (what & kVertexBins) DrawVertexBins(true); // --- Do the results ---------------------------------------------- fResults = GetCollection(file, "ForwardCorrResults"); if (!fResults) fResults = fSums; // Old-style if (what & kResults) DrawResults(true); // --- SPD clusters ---------------------------------------------- if (what & kCentral) { // --- Get top-level collection -------------------------------- fSums = GetCollection(file, "CentralCorrSums"); if (fSums) { MakeChapter("Central"); if (what & kEventInspector) DrawEventInspector(fSums); if (what & kTrackDensity) DrawTrackDensity(fSums); if (what & kVertexBins) DrawVertexBins(false); } else Warning("", "No CentralCorrSums found"); fResults = GetCollection(file, "CentralCorrResults"); if (!fResults) fResults = fSums; // Old-style if (!fResults) Warning("", "No CentralCorrResults found"); if (what & kResults) DrawResults(false); } CloseCanvas(); } protected: //____________________________________________________________________ void DrawTitlePage(TFile* file) { TCollection* c = GetCollection(file, "ForwardCorrSums"); fBody->cd(); Double_t y = .9; TLatex* ltx = new TLatex(.5, y, "ESD+MC #rightarrow Corrections"); ltx->SetTextSize(0.07); ltx->SetTextFont(62); ltx->SetTextAlign(22); ltx->SetNDC(); ltx->Draw(); y -= .075; TCollection* ei = GetCollection(c, "fmdEventInspector"); if (ei) { UShort_t sys=0; UShort_t sNN=0; Int_t field=0; ULong_t runNo=0; GetParameter(ei, "sys", sys); GetParameter(ei, "sNN", sNN); GetParameter(ei, "field", field); GetParameter(ei, "runNo", runNo); TString tS; SysString(sys, tS); DrawParameter(y, "System", tS); TString tE; SNNString(sNN, tE); DrawParameter(y, "#sqrt{s_{NN}}", tE); DrawParameter(y, "L3 B field", Form("%+2dkG", field)); DrawParameter(y, "Run #", Form("%6lu", runNo)); } PrintCanvas("MC Corrections"); } //____________________________________________________________________ TCollection* GetVertexList(TCollection* parent, const TAxis& axis, Int_t bin) { TString folder = TString::Format("vtx%+05.1f_%+05.1f", axis.GetBinLowEdge(bin), axis.GetBinUpEdge(bin)); folder.ReplaceAll(".", "d"); folder.ReplaceAll("+", "p"); folder.ReplaceAll("-", "m"); TCollection* c = GetCollection(parent, folder); if (!c) Warning("DrawVertexBins", "List %s not found", folder.Data()); return c; } //____________________________________________________________________ void DrawVertexBins(Bool_t forward) { TH1* vtxHist = GetH1(fSums, "vtxAxis"); if (!vtxHist) return; Info("DrawVertexBins", "Drawing %s vertex bins - %d bins", forward ? "Forward" : "Central", vtxHist->GetNbinsX()); TAxis* vtxAxis = vtxHist->GetXaxis(); for (Int_t i = 1; i <= vtxAxis->GetNbins(); i++) { Info("DrawVertexBins", " - Bin %d (%+5.1f - %+5.1f)", i, vtxAxis->GetBinLowEdge(i), vtxAxis->GetBinUpEdge(i)); TCollection* c = GetVertexList(fSums, *vtxAxis, i); if (!c) continue; if (forward) { DivideForRings(true, true); for (UShort_t d = 1; d <= 3; d++) { for (UShort_t q = 0; q < (d == 1 ? 1 : 2); q++) { Char_t r = q == 0 ? 'I' : 'O'; DrawInRingPad(d,r, GetH2(c, Form("FMD%d%c_cache",d,r)), "colz"); } } DrawInPad(fBody, (fLandscape ? 4: 2), GetH2(c, "primary"), "colz"); } else { fBody->Divide(1,3, 0, 0); DrawInPad(fBody, 1, GetH2(c, "hits"), "colz"); DrawInPad(fBody, 2, GetH2(c, "clusters"), "colz"); DrawInPad(fBody, 3, GetH2(c, "primary"), "colz"); } PrintCanvas(Form("%s sums - IP_{z} bin %+5.1f - %+5.1f", (forward ? "Forward" : "Central"), vtxAxis->GetBinLowEdge(i), vtxAxis->GetBinUpEdge(i))); } } //____________________________________________________________________ void DrawResults(Bool_t forward) { Info("DrawResults", "Drawing resulting %s vertex bins", forward ? "Forward" : "Central"); TH1* vtxHist = GetH1(fSums, "vtxAxis"); if (!vtxHist) return; TAxis* vtxAxis = vtxHist->GetXaxis(); for (Int_t i = 1; i <= vtxAxis->GetNbins(); i++) { Info("DrawResults", " - Bin %d (%+5.1f - %+5.1f)", i, vtxAxis->GetBinLowEdge(i), vtxAxis->GetBinUpEdge(i)); TCollection* c = GetVertexList(fResults, *vtxAxis, i); if (!c) continue; if (forward) { THStack* all = new THStack("all", "2^{nd} correction averaged over #phi"); DivideForRings(true, true); for (UShort_t d = 1; d <= 3; d++) { for (UShort_t q = 0; q < (d == 1 ? 1 : 2); q++) { Char_t r = q == 0 ? 'I' : 'O'; // TVirtualPad* p = RingPad(d, r); // p->cd(); // p->Divide(1,2,0,0); TH2* h = GetH2(c, Form("FMD%d%c_vtxbin%03d",d,r,i)); DrawInRingPad(d,r, h,"colz"); // TVirtualPad* pp = p->cd(1); // TVirtualPad* ppp = p->cd(2); // ppp->SetRightMargin(pp->GetRightMargin()); TH1* hh = h->ProjectionX(); hh->Scale(1./ h->GetNbinsY()); hh->SetFillColor(RingColor(d,r)); hh->SetLineColor(RingColor(d,r)); hh->SetMarkerColor(RingColor(d,r)); hh->SetFillStyle(3001); hh->SetTitle(Form("#LT%s#GT", hh->GetTitle())); // DrawInPad(p,2, hh, "hist e"); all->Add(hh, "hist e"); } TVirtualPad* p = RingPad(0, '0'); p->SetBottomMargin(0.10); p->SetLeftMargin(0.10); p->SetRightMargin(0.05); DrawInRingPad(0, 'O', all, "nostack"); } } else { fBody->Divide(2,4,0,0); TH2* secMap = GetH2(c, "secMap"); TH2* secMapAlt = GetH2(c, "secMapEff"); if (!secMapAlt) secMapAlt = GetH2(c, "secMapHit"); TH1* acc = GetH1(c, "acc"); TH1* accAlt = GetH1(c, "accEff"); if (!accAlt) accAlt = GetH1(c, "accHit"); TH1* secMapProj = secMap->ProjectionX(); secMapProj->Scale(1./ secMap->GetNbinsY()); secMapProj->Divide(acc); secMapProj->SetFillColor(kRed+1); secMapProj->SetFillStyle(3001); secMapProj->SetTitle(Form("#LT%s#GT/Acceptance", secMap->GetTitle())); TH1* secMapAltProj = secMapAlt->ProjectionX(); secMapAltProj->Scale(1./ secMapAlt->GetNbinsY()); secMapAltProj->Divide(accAlt); secMapAltProj->SetFillColor(kBlue+1); secMapAltProj->SetFillStyle(3001); secMapAltProj->SetTitle(Form("#LT%s#GT/Acceptance", secMapAlt->GetTitle())); Double_t secMapMax = TMath::Max(secMap->GetMaximum(), secMapAlt->GetMaximum()); secMap->SetMaximum(secMapMax); secMapAlt->SetMaximum(secMapMax); Double_t secMapProjMax = TMath::Max(secMapProj->GetMaximum(), secMapAltProj->GetMaximum()); secMapProj->SetMaximum(secMapProjMax); secMapAltProj->SetMaximum(secMapProjMax); acc->SetFillColor(kRed+1); acc->SetFillStyle(3001); accAlt->SetFillColor(kBlue+1); accAlt->SetFillStyle(3001); Double_t accMax = TMath::Max(acc->GetMaximum(),accAlt->GetMaximum()); acc->SetMaximum(accMax); accAlt->SetMaximum(accMax); if (secMap->GetMean(1) > 0 && secMap->GetMean(2) > 0) DrawInPad(fBody, 1, secMap, "colz", kGridx); if (secMapAlt->GetMean(1) > 0 && secMapAlt->GetMean(2) > 0) DrawInPad(fBody, 2, secMapAlt, "colz", kGridx); TVirtualPad* p = fBody; TVirtualPad* pp = p->cd(1); TVirtualPad* ppp = p->cd(3); ppp->SetRightMargin(pp->GetRightMargin()); DrawInPad(p,3, secMapProj, "hist", kGridx|kGridy); ppp = p->cd(5); ppp->SetRightMargin(pp->GetRightMargin()); DrawInPad(fBody, 5, acc, "", kGridx|kGridy); pp = p->cd(2); pp->SetLeftMargin(0.10); ppp = p->cd(4); ppp->SetRightMargin(pp->GetRightMargin()); ppp->SetLeftMargin(0.10); DrawInPad(p,4, secMapAltProj, "hist", kGridx|kGridy); pp = p->cd(4); pp->SetLeftMargin(0.10); ppp = p->cd(6); ppp->SetRightMargin(pp->GetRightMargin()); ppp->SetLeftMargin(0.10); DrawInPad(fBody, 6, accAlt, "", kGridx|kGridy); TH2* diag = GetH2(c, "diagnostics"); if (diag->GetMean(1) > 0 && diag->GetMean(2) > 0) DrawInPad(fBody, 7, diag, "colz"); if (secMap->GetMean(1) > 0 && secMap->GetMean(2) > 0 && secMapAlt->GetMean(1) > 0 && secMapAlt->GetMean(2) > 0) { TH2* ratio = static_cast<TH2*>(secMap->Clone("ratio")); ratio->Add(secMapAlt, -1); ratio->Divide(secMapAlt); ratio->SetTitle("Relative difference between maps"); ratio->SetZTitle("#frac{S - S_{alt}}{S_{alt}}"); pp = p->cd(8); pp->SetLeftMargin(0.10); DrawInPad(fBody, 8, ratio, "colz"); } } PrintCanvas(Form("%s results - IP_{z} bin %+5.1f - %+5.1f", (forward ? "Forward" : "Central"), vtxAxis->GetBinLowEdge(i), vtxAxis->GetBinUpEdge(i))); } } TCollection* fSums; TCollection* fResults; }; // #endif <|endoftext|>
<commit_before> #include "OptFossilCollManagerFactory.h" #include "ChebyFossilCollManager.h" #include "SimulationConfiguration.h" #include "TimeWarpConfigurationManager.h" #include "ThreadedTimeWarpSimulationManager.h" #include "ThreadedChebyFossilCollManager.h" #include <WarpedDebug.h> OptFossilCollManagerFactory::OptFossilCollManagerFactory(){} OptFossilCollManagerFactory::~OptFossilCollManagerFactory(){ // myFossilManager will be deleted by the end user - the // TimeWarpSimulationManager } Configurable * OptFossilCollManagerFactory::allocate(SimulationConfiguration &configuration, Configurable *parent) const { Configurable *retval = NULL; TimeWarpSimulationManager *mySimulationManager = dynamic_cast<TimeWarpSimulationManager *> (parent); ThreadedTimeWarpSimulationManager *myThreadedSimulationManager = dynamic_cast<ThreadedTimeWarpSimulationManager *> (parent); ASSERT( mySimulationManager != NULL ); // the following cases are possible: // (1) Manager is Cheby. // (2) None is used. std::string optFossilCollManagerType = configuration.get_string( {"TimeWarp", "OptFossilCollManager", "Type"}, "None"); std::string simulationType = configuration.get_string({"Simulation"}, "Sequential"); if (optFossilCollManagerType == "Cheby") { int checkpointPeriod = configuration.get_int({"TimeWarp", "OptFossilCollManager", "CheckpointTime"}, 1000); int minSamples = configuration.get_int({"TimeWarp", "OptFossilCollManager", "MinimumSamples"}, 64); int maxSamples = configuration.get_int({"TimeWarp", "OptFossilCollManager", "MaximumSamples"}, 100); int defaultLength = configuration.get_int({"TimeWarp", "OptFossilCollManager", "DefaultLength"}, 2000); double riskFactor = 0.99; configuration.getOptFossilCollRiskFactor(riskFactor); if (simulationType == "ThreadedTimeWarp") { retval = new ThreadedChebyFossilCollManager(myThreadedSimulationManager, checkpointPeriod, minSamples, maxSamples, defaultLength, riskFactor); myThreadedSimulationManager->setOptFossilColl(true); } else { retval = new ChebyFossilCollManager(mySimulationManager, checkpointPeriod, minSamples, maxSamples, defaultLength, riskFactor); mySimulationManager->setOptFossilColl(true); debug::debugout << "(" << mySimulationManager->getSimulationManagerID() << ") configured a Cheby Optimistic Fossil Collection Manager " << "with checkpoint interval: " << checkpointPeriod << ", and risk factor: " << riskFactor << endl; } } else if (optFossilCollManagerType == "None") { retval = NULL; } else { mySimulationManager->shutdown( "Unknown FossilManager choice \"" + configuration.getGVTManagerType() + "\""); } return retval; } const OptFossilCollManagerFactory * OptFossilCollManagerFactory::instance(){ static OptFossilCollManagerFactory *singleton = new OptFossilCollManagerFactory(); return singleton; } <commit_msg>Removed getOptFossilCollRiskFactor usage.<commit_after> #include "OptFossilCollManagerFactory.h" #include "ChebyFossilCollManager.h" #include "SimulationConfiguration.h" #include "TimeWarpConfigurationManager.h" #include "ThreadedTimeWarpSimulationManager.h" #include "ThreadedChebyFossilCollManager.h" #include <WarpedDebug.h> OptFossilCollManagerFactory::OptFossilCollManagerFactory(){} OptFossilCollManagerFactory::~OptFossilCollManagerFactory(){ // myFossilManager will be deleted by the end user - the // TimeWarpSimulationManager } Configurable * OptFossilCollManagerFactory::allocate(SimulationConfiguration &configuration, Configurable *parent) const { Configurable *retval = NULL; TimeWarpSimulationManager *mySimulationManager = dynamic_cast<TimeWarpSimulationManager *> (parent); ThreadedTimeWarpSimulationManager *myThreadedSimulationManager = dynamic_cast<ThreadedTimeWarpSimulationManager *> (parent); ASSERT( mySimulationManager != NULL ); // the following cases are possible: // (1) Manager is Cheby. // (2) None is used. std::string optFossilCollManagerType = configuration.get_string( {"TimeWarp", "OptFossilCollManager", "Type"}, "None"); std::string simulationType = configuration.get_string({"Simulation"}, "Sequential"); if (optFossilCollManagerType == "Cheby") { int checkpointPeriod = configuration.get_int({"TimeWarp", "OptFossilCollManager", "CheckpointTime"}, 1000); int minSamples = configuration.get_int({"TimeWarp", "OptFossilCollManager", "MinimumSamples"}, 64); int maxSamples = configuration.get_int({"TimeWarp", "OptFossilCollManager", "MaximumSamples"}, 100); int defaultLength = configuration.get_int({"TimeWarp", "OptFossilCollManager", "DefaultLength"}, 2000); double riskFactor = configuration.get_double({"TimeWarp", "OptFossilCollManager", "AcceptableRisk"}, 0.99); configuration.getOptFossilCollRiskFactor(riskFactor); if (simulationType == "ThreadedTimeWarp") { retval = new ThreadedChebyFossilCollManager(myThreadedSimulationManager, checkpointPeriod, minSamples, maxSamples, defaultLength, riskFactor); myThreadedSimulationManager->setOptFossilColl(true); } else { retval = new ChebyFossilCollManager(mySimulationManager, checkpointPeriod, minSamples, maxSamples, defaultLength, riskFactor); mySimulationManager->setOptFossilColl(true); debug::debugout << "(" << mySimulationManager->getSimulationManagerID() << ") configured a Cheby Optimistic Fossil Collection Manager " << "with checkpoint interval: " << checkpointPeriod << ", and risk factor: " << riskFactor << endl; } } else if (optFossilCollManagerType == "None") { retval = NULL; } else { mySimulationManager->shutdown( "Unknown FossilManager choice \"" + configuration.getGVTManagerType() + "\""); } return retval; } const OptFossilCollManagerFactory * OptFossilCollManagerFactory::instance(){ static OptFossilCollManagerFactory *singleton = new OptFossilCollManagerFactory(); return singleton; } <|endoftext|>
<commit_before>#ifndef __STDAIR_BOM_BOMITERATOR_T_HPP #define __STDAIR_BOM_BOMITERATOR_T_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <vector> #include <map> // STDAIR #include <stdair/basic/BasTypes.hpp> namespace stdair { /** Template class aimed at iterating a list or a map of children BOM structure of a dedicated type. <br> This class aimed at implementing the "normal" operators except ones that needs to return a specific type (const/non-const) of iterator. */ template <typename ITERATOR> struct BomIteratorAbstract { protected: /** Normal constructor. */ BomIteratorAbstract (ITERATOR iIterator) : _itBomStructureObject (iIterator) { } /** Default constructor. */ BomIteratorAbstract () { } /** Default copy constructor. */ BomIteratorAbstract (const BomIteratorAbstract& iBomIterator) : _itBomStructureObject (iBomIterator._itBomStructureObject) { } /** Destructor. */ ~BomIteratorAbstract() { } public: // ///////////// Operators ////////////// /** Incrementing (prefix and postfix) operators. */ void operator++ () { ++_itBomStructureObject; } void operator++ (int) { ++_itBomStructureObject; } /** Decrementing (prefix and postfix) operators. */ void operator-- () { --_itBomStructureObject; } void operator-- (int) { --_itBomStructureObject; } /** Equality operators. */ bool operator== (const BomIteratorAbstract& iIt) { return _itBomStructureObject == iIt._itBomStructureObject; } bool operator!= (const BomIteratorAbstract& iIt) { return _itBomStructureObject != iIt._itBomStructureObject; } /** Relational operators. */ bool operator< (const BomIteratorAbstract& iIt) { return _itBomStructureObject < iIt._itBomStructureObject; } bool operator> (const BomIteratorAbstract& iIt) { return _itBomStructureObject > iIt._itBomStructureObject; } bool operator<= (const BomIteratorAbstract& iIt) { return _itBomStructureObject <= iIt._itBomStructureObject; } bool operator>= (const BomIteratorAbstract& iIt) { return _itBomStructureObject >= iIt._itBomStructureObject; } public: ///////////// Attributes ////////////// /** Iterator for the current BOM structure on the non-ordered list. */ ITERATOR _itBomStructureObject; }; /** Operators for BomIteratorAbstract that need to be implemented outside of BomIteratorAbstract scope. */ template<typename ITERATOR> inline typename ITERATOR::difference_type operator-(const BomIteratorAbstract<ITERATOR>& l, const BomIteratorAbstract<ITERATOR>& r) { return l._itBomStructureObject - r._itBomStructureObject; } /** Template class aimed at iterating a list or a map of children BOM structure of a dedicated type using const iterators. <br> This class aimed at implementing the specific operators for const iterators. */ template <typename BOM_CONTENT, typename ITERATOR> struct BomConstIterator_T : public BomIteratorAbstract<ITERATOR> { public: // Definition allowing to retrieve the parent type. typedef BomIteratorAbstract<ITERATOR> Parent_T; // Definition allowing to retrieve the corresponding bom structure. typedef typename BOM_CONTENT::BomStructure_T BomStructure_T; // Define the pair of string and pointer of BOM_CONTENT. typedef typename std::pair<std::string, const BOM_CONTENT*> value_type; // Definition allowing the retrieve the difference type of the ITERATOR. typedef typename ITERATOR::difference_type difference_type; public: /** Normal constructor. */ BomConstIterator_T (ITERATOR iIterator) : Parent_T (iIterator) { } /** Default constructor. */ BomConstIterator_T () { } /** Default copy constructor. */ BomConstIterator_T (const BomConstIterator_T& iBomIterator) : Parent_T (iBomIterator.Parent_T::_itBomStructureObject) { } /** Destructor. */ ~BomConstIterator_T() { } public: // ////////////// Additive Operators /////////////// BomConstIterator_T operator+ (const difference_type iIndex) { return BomConstIterator_T(Parent_T::_itBomStructureObject + iIndex); } BomConstIterator_T& operator+= (const difference_type iIndex) { Parent_T::_itBomStructureObject += iIndex; return *this; } BomConstIterator_T operator- (const difference_type iIndex) { return BomConstIterator_T(Parent_T::_itBomStructureObject - iIndex); } BomConstIterator_T& operator-= (const difference_type iIndex) { Parent_T::_itBomStructureObject -= iIndex; return *this; } // ////////////// Dereferencing Operators ////////////// /** Dereferencing operator for iterators on a list. */ const BOM_CONTENT& operator* () { const BomStructure_T* lBomStruct_ptr = *Parent_T::_itBomStructureObject; assert (lBomStruct_ptr != NULL); BOM_CONTENT* lBomContent_ptr = BomStructure::getBomContentPtr<BOM_CONTENT> (*lBomStruct_ptr); assert (lBomContent_ptr != NULL); return *lBomContent_ptr; } /** Dereferencing operator for iterators on a map. */ value_type* operator-> () { const MapKey_T& lKey = Parent_T::_itBomStructureObject->first; const BomStructure_T* lBomStruct_ptr = Parent_T::_itBomStructureObject->second; assert (lBomStruct_ptr != NULL); BOM_CONTENT* lBomContent_ptr = BomStructure::getBomContentPtr<BOM_CONTENT> (*lBomStruct_ptr); assert (lBomContent_ptr != NULL); // See the comment below, at the definition of the _intermediateValue // attribute _intermediateValue.first = lKey; _intermediateValue.second = lBomContent_ptr; return &_intermediateValue; } protected: /** Helper attribute. <br>It is necessary to define that value at the attribute level, because the operator->() method needs to return a pointer on it. If that value be temporary, i.e., created at the fly when the operator->() method returns, we would return a pointer on a temporary value, which is not good. */ value_type _intermediateValue; }; /** Operators for BomConstIterator_T that need to be implemented outside of BomConstIterator_T scope. */ template<typename BOM_CONTENT, typename ITERATOR> inline BomConstIterator_T<BOM_CONTENT, ITERATOR> operator+(const typename ITERATOR::difference_type n, const BomConstIterator_T<BOM_CONTENT, ITERATOR>& r) { // Definition allowing to retrieve the Parent_T of BomConstIterator_T. typedef typename BomConstIterator_T<BOM_CONTENT,ITERATOR>::Parent_T Parent_T; return BomConstIterator_T<BOM_CONTENT, ITERATOR> (n+r.Parent_T::_itBomStructureObject); } /** Template class aimed at iterating a list or a map of children BOM structure of a dedicated type using non-const iterators. <br> This class aimed at implementing the specific operators for non-const iterators. */ template <typename BOM_CONTENT, typename ITERATOR> struct BomIterator_T : public BomIteratorAbstract<ITERATOR> { public: // Definition allowing to retrieve the parent type. typedef BomIteratorAbstract<ITERATOR> Parent_T; // Definition allowing to retrieve the corresponding bom structure. typedef typename BOM_CONTENT::BomStructure_T BomStructure_T; // Define the pair of string and pointer of BOM_CONTENT. typedef typename std::pair<std::string, const BOM_CONTENT*> value_type; // Definition allowing the retrieve the difference type of the ITERATOR. typedef typename ITERATOR::difference_type difference_type; public: /** Normal constructor. */ BomIterator_T (ITERATOR iIterator) : Parent_T (iIterator) { } /** Default constructor. */ BomIterator_T () { } /** Default copy constructor. */ BomIterator_T (const BomIterator_T& iBomIterator) : Parent_T (iBomIterator.Parent_T::_itBomStructureObject) { } /** Destructor. */ ~BomIterator_T() { } public: // ////////////// Additive Operators /////////////// BomIterator_T operator+ (const difference_type iIndex) { return BomIterator_T(Parent_T::_itBomStructureObject + iIndex); } BomIterator_T& operator+= (const difference_type iIndex) { Parent_T::_itBomStructureObject += iIndex; return *this; } BomIterator_T operator- (const difference_type iIndex) { return BomIterator_T(Parent_T::_itBomStructureObject - iIndex); } BomIterator_T& operator-= (const difference_type iIndex) { Parent_T::_itBomStructureObject -= iIndex; return *this; } // ////////////// Dereferencing Operators ////////////// /** Dereferencing operator for iterators on a list. */ const BOM_CONTENT& operator* () { const BomStructure_T* lBomStruct_ptr = *Parent_T::_itBomStructureObject; assert (lBomStruct_ptr != NULL); BOM_CONTENT* lBomContent_ptr = BomStructure::getBomContentPtr<BOM_CONTENT> (*lBomStruct_ptr); assert (lBomContent_ptr != NULL); return *lBomContent_ptr; } /** Dereferencing operator for iterators on a map. */ value_type* operator-> () { const MapKey_T& lKey = Parent_T::_itBomStructureObject->first; const BomStructure_T* lBomStruct_ptr = Parent_T::_itBomStructureObject->second; assert (lBomStruct_ptr != NULL); BOM_CONTENT* lBomContent_ptr = BomStructure::getBomContentPtr<BOM_CONTENT> (*lBomStruct_ptr); assert (lBomContent_ptr != NULL); // See the comment below, at the definition of the _intermediateValue // attribute _intermediateValue.first = lKey; _intermediateValue.second = lBomContent_ptr; return &_intermediateValue; } protected: /** Helper attribute. <br>It is necessary to define that value at the attribute level, because the operator->() method needs to return a pointer on it. If that value be temporary, i.e., created at the fly when the operator->() method returns, we would return a pointer on a temporary value, which is not good. */ value_type _intermediateValue; }; /** Operators for BomIterator_T that need to be implemented outside of BomIterator_T scope. */ template<typename BOM_CONTENT, typename ITERATOR> inline BomIterator_T<BOM_CONTENT, ITERATOR> operator+(const typename ITERATOR::difference_type n, const BomIterator_T<BOM_CONTENT, ITERATOR>& r) { // Definition allowing to retrieve the Parent_T of BomIterator_T. typedef typename BomIterator_T<BOM_CONTENT,ITERATOR>::Parent_T Parent_T; return BomIterator_T<BOM_CONTENT, ITERATOR> (n+r.Parent_T::_itBomStructureObject); } } #endif // __STDAIR_BOM_BOMITERATOR_T_HPP <commit_msg>[Dev] Some small changes.<commit_after>#ifndef __STDAIR_BOM_BOMITERATOR_T_HPP #define __STDAIR_BOM_BOMITERATOR_T_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <vector> #include <map> // STDAIR #include <stdair/basic/BasTypes.hpp> namespace stdair { /** Template class aimed at iterating a list or a map of children BOM structure of a dedicated type. <br> This class aimed at implementing the "normal" operators except ones that needs to return a specific type (const/non-const) of iterator. */ template <typename ITERATOR> struct BomIteratorAbstract { protected: /** Normal constructor. */ BomIteratorAbstract (ITERATOR iIterator) : _itBomStructureObject (iIterator) { } /** Default constructor. */ BomIteratorAbstract () { } /** Default copy constructor. */ BomIteratorAbstract (const BomIteratorAbstract& iBomIterator) : _itBomStructureObject (iBomIterator._itBomStructureObject) { } /** Destructor. */ ~BomIteratorAbstract() { } public: // ///////////// Operators ////////////// /** Incrementing (prefix and postfix) operators. */ void operator++ () { ++_itBomStructureObject; } void operator++ (int) { ++_itBomStructureObject; } /** Decrementing (prefix and postfix) operators. */ void operator-- () { --_itBomStructureObject; } void operator-- (int) { --_itBomStructureObject; } /** Equality operators. */ bool operator== (const BomIteratorAbstract& iIt) { return _itBomStructureObject == iIt._itBomStructureObject; } bool operator!= (const BomIteratorAbstract& iIt) { return _itBomStructureObject != iIt._itBomStructureObject; } /** Relational operators. */ bool operator< (const BomIteratorAbstract& iIt) { return _itBomStructureObject < iIt._itBomStructureObject; } bool operator> (const BomIteratorAbstract& iIt) { return _itBomStructureObject > iIt._itBomStructureObject; } bool operator<= (const BomIteratorAbstract& iIt) { return _itBomStructureObject <= iIt._itBomStructureObject; } bool operator>= (const BomIteratorAbstract& iIt) { return _itBomStructureObject >= iIt._itBomStructureObject; } public: ///////////// Attributes ////////////// /** Iterator for the current BOM structure on the non-ordered list. */ ITERATOR _itBomStructureObject; }; /** Operators for BomIteratorAbstract that need to be implemented outside of BomIteratorAbstract scope. */ template<typename ITERATOR> inline typename ITERATOR::difference_type operator-(const BomIteratorAbstract<ITERATOR>& l, const BomIteratorAbstract<ITERATOR>& r) { return l._itBomStructureObject - r._itBomStructureObject; } /** Template class aimed at iterating a list or a map of children BOM structure of a dedicated type using const iterators. <br> This class aimed at implementing the specific operators for const iterators. */ template <typename BOM_CONTENT, typename ITERATOR> struct BomConstIterator_T : public BomIteratorAbstract<ITERATOR> { public: // Definition allowing to retrieve the parent type. typedef BomIteratorAbstract<ITERATOR> Parent_T; // Definition allowing to retrieve the corresponding bom structure. typedef typename BOM_CONTENT::BomStructure_T BomStructure_T; // Define the pair of string and pointer of BOM_CONTENT. typedef typename std::pair<std::string, const BOM_CONTENT*> value_type; // Definition allowing the retrieve the difference type of the ITERATOR. typedef typename ITERATOR::difference_type difference_type; public: /** Normal constructor. */ BomConstIterator_T (ITERATOR iIterator) : Parent_T (iIterator) { } /** Default constructor. */ BomConstIterator_T () { } /** Default copy constructor. */ BomConstIterator_T (const BomConstIterator_T& iBomIterator) : Parent_T (iBomIterator.Parent_T::_itBomStructureObject) { } /** Destructor. */ ~BomConstIterator_T() { } public: // ////////////// Additive Operators /////////////// BomConstIterator_T operator+ (const difference_type iIndex) { return BomConstIterator_T(Parent_T::_itBomStructureObject + iIndex); } BomConstIterator_T& operator+= (const difference_type iIndex) { Parent_T::_itBomStructureObject += iIndex; return *this; } BomConstIterator_T operator- (const difference_type iIndex) { return BomConstIterator_T(Parent_T::_itBomStructureObject - iIndex); } BomConstIterator_T& operator-= (const difference_type iIndex) { Parent_T::_itBomStructureObject -= iIndex; return *this; } // ////////////// Dereferencing Operators ////////////// /** Dereferencing operator for iterators on a list. */ const BOM_CONTENT& operator* () { const BomStructure_T* lBomStruct_ptr = *Parent_T::_itBomStructureObject; assert (lBomStruct_ptr != NULL); BOM_CONTENT* lBomContent_ptr = BomStructure::getBomContentPtr<BOM_CONTENT> (*lBomStruct_ptr); assert (lBomContent_ptr != NULL); return *lBomContent_ptr; } /** Dereferencing operator for iterators on a map. */ value_type* operator-> () { const MapKey_T& lKey = Parent_T::_itBomStructureObject->first; const BomStructure_T* lBomStruct_ptr = Parent_T::_itBomStructureObject->second; assert (lBomStruct_ptr != NULL); BOM_CONTENT* lBomContent_ptr = BomStructure::getBomContentPtr<BOM_CONTENT> (*lBomStruct_ptr); assert (lBomContent_ptr != NULL); // See the comment below, at the definition of the _intermediateValue // attribute _intermediateValue.first = lKey; _intermediateValue.second = lBomContent_ptr; return &_intermediateValue; } protected: /** Helper attribute. <br>It is necessary to define that value at the attribute level, because the operator->() method needs to return a pointer on it. If that value be temporary, i.e., created at the fly when the operator->() method returns, we would return a pointer on a temporary value, which is not good. */ value_type _intermediateValue; }; /** Operators for BomConstIterator_T that need to be implemented outside of BomConstIterator_T scope. */ template<typename BOM_CONTENT, typename ITERATOR> inline BomConstIterator_T<BOM_CONTENT, ITERATOR> operator+(const typename ITERATOR::difference_type n, const BomConstIterator_T<BOM_CONTENT, ITERATOR>& r) { // Definition allowing to retrieve the Parent_T of BomConstIterator_T. typedef typename BomConstIterator_T<BOM_CONTENT,ITERATOR>::Parent_T Parent_T; return BomConstIterator_T<BOM_CONTENT, ITERATOR> (n+r.Parent_T::_itBomStructureObject); } /** Template class aimed at iterating a list or a map of children BOM structure of a dedicated type using non-const iterators. <br> This class aimed at implementing the specific operators for non-const iterators. */ template <typename BOM_CONTENT, typename ITERATOR> struct BomIterator_T : public BomIteratorAbstract<ITERATOR> { public: // Definition allowing to retrieve the parent type. typedef BomIteratorAbstract<ITERATOR> Parent_T; // Definition allowing to retrieve the corresponding bom structure. typedef typename BOM_CONTENT::BomStructure_T BomStructure_T; // Define the pair of string and pointer of BOM_CONTENT. typedef typename std::pair<std::string, BOM_CONTENT*> value_type; // Definition allowing the retrieve the difference type of the ITERATOR. typedef typename ITERATOR::difference_type difference_type; public: /** Normal constructor. */ BomIterator_T (ITERATOR iIterator) : Parent_T (iIterator) { } /** Default constructor. */ BomIterator_T () { } /** Default copy constructor. */ BomIterator_T (const BomIterator_T& iBomIterator) : Parent_T (iBomIterator.Parent_T::_itBomStructureObject) { } /** Destructor. */ ~BomIterator_T() { } public: // ////////////// Additive Operators /////////////// BomIterator_T operator+ (const difference_type iIndex) { return BomIterator_T(Parent_T::_itBomStructureObject + iIndex); } BomIterator_T& operator+= (const difference_type iIndex) { Parent_T::_itBomStructureObject += iIndex; return *this; } BomIterator_T operator- (const difference_type iIndex) { return BomIterator_T(Parent_T::_itBomStructureObject - iIndex); } BomIterator_T& operator-= (const difference_type iIndex) { Parent_T::_itBomStructureObject -= iIndex; return *this; } // ////////////// Dereferencing Operators ////////////// /** Dereferencing operator for iterators on a list. */ BOM_CONTENT& operator* () { const BomStructure_T* lBomStruct_ptr = *Parent_T::_itBomStructureObject; assert (lBomStruct_ptr != NULL); BOM_CONTENT* lBomContent_ptr = BomStructure::getBomContentPtr<BOM_CONTENT> (*lBomStruct_ptr); assert (lBomContent_ptr != NULL); return *lBomContent_ptr; } /** Dereferencing operator for iterators on a map. */ value_type* operator-> () { const MapKey_T& lKey = Parent_T::_itBomStructureObject->first; const BomStructure_T* lBomStruct_ptr = Parent_T::_itBomStructureObject->second; assert (lBomStruct_ptr != NULL); BOM_CONTENT* lBomContent_ptr = BomStructure::getBomContentPtr<BOM_CONTENT> (*lBomStruct_ptr); assert (lBomContent_ptr != NULL); // See the comment below, at the definition of the _intermediateValue // attribute _intermediateValue.first = lKey; _intermediateValue.second = lBomContent_ptr; return &_intermediateValue; } protected: /** Helper attribute. <br>It is necessary to define that value at the attribute level, because the operator->() method needs to return a pointer on it. If that value be temporary, i.e., created at the fly when the operator->() method returns, we would return a pointer on a temporary value, which is not good. */ value_type _intermediateValue; }; /** Operators for BomIterator_T that need to be implemented outside of BomIterator_T scope. */ template<typename BOM_CONTENT, typename ITERATOR> inline BomIterator_T<BOM_CONTENT, ITERATOR> operator+(const typename ITERATOR::difference_type n, const BomIterator_T<BOM_CONTENT, ITERATOR>& r) { // Definition allowing to retrieve the Parent_T of BomIterator_T. typedef typename BomIterator_T<BOM_CONTENT,ITERATOR>::Parent_T Parent_T; return BomIterator_T<BOM_CONTENT, ITERATOR> (n+r.Parent_T::_itBomStructureObject); } } #endif // __STDAIR_BOM_BOMITERATOR_T_HPP <|endoftext|>
<commit_before>// Copyright (c) 2021 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/roudi/port_pool_data.hpp" #include "iceoryx_posh/internal/runtime/node_data.hpp" #include "iceoryx_posh/popo/typed_subscriber.hpp" #include "iceoryx_posh/roudi/port_pool.hpp" #include "test.hpp" using namespace ::testing; using ::testing::Return; using namespace iox::capro; namespace test { static constexpr uint32_t DEFAULT_DEVICE_ID{0u}; static constexpr uint32_t DEFAULT_MEMORY_TYPE{0u}; class PortPool_test : public Test { public: iox::roudi::PortPoolData portPoolData; iox::roudi::PortPool sut{portPoolData}; iox::capro::ServiceDescription serviceDescription{"service1", "instance1"}; iox::ProcessName_t applicationName{"AppNmae"}; iox::mepoo::MemoryManager memoryManager; iox::popo::PublisherOptions publisherOptions; iox::popo::SubscriberOptions subscriberOptions; }; TEST_F(PortPool_test, AddNodeDataSuccessfully) { auto nodeData = sut.addNodeData("processName", "nodeName", 999U); ASSERT_THAT(nodeData.value()->m_process, Eq(iox::ProcessName_t("processName"))); ASSERT_THAT(nodeData.value()->m_node, Eq(iox::ProcessName_t("nodeName"))); ASSERT_THAT(nodeData.value()->m_nodeDeviceIdentifier, Eq(999U)); } TEST_F(PortPool_test, AddMaxNodeDataSuccessfully) { iox::cxx::vector<iox::runtime::NodeData*, iox::MAX_NODE_NUMBER> nodeContainer; for (uint32_t i = 1U; i <= iox::MAX_NODE_NUMBER; ++i) { auto nodeData = sut.addNodeData("processName", "nodeName", i); if (!nodeData.has_error()) { nodeContainer.push_back(nodeData.value()); } } ASSERT_THAT(nodeContainer.size(), Eq(iox::MAX_NODE_NUMBER)); } TEST_F(PortPool_test, AddNodeDataFailsWhenNodeListIsFull) { auto errorHandlerCalled{false}; iox::Error errorHandlerType; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) { errorHandlerType = error; errorHandlerCalled = true; }); for (uint32_t i = 0U; i <= iox::MAX_NODE_NUMBER; ++i) { sut.addNodeData("processName", "nodeName", i); } ASSERT_THAT(errorHandlerCalled, Eq(true)); EXPECT_EQ(errorHandlerType, iox::Error::kPORT_POOL__NODELIST_OVERFLOW); } TEST_F(PortPool_test, GetNodeDataListSuccessfully) { sut.addNodeData("processName", "nodeName", 999U); auto nodeDataList = sut.getNodeDataList(); ASSERT_THAT(nodeDataList.size(), Eq(1U)); } TEST_F(PortPool_test, GetMaxNodeDataListSuccessfully) { iox::cxx::vector<iox::runtime::NodeData*, iox::MAX_NODE_NUMBER> nodeContainer; for (uint32_t i = 1U; i <= iox::MAX_NODE_NUMBER; ++i) { auto nodeData = sut.addNodeData("processName", "nodeName", i); if (!nodeData.has_error()) { nodeContainer.push_back(nodeData.value()); } } auto nodeDataList = sut.getNodeDataList(); ASSERT_THAT(nodeDataList.size(), Eq(iox::MAX_NODE_NUMBER)); } TEST_F(PortPool_test, RemoveNodeDataSuccessfully) { auto nodeData = sut.addNodeData("processName", "nodeName", 999U); sut.removeNodeData(nodeData.value()); auto nodeDataList = sut.getNodeDataList(); ASSERT_THAT(nodeDataList.size(), Eq(0U)); } TEST_F(PortPool_test, AddPublisherPortSuccessfully) { auto publisherPort = sut.addPublisherPort(serviceDescription, &memoryManager, applicationName, publisherOptions); EXPECT_THAT(publisherPort.value()->m_serviceDescription, Eq(ServiceDescription{"service1", "instance1"})); EXPECT_EQ(publisherPort.value()->m_processName, iox::ProcessName_t{"AppNmae"}); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_historyCapacity, 0UL); EXPECT_EQ(publisherPort.value()->m_nodeName, iox::NodeName_t{""}); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_memoryInfo.deviceId, DEFAULT_DEVICE_ID); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_memoryInfo.memoryType, DEFAULT_MEMORY_TYPE); } TEST_F(PortPool_test, AddMaxPublisherPortSuccessfully) { for (uint32_t i = 0; i < iox::MAX_PUBLISHERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppNmae" + std::to_string(i)}; auto publisherPort = sut.addPublisherPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, &memoryManager, applicationName, publisherOptions); EXPECT_THAT(publisherPort.value()->m_serviceDescription, Eq(ServiceDescription{iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)})); EXPECT_EQ(publisherPort.value()->m_processName, applicationName); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_historyCapacity, 0UL); EXPECT_EQ(publisherPort.value()->m_nodeName, iox::NodeName_t{""}); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_memoryInfo.deviceId, DEFAULT_DEVICE_ID); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_memoryInfo.memoryType, DEFAULT_MEMORY_TYPE); } } TEST_F(PortPool_test, AddPublisherPortOverflow) { auto errorHandlerCalled{false}; iox::Error errorHandlerType; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) { errorHandlerType = error; errorHandlerCalled = true; }); for (uint32_t i = 0; i <= iox::MAX_PUBLISHERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppNmae" + std::to_string(i)}; auto publisherPort = sut.addPublisherPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, &memoryManager, applicationName, publisherOptions); } ASSERT_THAT(errorHandlerCalled, Eq(true)); EXPECT_EQ(errorHandlerType, iox::Error::kPORT_POOL__PUBLISHERLIST_OVERFLOW); } TEST_F(PortPool_test, GetPublisherPortDataListSuccessfully) { sut.addPublisherPort(serviceDescription, &memoryManager, applicationName, publisherOptions); auto publisherPortDataList = sut.getPublisherPortDataList(); ASSERT_THAT(publisherPortDataList.size(), Eq(1U)); } TEST_F(PortPool_test, GetPublisherPortDataListCompletelyFilledSuccessfully) { for (uint32_t i = 0; i < iox::MAX_PUBLISHERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppNmae" + std::to_string(i)}; auto publisherPort = sut.addPublisherPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, &memoryManager, applicationName, publisherOptions); } auto publisherPortDataList = sut.getPublisherPortDataList(); ASSERT_THAT(publisherPortDataList.size(), Eq(iox::MAX_PUBLISHERS)); } TEST_F(PortPool_test, RemovePublisherPortSuccessfully) { auto publisherPort = sut.addPublisherPort(serviceDescription, &memoryManager, applicationName, publisherOptions); sut.removePublisherPort(publisherPort.value()); auto publisherPortDataList = sut.getPublisherPortDataList(); ASSERT_THAT(publisherPortDataList.size(), Eq(0U)); } TEST_F(PortPool_test, AddSubscriberPortSuccessfully) { auto subscriberPort = sut.addSubscriberPort(serviceDescription, applicationName, subscriberOptions); EXPECT_THAT(subscriberPort.value()->m_serviceDescription, Eq(ServiceDescription{"service1", "instance1"})); EXPECT_EQ(subscriberPort.value()->m_processName, iox::ProcessName_t{"AppNmae"}); EXPECT_EQ(subscriberPort.value()->m_nodeName, iox::NodeName_t{""}); EXPECT_EQ(subscriberPort.value()->m_historyRequest, 0U); EXPECT_EQ(subscriberPort.value()->m_chunkReceiverData.m_queue.capacity(), 256U); EXPECT_EQ(subscriberPort.value()->m_chunkReceiverData.m_memoryInfo.deviceId, DEFAULT_DEVICE_ID); EXPECT_EQ(subscriberPort.value()->m_chunkReceiverData.m_memoryInfo.memoryType, DEFAULT_MEMORY_TYPE); } TEST_F(PortPool_test, AddMaxSubscriberPortSuccessfully) { for (uint32_t i = 0; i < iox::MAX_SUBSCRIBERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppNmae" + std::to_string(i)}; auto subscriberPort = sut.addSubscriberPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, applicationName, subscriberOptions); EXPECT_THAT(subscriberPort.value()->m_serviceDescription, Eq(ServiceDescription{iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)})); EXPECT_EQ(subscriberPort.value()->m_processName, applicationName); EXPECT_EQ(subscriberPort.value()->m_nodeName, iox::NodeName_t{""}); EXPECT_EQ(subscriberPort.value()->m_chunkReceiverData.m_memoryInfo.deviceId, DEFAULT_DEVICE_ID); EXPECT_EQ(subscriberPort.value()->m_chunkReceiverData.m_memoryInfo.memoryType, DEFAULT_MEMORY_TYPE); } } TEST_F(PortPool_test, AddSubscriberPortOverflow) { auto errorHandlerCalled{false}; iox::Error errorHandlerType; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) { errorHandlerType = error; errorHandlerCalled = true; }); for (uint32_t i = 0; i <= iox::MAX_SUBSCRIBERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppNmae" + std::to_string(i)}; auto publisherPort = sut.addSubscriberPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, applicationName, subscriberOptions); } ASSERT_THAT(errorHandlerCalled, Eq(true)); EXPECT_EQ(errorHandlerType, iox::Error::kPORT_POOL__SUBSCRIBERLIST_OVERFLOW); } TEST_F(PortPool_test, GetSubscriberPortDataListSuccessfully) { auto subscriberPort = sut.addSubscriberPort(serviceDescription, applicationName, subscriberOptions); auto subscriberPortDataList = sut.getSubscriberPortDataList(); ASSERT_THAT(subscriberPortDataList.size(), Eq(1U)); } TEST_F(PortPool_test, GetSubscriberPortDataListCompletelyFilledSuccessfully) { for (uint32_t i = 0; i < iox::MAX_SUBSCRIBERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppNmae" + std::to_string(i)}; auto publisherPort = sut.addSubscriberPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, applicationName, subscriberOptions); } auto subscriberPortDataList = sut.getSubscriberPortDataList(); ASSERT_THAT(subscriberPortDataList.size(), Eq(iox::MAX_SUBSCRIBERS)); } TEST_F(PortPool_test, RemoveSubscriberPortSuccessfully) { auto subscriberPort = sut.addSubscriberPort(serviceDescription, applicationName, subscriberOptions); sut.removeSubscriberPort(subscriberPort.value()); auto subscriberPortDataList = sut.getSubscriberPortDataList(); ASSERT_THAT(subscriberPortDataList.size(), Eq(0U)); } } // namespace test <commit_msg>iox-#496 cleanup<commit_after>// Copyright (c) 2021 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/roudi/port_pool_data.hpp" #include "iceoryx_posh/internal/runtime/node_data.hpp" #include "iceoryx_posh/popo/typed_subscriber.hpp" #include "iceoryx_posh/roudi/port_pool.hpp" #include "test.hpp" using namespace ::testing; using ::testing::Return; using namespace iox::capro; namespace test { static constexpr uint32_t DEFAULT_DEVICE_ID{0u}; static constexpr uint32_t DEFAULT_MEMORY_TYPE{0u}; class PortPool_test : public Test { public: iox::roudi::PortPoolData m_portPoolData; iox::roudi::PortPool sut{m_portPoolData}; iox::capro::ServiceDescription m_serviceDescription{"service1", "instance1"}; iox::ProcessName_t m_applicationName{"AppName"}; iox::ProcessName_t m_processName{"processName"}; iox::ProcessName_t m_nodeName{"nodeName"}; const uint64_t m_nodeDeviceId = 999U; iox::mepoo::MemoryManager m_memoryManager; iox::popo::PublisherOptions m_publisherOptions; iox::popo::SubscriberOptions m_subscriberOptions; }; TEST_F(PortPool_test, AddNodeDataIsSuccessful) { auto nodeData = sut.addNodeData(m_processName, m_nodeName, m_nodeDeviceId); ASSERT_THAT(nodeData.value()->m_process, Eq(m_processName)); ASSERT_THAT(nodeData.value()->m_node, Eq(m_nodeName)); ASSERT_THAT(nodeData.value()->m_nodeDeviceIdentifier, Eq(m_nodeDeviceId)); } TEST_F(PortPool_test, AddNodeDataToMaxCapacityIsSuccessful) { iox::cxx::vector<iox::runtime::NodeData*, iox::MAX_NODE_NUMBER> nodeContainer; for (uint32_t i = 1U; i <= iox::MAX_NODE_NUMBER; ++i) { auto nodeData = sut.addNodeData(m_processName, m_nodeName, i); if (!nodeData.has_error()) { nodeContainer.push_back(nodeData.value()); } } ASSERT_THAT(nodeContainer.size(), Eq(iox::MAX_NODE_NUMBER)); } TEST_F(PortPool_test, AddNodeDataWhenNodeListIsFullReturnsError) { auto errorHandlerCalled{false}; iox::Error errorHandlerType; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) { errorHandlerType = error; errorHandlerCalled = true; }); for (uint32_t i = 0U; i <= iox::MAX_NODE_NUMBER; ++i) { sut.addNodeData(m_processName, m_nodeName, i); } ASSERT_THAT(errorHandlerCalled, Eq(true)); EXPECT_EQ(errorHandlerType, iox::Error::kPORT_POOL__NODELIST_OVERFLOW); } TEST_F(PortPool_test, GetNodeDataListWhenEmptyIsSuccessful) { auto nodeDataList = sut.getNodeDataList(); ASSERT_THAT(nodeDataList.size(), Eq(0U)); } TEST_F(PortPool_test, GetNodeDataListIsSuccessful) { sut.addNodeData(m_processName, m_nodeName, m_nodeDeviceId); auto nodeDataList = sut.getNodeDataList(); ASSERT_THAT(nodeDataList.size(), Eq(1U)); } TEST_F(PortPool_test, GetNodeDataListWithMaxCapacityIsSuccessful) { iox::cxx::vector<iox::runtime::NodeData*, iox::MAX_NODE_NUMBER> nodeContainer; for (uint32_t i = 1U; i <= iox::MAX_NODE_NUMBER; ++i) { auto nodeData = sut.addNodeData(m_processName, m_nodeName, i); if (!nodeData.has_error()) { nodeContainer.push_back(nodeData.value()); } } auto nodeDataList = sut.getNodeDataList(); ASSERT_THAT(nodeDataList.size(), Eq(iox::MAX_NODE_NUMBER)); } TEST_F(PortPool_test, RemoveNodeDataIsSuccessful) { auto nodeData = sut.addNodeData(m_processName, m_nodeName, m_nodeDeviceId); sut.removeNodeData(nodeData.value()); auto nodeDataList = sut.getNodeDataList(); ASSERT_THAT(nodeDataList.size(), Eq(0U)); } TEST_F(PortPool_test, AddPublisherPortIsSuccessful) { auto publisherPort = sut.addPublisherPort(m_serviceDescription, &m_memoryManager, m_applicationName, m_publisherOptions); EXPECT_THAT(publisherPort.value()->m_serviceDescription, Eq(ServiceDescription{"service1", "instance1"})); EXPECT_EQ(publisherPort.value()->m_processName, m_applicationName); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_historyCapacity, 0UL); EXPECT_EQ(publisherPort.value()->m_nodeName, iox::NodeName_t{""}); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_memoryInfo.deviceId, DEFAULT_DEVICE_ID); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_memoryInfo.memoryType, DEFAULT_MEMORY_TYPE); } TEST_F(PortPool_test, AddMaxPublisherPortWithMaxCapacityIsSuccessful) { for (uint32_t i = 0; i < iox::MAX_PUBLISHERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppName" + std::to_string(i)}; auto publisherPort = sut.addPublisherPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, &m_memoryManager, applicationName, m_publisherOptions); EXPECT_THAT(publisherPort.value()->m_serviceDescription, Eq(ServiceDescription{iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)})); EXPECT_EQ(publisherPort.value()->m_processName, applicationName); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_historyCapacity, 0UL); EXPECT_EQ(publisherPort.value()->m_nodeName, iox::NodeName_t{""}); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_memoryInfo.deviceId, DEFAULT_DEVICE_ID); EXPECT_EQ(publisherPort.value()->m_chunkSenderData.m_memoryInfo.memoryType, DEFAULT_MEMORY_TYPE); } } TEST_F(PortPool_test, AddPublisherPortWhenOverflowsReurnsError) { auto errorHandlerCalled{false}; iox::Error errorHandlerType; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) { errorHandlerType = error; errorHandlerCalled = true; }); for (uint32_t i = 0; i <= iox::MAX_PUBLISHERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppName" + std::to_string(i)}; auto publisherPort = sut.addPublisherPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, &m_memoryManager, applicationName, m_publisherOptions); } ASSERT_THAT(errorHandlerCalled, Eq(true)); EXPECT_EQ(errorHandlerType, iox::Error::kPORT_POOL__PUBLISHERLIST_OVERFLOW); } TEST_F(PortPool_test, GetPublisherPortDataListIsSuccessful) { auto publisherPortDataList = sut.getPublisherPortDataList(); EXPECT_THAT(publisherPortDataList.size(), Eq(0U)); sut.addPublisherPort(m_serviceDescription, &m_memoryManager, m_applicationName, m_publisherOptions); publisherPortDataList = sut.getPublisherPortDataList(); ASSERT_THAT(publisherPortDataList.size(), Eq(1U)); } TEST_F(PortPool_test, GetPublisherPortDataListWhenEmptyIsSuccessful) { auto nodeDataList = sut.getPublisherPortDataList(); ASSERT_THAT(nodeDataList.size(), Eq(0U)); } TEST_F(PortPool_test, GetPublisherPortDataListCompletelyFilledSuccessfully) { for (uint32_t i = 0; i < iox::MAX_PUBLISHERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppName" + std::to_string(i)}; auto publisherPort = sut.addPublisherPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, &m_memoryManager, applicationName, m_publisherOptions); } auto publisherPortDataList = sut.getPublisherPortDataList(); ASSERT_THAT(publisherPortDataList.size(), Eq(iox::MAX_PUBLISHERS)); } TEST_F(PortPool_test, RemovePublisherPortIsSuccessful) { auto publisherPort = sut.addPublisherPort(m_serviceDescription, &m_memoryManager, m_applicationName, m_publisherOptions); sut.removePublisherPort(publisherPort.value()); auto publisherPortDataList = sut.getPublisherPortDataList(); ASSERT_THAT(publisherPortDataList.size(), Eq(0U)); } TEST_F(PortPool_test, AddSubscriberPortIsSuccessful) { auto subscriberPort = sut.addSubscriberPort(m_serviceDescription, m_applicationName, m_subscriberOptions); EXPECT_THAT(subscriberPort.value()->m_serviceDescription, Eq(m_serviceDescription)); EXPECT_EQ(subscriberPort.value()->m_processName, m_applicationName); EXPECT_EQ(subscriberPort.value()->m_nodeName, iox::NodeName_t{""}); EXPECT_EQ(subscriberPort.value()->m_historyRequest, 0U); EXPECT_EQ(subscriberPort.value()->m_chunkReceiverData.m_queue.capacity(), 256U); EXPECT_EQ(subscriberPort.value()->m_chunkReceiverData.m_memoryInfo.deviceId, DEFAULT_DEVICE_ID); EXPECT_EQ(subscriberPort.value()->m_chunkReceiverData.m_memoryInfo.memoryType, DEFAULT_MEMORY_TYPE); } TEST_F(PortPool_test, AddSubscriberPortToMaxCapacityIsSuccessful) { for (uint32_t i = 0; i < iox::MAX_SUBSCRIBERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppName" + std::to_string(i)}; auto subscriberPort = sut.addSubscriberPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, applicationName, m_subscriberOptions); EXPECT_THAT(subscriberPort.value()->m_serviceDescription, Eq(ServiceDescription{iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)})); EXPECT_EQ(subscriberPort.value()->m_processName, applicationName); EXPECT_EQ(subscriberPort.value()->m_nodeName, iox::NodeName_t{""}); EXPECT_EQ(subscriberPort.value()->m_chunkReceiverData.m_memoryInfo.deviceId, DEFAULT_DEVICE_ID); EXPECT_EQ(subscriberPort.value()->m_chunkReceiverData.m_memoryInfo.memoryType, DEFAULT_MEMORY_TYPE); } } TEST_F(PortPool_test, AddSubscriberPortWhenOverflowsReurnsError) { auto errorHandlerCalled{false}; iox::Error errorHandlerType; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) { errorHandlerType = error; errorHandlerCalled = true; }); for (uint32_t i = 0; i <= iox::MAX_SUBSCRIBERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppName" + std::to_string(i)}; auto publisherPort = sut.addSubscriberPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, applicationName, m_subscriberOptions); } ASSERT_THAT(errorHandlerCalled, Eq(true)); EXPECT_EQ(errorHandlerType, iox::Error::kPORT_POOL__SUBSCRIBERLIST_OVERFLOW); } TEST_F(PortPool_test, GetSubscriberPortDataListIsSuccessful) { auto subscriberPortDataList = sut.getSubscriberPortDataList(); EXPECT_THAT(subscriberPortDataList.size(), Eq(0U)); auto subscriberPort = sut.addSubscriberPort(m_serviceDescription, m_applicationName, m_subscriberOptions); subscriberPortDataList = sut.getSubscriberPortDataList(); ASSERT_THAT(subscriberPortDataList.size(), Eq(1U)); } TEST_F(PortPool_test, GetSubscriberPortDataListWhenEmptyIsSuccessful) { auto nodeDataList = sut.getSubscriberPortDataList(); ASSERT_THAT(nodeDataList.size(), Eq(0U)); } TEST_F(PortPool_test, GetSubscriberPortDataListCompletelyFilledIsSuccessful) { for (uint32_t i = 0; i < iox::MAX_SUBSCRIBERS; ++i) { std::string service = "service" + std::to_string(i); std::string instance = "instance" + std::to_string(i); iox::ProcessName_t applicationName = {iox::cxx::TruncateToCapacity, "AppName" + std::to_string(i)}; auto publisherPort = sut.addSubscriberPort({iox::capro::IdString_t(iox::cxx::TruncateToCapacity, service), iox::capro::IdString_t(iox::cxx::TruncateToCapacity, instance)}, applicationName, m_subscriberOptions); } auto subscriberPortDataList = sut.getSubscriberPortDataList(); ASSERT_THAT(subscriberPortDataList.size(), Eq(iox::MAX_SUBSCRIBERS)); } TEST_F(PortPool_test, RemoveSubscriberPortIsSuccessful) { auto subscriberPort = sut.addSubscriberPort(m_serviceDescription, m_applicationName, m_subscriberOptions); sut.removeSubscriberPort(subscriberPort.value()); auto subscriberPortDataList = sut.getSubscriberPortDataList(); ASSERT_THAT(subscriberPortDataList.size(), Eq(0U)); } } // namespace test <|endoftext|>
<commit_before> /* Copyright (c) 2011, Peter Barrett ** ** Permission to use, copy, modify, and/or distribute this software for ** any purpose with or without fee is hereby granted, provided that the ** above copyright notice and this permission notice appear in all copies. ** ** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR ** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES ** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, ** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS ** SOFTWARE. */ #include "Platform.h" #include "USBAPI.h" #include <avr/wdt.h> #if defined(USBCON) #ifdef CDC_ENABLED #if (RAMEND < 1000) #define SERIAL_BUFFER_SIZE 16 #else #define SERIAL_BUFFER_SIZE 64 #endif struct ring_buffer { unsigned char buffer[SERIAL_BUFFER_SIZE]; volatile int head; volatile int tail; }; ring_buffer cdc_rx_buffer = { { 0 }, 0, 0}; typedef struct { u32 dwDTERate; u8 bCharFormat; u8 bParityType; u8 bDataBits; u8 lineState; } LineInfo; static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 }; #define WEAK __attribute__ ((weak)) extern const CDCDescriptor _cdcInterface PROGMEM; const CDCDescriptor _cdcInterface = { D_IAD(0,2,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,1), // CDC communication interface D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0), D_CDCCS(CDC_HEADER,0x10,0x01), // Header (1.10 bcd) D_CDCCS(CDC_CALL_MANAGEMENT,1,1), // Device handles call management (not) D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,6), // SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE), // Communication interface is master, data interface is slave 0 D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10,0x40), // CDC data interface D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0), D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,0x40,0), D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,0x40,0) }; int WEAK CDC_GetInterface(u8* interfaceNum) { interfaceNum[0] += 2; // uses 2 return USB_SendControl(TRANSFER_PGM,&_cdcInterface,sizeof(_cdcInterface)); } bool WEAK CDC_Setup(Setup& setup) { u8 r = setup.bRequest; u8 requestType = setup.bmRequestType; if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType) { if (CDC_GET_LINE_CODING == r) { USB_SendControl(0,(void*)&_usbLineInfo,7); return true; } } if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType) { if (CDC_SET_LINE_CODING == r) { USB_RecvControl((void*)&_usbLineInfo,7); return true; } if (CDC_SET_CONTROL_LINE_STATE == r) { _usbLineInfo.lineState = setup.wValueL; // auto-reset into the bootloader is triggered when the port, already // open at 1200 bps, is closed. this is the signal to start the watchdog // with a relatively long period so it can finish housekeeping tasks // like servicing endpoints before the sketch ends // We check DTR state to determine if host port is open (bit 0 of lineState). // Serial1.print(">"); Serial1.println(_usbLineInfo.lineState, HEX); if ((_usbLineInfo.lineState & 0x01) == 0 && _usbLineInfo.dwDTERate == 1200) { *(uint16_t *)0x0A00 = 0x7777; wdt_enable(WDTO_250MS); } else { // Most OSs do some intermediate steps when configuring ports and DTR can // twiggle more than once before stabilizing. // To avoid spurious resets we set the watchdog to 250ms and eventually // cancel if DTR goes back high. wdt_disable(); wdt_reset(); *(uint16_t *)0x0A00 = 0x0; } return true; } } return false; } int _serialPeek = -1; void Serial_::begin(uint16_t baud_count) { } void Serial_::end(void) { } void Serial_::accept(void) { ring_buffer *buffer = &cdc_rx_buffer; int c = USB_Recv(CDC_RX); int i = (unsigned int)(buffer->head+1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != buffer->tail) { buffer->buffer[buffer->head] = c; buffer->head = i; } } int Serial_::available(void) { ring_buffer *buffer = &cdc_rx_buffer; return (unsigned int)(SERIAL_BUFFER_SIZE + buffer->head - buffer->tail) % SERIAL_BUFFER_SIZE; } int Serial_::peek(void) { ring_buffer *buffer = &cdc_rx_buffer; if (buffer->head == buffer->tail) { return -1; } else { return buffer->buffer[buffer->tail]; } } int Serial_::read(void) { ring_buffer *buffer = &cdc_rx_buffer; // if the head isn't ahead of the tail, we don't have any characters if (buffer->head == buffer->tail) { return -1; } else { unsigned char c = buffer->buffer[buffer->tail]; buffer->tail = (unsigned int)(buffer->tail + 1) % SERIAL_BUFFER_SIZE; return c; } } void Serial_::flush(void) { USB_Flush(CDC_TX); } size_t Serial_::write(uint8_t c) { /* only try to send bytes if the high-level CDC connection itself is open (not just the pipe) - the OS should set lineState when the port is opened and clear lineState when the port is closed. bytes sent before the user opens the connection or after the connection is closed are lost - just like with a UART. */ // TODO - ZE - check behavior on different OSes and test what happens if an // open connection isn't broken cleanly (cable is yanked out, host dies // or locks up, or host virtual serial port hangs) if (_usbLineInfo.lineState > 0) { int r = USB_Send(CDC_TX,&c,1); if (r > 0) { return r; } else { setWriteError(); return 0; } } setWriteError(); return 0; } Serial_ Serial; #endif #endif /* if defined(USBCON) */ <commit_msg>changed auto-reset logic for Leonardo. only do WDT manipulation if the port is opened at 1200 bps. (Dave Mellis)<commit_after> /* Copyright (c) 2011, Peter Barrett ** ** Permission to use, copy, modify, and/or distribute this software for ** any purpose with or without fee is hereby granted, provided that the ** above copyright notice and this permission notice appear in all copies. ** ** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR ** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES ** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, ** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS ** SOFTWARE. */ #include "Platform.h" #include "USBAPI.h" #include <avr/wdt.h> #if defined(USBCON) #ifdef CDC_ENABLED #if (RAMEND < 1000) #define SERIAL_BUFFER_SIZE 16 #else #define SERIAL_BUFFER_SIZE 64 #endif struct ring_buffer { unsigned char buffer[SERIAL_BUFFER_SIZE]; volatile int head; volatile int tail; }; ring_buffer cdc_rx_buffer = { { 0 }, 0, 0}; typedef struct { u32 dwDTERate; u8 bCharFormat; u8 bParityType; u8 bDataBits; u8 lineState; } LineInfo; static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 }; #define WEAK __attribute__ ((weak)) extern const CDCDescriptor _cdcInterface PROGMEM; const CDCDescriptor _cdcInterface = { D_IAD(0,2,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,1), // CDC communication interface D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0), D_CDCCS(CDC_HEADER,0x10,0x01), // Header (1.10 bcd) D_CDCCS(CDC_CALL_MANAGEMENT,1,1), // Device handles call management (not) D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,6), // SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE), // Communication interface is master, data interface is slave 0 D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10,0x40), // CDC data interface D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0), D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,0x40,0), D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,0x40,0) }; int WEAK CDC_GetInterface(u8* interfaceNum) { interfaceNum[0] += 2; // uses 2 return USB_SendControl(TRANSFER_PGM,&_cdcInterface,sizeof(_cdcInterface)); } bool WEAK CDC_Setup(Setup& setup) { u8 r = setup.bRequest; u8 requestType = setup.bmRequestType; if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType) { if (CDC_GET_LINE_CODING == r) { USB_SendControl(0,(void*)&_usbLineInfo,7); return true; } } if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType) { if (CDC_SET_LINE_CODING == r) { USB_RecvControl((void*)&_usbLineInfo,7); return true; } if (CDC_SET_CONTROL_LINE_STATE == r) { _usbLineInfo.lineState = setup.wValueL; // auto-reset into the bootloader is triggered when the port, already // open at 1200 bps, is closed. this is the signal to start the watchdog // with a relatively long period so it can finish housekeeping tasks // like servicing endpoints before the sketch ends if (1200 == _usbLineInfo.dwDTERate) { // We check DTR state to determine if host port is open (bit 0 of lineState). // Serial1.print(">"); Serial1.println(_usbLineInfo.lineState, HEX); if ((_usbLineInfo.lineState & 0x01) == 0) { *(uint16_t *)0x0A00 = 0x7777; wdt_enable(WDTO_250MS); } else { // Most OSs do some intermediate steps when configuring ports and DTR can // twiggle more than once before stabilizing. // To avoid spurious resets we set the watchdog to 250ms and eventually // cancel if DTR goes back high. wdt_disable(); wdt_reset(); *(uint16_t *)0x0A00 = 0x0; } } return true; } } return false; } int _serialPeek = -1; void Serial_::begin(uint16_t baud_count) { } void Serial_::end(void) { } void Serial_::accept(void) { ring_buffer *buffer = &cdc_rx_buffer; int c = USB_Recv(CDC_RX); int i = (unsigned int)(buffer->head+1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != buffer->tail) { buffer->buffer[buffer->head] = c; buffer->head = i; } } int Serial_::available(void) { ring_buffer *buffer = &cdc_rx_buffer; return (unsigned int)(SERIAL_BUFFER_SIZE + buffer->head - buffer->tail) % SERIAL_BUFFER_SIZE; } int Serial_::peek(void) { ring_buffer *buffer = &cdc_rx_buffer; if (buffer->head == buffer->tail) { return -1; } else { return buffer->buffer[buffer->tail]; } } int Serial_::read(void) { ring_buffer *buffer = &cdc_rx_buffer; // if the head isn't ahead of the tail, we don't have any characters if (buffer->head == buffer->tail) { return -1; } else { unsigned char c = buffer->buffer[buffer->tail]; buffer->tail = (unsigned int)(buffer->tail + 1) % SERIAL_BUFFER_SIZE; return c; } } void Serial_::flush(void) { USB_Flush(CDC_TX); } size_t Serial_::write(uint8_t c) { /* only try to send bytes if the high-level CDC connection itself is open (not just the pipe) - the OS should set lineState when the port is opened and clear lineState when the port is closed. bytes sent before the user opens the connection or after the connection is closed are lost - just like with a UART. */ // TODO - ZE - check behavior on different OSes and test what happens if an // open connection isn't broken cleanly (cable is yanked out, host dies // or locks up, or host virtual serial port hangs) if (_usbLineInfo.lineState > 0) { int r = USB_Send(CDC_TX,&c,1); if (r > 0) { return r; } else { setWriteError(); return 0; } } setWriteError(); return 0; } Serial_ Serial; #endif #endif /* if defined(USBCON) */ <|endoftext|>
<commit_before>/* * shared_ptr-impl.hpp - Copyright (C) 2007 by Nathan Reed * Implementation of shared_ptr class template. */ // Declaration of container for the refcounts #ifdef _MSC_VER typedef stdext::hash_map<void *, int> refcounts_t; #else struct ptr_hash { size_t operator () (void *v) const { static __gnu_cxx::hash<unsigned int> H; return H((unsigned int)v); } }; typedef __gnu_cxx::hash_map<void *, int, ptr_hash> refcounts_t; #endif extern refcounts_t refcounts_; /* * shared_ptr <T> implementation */ template <typename T> shared_ptr<T>::shared_ptr (T* ptr_): ptr(ptr_) { ++refcounts_[ptr]; } template <typename T> shared_ptr<T>::shared_ptr (const shared_ptr<T>& rhs): ptr(rhs.ptr) { ++refcounts_[ptr]; } template <typename T> template <typename U> shared_ptr<T>::shared_ptr (const shared_ptr<U>& rhs): ptr(static_cast<T*>(rhs.ptr)) { ++refcounts_[ptr]; } template <typename T> template <typename U> shared_ptr<T>& shared_ptr<T>::operator = (const shared_ptr<U>& rhs) { release(); ptr = static_cast<T*>(rhs.ptr); ++refcounts_[ptr]; return *this; } template <typename T> T* shared_ptr<T>::get () const { return ptr; } template <typename T> T* shared_ptr<T>::operator * () const { return ptr; } template <typename T> T* shared_ptr<T>::operator -> () const { return ptr; } template <typename T> void shared_ptr<T>::reset () { if (!ptr) return; if (--refcounts_[ptr] <= 0) delete ptr; ptr = 0; } template <typename T> shared_ptr<T>::~shared_ptr () { reset(); } <commit_msg>Fixed one more lingering reference to release() in shared_ptr<commit_after>/* * shared_ptr-impl.hpp - Copyright (C) 2007 by Nathan Reed * Implementation of shared_ptr class template. */ // Declaration of container for the refcounts #ifdef _MSC_VER typedef stdext::hash_map<void *, int> refcounts_t; #else struct ptr_hash { size_t operator () (void *v) const { static __gnu_cxx::hash<unsigned int> H; return H((unsigned int)v); } }; typedef __gnu_cxx::hash_map<void *, int, ptr_hash> refcounts_t; #endif extern refcounts_t refcounts_; /* * shared_ptr <T> implementation */ template <typename T> shared_ptr<T>::shared_ptr (T* ptr_): ptr(ptr_) { ++refcounts_[ptr]; } template <typename T> shared_ptr<T>::shared_ptr (const shared_ptr<T>& rhs): ptr(rhs.ptr) { ++refcounts_[ptr]; } template <typename T> template <typename U> shared_ptr<T>::shared_ptr (const shared_ptr<U>& rhs): ptr(static_cast<T*>(rhs.ptr)) { ++refcounts_[ptr]; } template <typename T> template <typename U> shared_ptr<T>& shared_ptr<T>::operator = (const shared_ptr<U>& rhs) { reset(); ptr = static_cast<T*>(rhs.ptr); ++refcounts_[ptr]; return *this; } template <typename T> T* shared_ptr<T>::get () const { return ptr; } template <typename T> T* shared_ptr<T>::operator * () const { return ptr; } template <typename T> T* shared_ptr<T>::operator -> () const { return ptr; } template <typename T> void shared_ptr<T>::reset () { if (!ptr) return; if (--refcounts_[ptr] <= 0) delete ptr; ptr = 0; } template <typename T> shared_ptr<T>::~shared_ptr () { reset(); } <|endoftext|>
<commit_before>#include <stdexcept> #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" using namespace cv; #include "feature.hpp" #include "FeatMat.hpp" #include "../saliency/saliency.hpp" #include "../util/opencv.hpp" Mat getFeatureVector(const Mat& img) { // Calculate saliency map Mat saliency = getSaliency(img); // Calculate gradient image Mat gradient = getGradient(img); // Calculate feature vector return getFeatureVector(saliency, gradient); } Mat getFeatureVector(const Mat& img, const Rect crop) { // Calculate saliency map Mat saliency = getSaliency(img); // Calculate gradient image Mat gradient = getGradient(img); return getFeatureVector(saliency, gradient, crop); } Mat getFeatureVector(const Mat& saliency, const Mat& gradient, const Rect crop) { return getFeatureVector(saliency(crop), gradient(crop)); } Mat getFeatureVector(const Mat& saliency, const Mat& gradient) { int h = saliency.rows, w = saliency.cols; // Resize saliency map to be 8x8. Use INTER_AREA to average pixel values Mat _saliency; #ifdef spsm3 resize(saliency, _saliency, Size(8, 8), INTER_AREA); #elif spsm2 resize(saliency, _saliency, Size(4, 4), INTER_AREA); #endif // Initialise feature vector Mat feats = Mat(Size(FEATS_N, 1), CV_32F); float* _feats = feats.ptr<float>(0); int i = 0; // Index in feature vector // Add mean values for 1/64ths float* p_saliency = _saliency.ptr<float>(0); #ifdef spsm3 for (int c = 0; c < 64; c++) { _feats[i] = p_saliency[i]; i++; } #endif // Add mean values for 1/16ths #ifdef spsm3 for (int j = 0; j < 4; j++) for (int k = 0; k < 4; k++) { _feats[i] = .25f * ( _feats[16 * j + 2 * k] + _feats[16 * j + 2 * k + 1] + _feats[16 * j + 2 * k + 8] + _feats[16 * j + 2 * k + 9] ); i++; } #elif spsm2 for (int c = 0; c < 16; c++) { _feats[i] = p_saliency[i]; i++; } #endif // Add mean values for 1/4ths for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) { _feats[i] = 0.25f * ( #ifdef spsm3 _feats[64 + 8 * j + 2 * k] + _feats[64 + 8 * j + 2 * k + 1] + _feats[64 + 8 * j + 2 * k + 4] + _feats[64 + 8 * j + 2 * k + 5] #elif spsm2 _feats[8 * j + 2 * k] + _feats[8 * j + 2 * k + 1] + _feats[8 * j + 2 * k + 4] + _feats[8 * j + 2 * k + 5] #endif ); i++; } // Add mean value for all pixels in saliency map _feats[i] = .25f * ( _feats[i - 4] + _feats[i - 3] + _feats[i - 2] + _feats[i - 1] ); return feats; } Mat getGradient(const Mat& img) { // Set to single-channel Mat gray; if (img.channels() == 3) { cvtColor(img, gray, CV_BGR2GRAY); } else gray = img; // Blur to remove high frequency textures Mat blurred; Size kernel_size = Size(3, 3); float sigma = 1.f; GaussianBlur(gray, blurred, kernel_size, sigma); // Calculate gradient of image Mat grad; Sobel(blurred, grad, CV_32F, 1, 1, 3); // Fix range Mat out; normalize(grad, out, 0.f, 1.f, NORM_MINMAX); return out; } <commit_msg>Don't crop gradient (not used and can be given empty image)<commit_after>#include <stdexcept> #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" using namespace cv; #include "feature.hpp" #include "FeatMat.hpp" #include "../saliency/saliency.hpp" #include "../util/opencv.hpp" Mat getFeatureVector(const Mat& img) { // Calculate saliency map Mat saliency = getSaliency(img); // Calculate gradient image Mat gradient = getGradient(img); // Calculate feature vector return getFeatureVector(saliency, gradient); } Mat getFeatureVector(const Mat& img, const Rect crop) { // Calculate saliency map Mat saliency = getSaliency(img); // Calculate gradient image Mat gradient = getGradient(img); return getFeatureVector(saliency, gradient, crop); } Mat getFeatureVector(const Mat& saliency, const Mat& gradient, const Rect crop) { // TODO: Remove gradient argument from getFeatureVector methods //return getFeatureVector(saliency(crop), gradient(crop)); return getFeatureVector(saliency(crop), gradient); } Mat getFeatureVector(const Mat& saliency, const Mat& gradient) { int h = saliency.rows, w = saliency.cols; // Resize saliency map to be 8x8. Use INTER_AREA to average pixel values Mat _saliency; #ifdef spsm3 resize(saliency, _saliency, Size(8, 8), INTER_AREA); #elif spsm2 resize(saliency, _saliency, Size(4, 4), INTER_AREA); #endif // Initialise feature vector Mat feats = Mat(Size(FEATS_N, 1), CV_32F); float* _feats = feats.ptr<float>(0); int i = 0; // Index in feature vector // Add mean values for 1/64ths float* p_saliency = _saliency.ptr<float>(0); #ifdef spsm3 for (int c = 0; c < 64; c++) { _feats[i] = p_saliency[i]; i++; } #endif // Add mean values for 1/16ths #ifdef spsm3 for (int j = 0; j < 4; j++) for (int k = 0; k < 4; k++) { _feats[i] = .25f * ( _feats[16 * j + 2 * k] + _feats[16 * j + 2 * k + 1] + _feats[16 * j + 2 * k + 8] + _feats[16 * j + 2 * k + 9] ); i++; } #elif spsm2 for (int c = 0; c < 16; c++) { _feats[i] = p_saliency[i]; i++; } #endif // Add mean values for 1/4ths for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) { _feats[i] = 0.25f * ( #ifdef spsm3 _feats[64 + 8 * j + 2 * k] + _feats[64 + 8 * j + 2 * k + 1] + _feats[64 + 8 * j + 2 * k + 4] + _feats[64 + 8 * j + 2 * k + 5] #elif spsm2 _feats[8 * j + 2 * k] + _feats[8 * j + 2 * k + 1] + _feats[8 * j + 2 * k + 4] + _feats[8 * j + 2 * k + 5] #endif ); i++; } // Add mean value for all pixels in saliency map _feats[i] = .25f * ( _feats[i - 4] + _feats[i - 3] + _feats[i - 2] + _feats[i - 1] ); return feats; } Mat getGradient(const Mat& img) { // Set to single-channel Mat gray; if (img.channels() == 3) { cvtColor(img, gray, CV_BGR2GRAY); } else gray = img; // Blur to remove high frequency textures Mat blurred; Size kernel_size = Size(3, 3); float sigma = 1.f; GaussianBlur(gray, blurred, kernel_size, sigma); // Calculate gradient of image Mat grad; Sobel(blurred, grad, CV_32F, 1, 1, 3); // Fix range Mat out; normalize(grad, out, 0.f, 1.f, NORM_MINMAX); return out; } <|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 "webkit/fileapi/file_system_dir_url_request_job.h" #include <algorithm> #include "base/compiler_specific.h" #include "base/file_util_proxy.h" #include "base/message_loop.h" #include "base/platform_file.h" #include "base/sys_string_conversions.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "build/build_config.h" #include "googleurl/src/gurl.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "net/url_request/url_request.h" #include "webkit/fileapi/file_system_path_manager.h" #include "webkit/fileapi/file_system_util.h" using net::URLRequest; using net::URLRequestJob; using net::URLRequestStatus; namespace fileapi { FileSystemDirURLRequestJob::FileSystemDirURLRequestJob( URLRequest* request, FileSystemPathManager* path_manager, scoped_refptr<base::MessageLoopProxy> file_thread_proxy) : URLRequestJob(request), path_manager_(path_manager), ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(callback_factory_(this)), file_thread_proxy_(file_thread_proxy) { } FileSystemDirURLRequestJob::~FileSystemDirURLRequestJob() { } void FileSystemDirURLRequestJob::Start() { MessageLoop::current()->PostTask(FROM_HERE, method_factory_.NewRunnableMethod( &FileSystemDirURLRequestJob::StartAsync)); } void FileSystemDirURLRequestJob::Kill() { URLRequestJob::Kill(); callback_factory_.RevokeAll(); } bool FileSystemDirURLRequestJob::ReadRawData(net::IOBuffer* dest, int dest_size, int *bytes_read) { int count = std::min(dest_size, static_cast<int>(data_.size())); if (count > 0) { memcpy(dest->data(), data_.data(), count); data_.erase(0, count); } *bytes_read = count; return true; } bool FileSystemDirURLRequestJob::GetMimeType(std::string* mime_type) const { *mime_type = "text/html"; return true; } bool FileSystemDirURLRequestJob::GetCharset(std::string* charset) { *charset = "utf-8"; return true; } void FileSystemDirURLRequestJob::StartAsync() { GURL origin_url; FileSystemType type; if (!CrackFileSystemURL(request_->url(), &origin_url, &type, &relative_dir_path_)) { NotifyFailed(net::ERR_INVALID_URL); return; } path_manager_->GetFileSystemRootPath( origin_url, type, false, // create callback_factory_.NewCallback( &FileSystemDirURLRequestJob::DidGetRootPath)); } void FileSystemDirURLRequestJob::DidGetRootPath(bool success, const FilePath& root_path, const std::string& name) { if (!success) { NotifyFailed(net::ERR_FILE_NOT_FOUND); return; } absolute_dir_path_ = root_path.Append(relative_dir_path_); // We assume it's a directory if we've gotten here: either the path // ends with '/', or FileSystemDirURLRequestJob already statted it and // found it to be a directory. base::FileUtilProxy::ReadDirectory(file_thread_proxy_, absolute_dir_path_, callback_factory_.NewCallback( &FileSystemDirURLRequestJob::DidReadDirectory)); } void FileSystemDirURLRequestJob::DidReadDirectory( base::PlatformFileError error_code, const std::vector<base::FileUtilProxy::Entry>& entries) { if (error_code != base::PLATFORM_FILE_OK) { NotifyFailed(error_code); return; } #if defined(OS_WIN) const string16& title = absolute_dir_path_.value(); #elif defined(OS_POSIX) const string16& title = WideToUTF16( base::SysNativeMBToWide(absolute_dir_path_.value())); #endif data_.append(net::GetDirectoryListingHeader(title)); typedef std::vector<base::FileUtilProxy::Entry>::const_iterator EntryIterator; for (EntryIterator it = entries.begin(); it != entries.end(); ++it) { #if defined(OS_WIN) const string16& name = it->name; #elif defined(OS_POSIX) const string16& name = WideToUTF16(base::SysNativeMBToWide(it->name)); #endif // TODO(adamk): Add file size? data_.append(net::GetDirectoryListingEntry( name, std::string(), it->is_directory, 0, base::Time())); } set_expected_content_size(data_.size()); NotifyHeadersComplete(); } void FileSystemDirURLRequestJob::NotifyFailed(int rv) { NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, rv)); } } // namespace fileapi <commit_msg>Display only the sandboxed portion of the URL when listing a filesystem: URL that refers to a directory.<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 "webkit/fileapi/file_system_dir_url_request_job.h" #include <algorithm> #include "base/compiler_specific.h" #include "base/file_util_proxy.h" #include "base/message_loop.h" #include "base/platform_file.h" #include "base/sys_string_conversions.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "build/build_config.h" #include "googleurl/src/gurl.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "net/url_request/url_request.h" #include "webkit/fileapi/file_system_path_manager.h" #include "webkit/fileapi/file_system_util.h" using net::URLRequest; using net::URLRequestJob; using net::URLRequestStatus; namespace fileapi { FileSystemDirURLRequestJob::FileSystemDirURLRequestJob( URLRequest* request, FileSystemPathManager* path_manager, scoped_refptr<base::MessageLoopProxy> file_thread_proxy) : URLRequestJob(request), path_manager_(path_manager), ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(callback_factory_(this)), file_thread_proxy_(file_thread_proxy) { } FileSystemDirURLRequestJob::~FileSystemDirURLRequestJob() { } void FileSystemDirURLRequestJob::Start() { MessageLoop::current()->PostTask(FROM_HERE, method_factory_.NewRunnableMethod( &FileSystemDirURLRequestJob::StartAsync)); } void FileSystemDirURLRequestJob::Kill() { URLRequestJob::Kill(); callback_factory_.RevokeAll(); } bool FileSystemDirURLRequestJob::ReadRawData(net::IOBuffer* dest, int dest_size, int *bytes_read) { int count = std::min(dest_size, static_cast<int>(data_.size())); if (count > 0) { memcpy(dest->data(), data_.data(), count); data_.erase(0, count); } *bytes_read = count; return true; } bool FileSystemDirURLRequestJob::GetMimeType(std::string* mime_type) const { *mime_type = "text/html"; return true; } bool FileSystemDirURLRequestJob::GetCharset(std::string* charset) { *charset = "utf-8"; return true; } void FileSystemDirURLRequestJob::StartAsync() { GURL origin_url; FileSystemType type; if (!CrackFileSystemURL(request_->url(), &origin_url, &type, &relative_dir_path_)) { NotifyFailed(net::ERR_INVALID_URL); return; } path_manager_->GetFileSystemRootPath( origin_url, type, false, // create callback_factory_.NewCallback( &FileSystemDirURLRequestJob::DidGetRootPath)); } void FileSystemDirURLRequestJob::DidGetRootPath(bool success, const FilePath& root_path, const std::string& name) { if (!success) { NotifyFailed(net::ERR_FILE_NOT_FOUND); return; } absolute_dir_path_ = root_path.Append(relative_dir_path_); // We assume it's a directory if we've gotten here: either the path // ends with '/', or FileSystemDirURLRequestJob already statted it and // found it to be a directory. base::FileUtilProxy::ReadDirectory(file_thread_proxy_, absolute_dir_path_, callback_factory_.NewCallback( &FileSystemDirURLRequestJob::DidReadDirectory)); } void FileSystemDirURLRequestJob::DidReadDirectory( base::PlatformFileError error_code, const std::vector<base::FileUtilProxy::Entry>& entries) { if (error_code != base::PLATFORM_FILE_OK) { NotifyFailed(error_code); return; } #if defined(OS_WIN) const string16& title = relative_dir_path_.value(); #elif defined(OS_POSIX) const string16& title = WideToUTF16( base::SysNativeMBToWide(relative_dir_path_.value())); #endif data_.append(net::GetDirectoryListingHeader(ASCIIToUTF16("/") + title)); typedef std::vector<base::FileUtilProxy::Entry>::const_iterator EntryIterator; for (EntryIterator it = entries.begin(); it != entries.end(); ++it) { #if defined(OS_WIN) const string16& name = it->name; #elif defined(OS_POSIX) const string16& name = WideToUTF16(base::SysNativeMBToWide(it->name)); #endif // TODO(adamk): Add file size? data_.append(net::GetDirectoryListingEntry( name, std::string(), it->is_directory, 0, base::Time())); } set_expected_content_size(data_.size()); NotifyHeadersComplete(); } void FileSystemDirURLRequestJob::NotifyFailed(int rv) { NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, rv)); } } // namespace fileapi <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "webkit/fileapi/media/filtering_file_enumerator.h" namespace fileapi { FilteringFileEnumerator::FilteringFileEnumerator( scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator> base_enumerator, MediaPathFilter* filter) : base_enumerator_(base_enumerator.Pass()), filter_(filter) { DCHECK(base_enumerator_.get()); DCHECK(filter); } FilteringFileEnumerator::~FilteringFileEnumerator() { } FilePath FilteringFileEnumerator::Next() { while (true) { FilePath next = base_enumerator_->Next(); if (next.empty() || base_enumerator_->IsDirectory() || filter_->Match(next)) return next; } } int64 FilteringFileEnumerator::Size() { return base_enumerator_->Size(); } base::Time FilteringFileEnumerator::LastModifiedTime() { return base_enumerator_->LastModifiedTime(); } bool FilteringFileEnumerator::IsDirectory() { return base_enumerator_->IsDirectory(); } } // namespace fileapi <commit_msg>[MediaGallery] Filter hidden media files and folders.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/logging.h" #include "build/build_config.h" #include "webkit/fileapi/media/filtering_file_enumerator.h" #if defined(OS_WIN) #include <windows.h> #else #include <cstring> #include "base/string_util.h" #endif namespace fileapi { namespace { // Used to skip the hidden folders and files. Returns true if the file specified // by |path| should be skipped. bool ShouldSkip(const FilePath& path) { const FilePath& base_name = path.BaseName(); if (base_name.empty()) return false; // Dot files (aka hidden files) if (base_name.value()[0] == '.') return true; // Mac OS X file. if (base_name.value() == FILE_PATH_LITERAL("__MACOSX")) return true; #if defined(OS_WIN) DWORD file_attributes = ::GetFileAttributes(path.value().c_str()); if ((file_attributes != INVALID_FILE_ATTRIBUTES) && ((file_attributes & FILE_ATTRIBUTE_HIDDEN) != 0)) return true; #else // Windows always creates a recycle bin folder in the attached device to store // all the deleted contents. On non-windows operating systems, there is no way // to get the hidden attribute of windows recycle bin folders that are present // on the attached device. Therefore, compare the file path name to the // recycle bin name and exclude those folders. For more details, please refer // to http://support.microsoft.com/kb/171694. const char win_98_recycle_bin_name[] = "RECYCLED"; const char win_xp_recycle_bin_name[] = "RECYCLER"; const char win_vista_recycle_bin_name[] = "$Recycle.bin"; if ((base::strncasecmp(base_name.value().c_str(), win_98_recycle_bin_name, strlen(win_98_recycle_bin_name)) == 0) || (base::strncasecmp(base_name.value().c_str(), win_xp_recycle_bin_name, strlen(win_xp_recycle_bin_name)) == 0) || (base::strncasecmp(base_name.value().c_str(), win_vista_recycle_bin_name, strlen(win_vista_recycle_bin_name)) == 0)) return true; #endif return false; } } // namespace FilteringFileEnumerator::FilteringFileEnumerator( scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator> base_enumerator, MediaPathFilter* filter) : base_enumerator_(base_enumerator.Pass()), filter_(filter) { DCHECK(base_enumerator_.get()); DCHECK(filter); } FilteringFileEnumerator::~FilteringFileEnumerator() { } FilePath FilteringFileEnumerator::Next() { while (true) { FilePath next = base_enumerator_->Next(); if (ShouldSkip(next)) continue; if (next.empty() || base_enumerator_->IsDirectory() || filter_->Match(next)) return next; } } int64 FilteringFileEnumerator::Size() { return base_enumerator_->Size(); } base::Time FilteringFileEnumerator::LastModifiedTime() { return base_enumerator_->LastModifiedTime(); } bool FilteringFileEnumerator::IsDirectory() { return base_enumerator_->IsDirectory(); } } // namespace fileapi <|endoftext|>
<commit_before>#include <stdio.h> #include <iostream> #include <assert.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char s1[]= "Hello, Mel. Today is sunday. Let's go party!"; fprintf (stdout,"%s -> %d\n",s1,strlen(s1) ); return 0; } ============================================================= #include <stdio.h> #include <iostream> #include <assert.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char s1[]= "Hello, Mel. Today is sunday. Let's go party!"; strcat(s1, "Melaniya!"); fprintf (stdout,"%s -> %d\n",s1,strlen(s1) ); return 0; } =============================================== Подава брой символи "strlen" : fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) ); =============================================== Добавя "strcat": strcat(s1, "- From team! :)"); ================================================ Сравнява "strcmp": strcmp("Hello", "Hello") = 0 strcmp(s1, "Hello") = 1 strcmp("Hello", s1) = -1 ================================================ Търси съвпадение на символ в стринга "*strchr" и дава съдържание: fprintf (stdout,"strchr -> %c\n",*strchr("Hello", 'H')); ако не ползване * се получава НОТА :) превърта; #include <stdio.h> #include <iostream> #include <assert.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char s1[]= "Hello, Mel. Today is sunday. Let's go party!"; strcat(s1, "- From team! :)"); fprintf (stdout,"strcmp -> %d\n",strcmp("Hello", "Hello")); fprintf (stdout,"strchr -> %c\n",strchr("Hello", 'H')); fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) ); return 0; } ================================================ адрес за обръщане на масив в обратен ред http://www.introprogramming.info/intro-csharp-book/read-online/glava7-masivi/ ================================================ #include <stdio.h> #include <iostream> #include <assert.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char s1[]= "Hello, Mel. Today is sunday. Let's go party!"; int i; fprintf (stdout,"%s -> %d\n",s1,strlen(s1) ); for (i=0; i<strlen(s1);i++) fprintf (stdout,"[%c]",s1[i]); return 0; } ============================================= #include <stdio.h> #include <iostream> #include <assert.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char s1[]= "Hello, Mel. Today is sunday. Let's go party!"; int i; fprintf (stdout,"%s -> %d\n",s1,strlen(s1) ); for (i=strlen(s1)-1;i>=0;i--) fprintf (stdout,"%c",s1[i]); return 0; } <commit_msg>Update experians.cpp<commit_after>#include <stdio.h> #include <iostream> #include <assert.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char s1[]= "Hello, Mel. Today is sunday. Let's go party!"; fprintf (stdout,"%s -> %d\n",s1,strlen(s1) ); return 0; } ============================================================= #include <stdio.h> #include <iostream> #include <assert.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char s1[]= "Hello, Mel. Today is sunday. Let's go party!"; strcat(s1, "Melaniya!"); fprintf (stdout,"%s -> %d\n",s1,strlen(s1) ); return 0; } =============================================== Подава брой символи "strlen" : fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) ); =============================================== Добавя "strcat": strcat(s1, "- From team! :)"); ================================================ Сравнява "strcmp": strcmp("Hello", "Hello") = 0 strcmp(s1, "Hello") = 1 strcmp("Hello", s1) = -1 ================================================ Търси съвпадение на символ в стринга "*strchr" и дава съдържание: fprintf (stdout,"strchr -> %c\n",*strchr("Hello", 'H')); ако не ползване * се получава НОТА :) превърта; #include <stdio.h> #include <iostream> #include <assert.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char s1[]= "Hello, Mel. Today is sunday. Let's go party!"; strcat(s1, "- From team! :)"); fprintf (stdout,"strcmp -> %d\n",strcmp("Hello", "Hello")); fprintf (stdout,"strchr -> %c\n",strchr("Hello", 'H')); fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) ); return 0; } ================================================ адрес за обръщане на масив в обратен ред http://www.introprogramming.info/intro-csharp-book/read-online/glava7-masivi/ ================================================ #include <stdio.h> #include <iostream> #include <assert.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char s1[]= "Hello, Mel. Today is sunday. Let's go party!"; int i; fprintf (stdout,"%s -> %d\n",s1,strlen(s1) ); for (i=0; i<strlen(s1);i++) fprintf (stdout,"[%c]",s1[i]); return 0; } ============================================= #include <stdio.h> #include <iostream> #include <assert.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char s1[]= "Hello, Mel. Today is sunday. Let's go party!"; int i; fprintf (stdout,"%s -> %d\n",s1,strlen(s1) ); for (i=strlen(s1)-1;i>=0;i--) fprintf (stdout,"%c",s1[i]); return 0; } ===================================== <|endoftext|>
<commit_before>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2017 Victor DENIS (victordenis01@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. ** ***********************************************************************************/ #include "Widgets/Tab/TabStackedWidget.hpp" #include <QApplication> #include <QTimer> #include "Widgets/Tab/ComboTabBar.hpp" namespace Sn { TabStackedWidget::TabStackedWidget(QWidget* parent) : QWidget(parent), m_currentIndex(-1), m_previousIndex(-1) { m_layout = new QVBoxLayout(this); m_layout->setSpacing(0); m_layout->setContentsMargins(0, 0, 0, 0); m_stack = new QStackedWidget(this); m_layout->addWidget(m_stack); connect(m_stack, &QStackedWidget::widgetRemoved, this, TabStackedWidget::tabWasRemoved); } TabStackedWidget::~TabStackedWidget() { // Empty } void TabStackedWidget::setTabBar(ComboTabBar* tab) { Q_ASSERT(tab); if (tab->parentWidget() != this) { tab->setParent(this); tab->show(); } delete m_comboTabBar; m_dirtyTabBar = true; m_comboTabBar = tab; setFocusProxy(m_comboTabBar); connect(m_comboTabBar, &ComboTabBar::currentChanged, this, &TabStackedWidget::showTab); connect(m_comboTabBar, &ComboTabBar::tabMoved, this, &TabStackedWidget::tabWasMoved); connect(m_comboTabBar, &ComboTabBar::overFlowChanged, this, &TabStackedWidget::setUpLayout); if (m_comboTabBar->tabsClosable()) connect(m_comboTabBar, &ComboTabBar::tabCloseRequested, this, &TabStackedWidget::tabCloseRequested); setDocumentMode(m_comboTabBar->documentMode()); m_comboTabBar->installEventFilter(this); setUpLayout(); } bool TabStackedWidget::documentMode() const { return m_comboTabBar->documentMode(); } void TabStackedWidget::setDocumentMode(bool enable) { m_comboTabBar->setDocumentMode(enable); m_comboTabBar->setDrawBase(enable); m_comboTabBar->setExpanding(!enable); } int TabStackedWidget::addTab(QWidget* widget, const QString& label, bool pinned) { return insertTab(-1, widget, label, pinned); } int TabStackedWidget::insertTab(int index, QWidget* widget, const QString& label, bool pinned) { if (!widget) return -1; if (pinned) { index = index < 0 ? m_comboTabBar->pinnedTabsCount() : qMin(index, m_comboTabBar->pinnedTabsCount()); index = m_stack->insertWidget(index, widget); m_comboTabBar->insertTab(index, QIcon(), label, true); } else { index = index < 0 ? -1 : qMax(index, m_comboTabBar->pinnedTabsCount()); index = m_stack->insertWidget(index, widget); m_comboTabBar->insertTab(index, QIcon(), label, false); } if (m_previousIndex >= index) ++m_previousIndex; if (m_currentIndex >= index) ++m_currentIndex; QTimer::singleShot(0, this, &TabStackedWidget::setUpLayout); } QString TabStackedWidget::tabText(int index) const { return m_comboTabBar->tabText(index); } void TabStackedWidget::setTabText(int index, const QString& label) { m_comboTabBar->setTabText(index, label); } QString TabStackedWidget::tabToolTip(int index) const { return m_comboTabBar->tabToolTip(index); } void TabStackedWidget::setTabToolTip(int index, const QString& tip) { m_comboTabBar->setTabToolTip(index, tip); } int TabStackedWidget::pinUnPinTab(int index, const QString& title) { QWidget* widget{m_stack->widget(index)}; QWidget* currentWidget{m_stack->currentWidget()}; if (!widget || !currentWidget) return -1; bool makePinned = index >= m_comboTabBar->pinnedTabsCount(); QWidget* button = m_comboTabBar->tabButton(index, m_comboTabBar->iconButtonPosition()); m_comboTabBar->m_blockCurrentChangedSignal = true; m_comboTabBar->setTabButton(index, m_comboTabBar->iconButtonPosition(), nullptr); m_stack->removeWidget(widget); int newIndex{insertTab(makePinned ? 0 : m_comboTabBar->pinnedTabsCount(), widget, title, makePinned)}; m_comboTabBar->setTabButton(newIndex, m_comboTabBar->iconButtonPosition(), button); m_comboTabBar->m_blockCurrentChangedSignal = false; setCurrentWidget(currentWidget); emit pinStateChanged(newIndex, makePinned); return newIndex; } void TabStackedWidget::removeTab(int index) { if (QWidget* widget = m_stack->widget(index)) { if (index == currentIndex() && count() > 1) selectTabOnRemove(); m_stack->removeWidget(widget); } } int TabStackedWidget::currentIndex() const { return m_comboTabBar->currentIndex(); } int TabStackedWidget::indexOf(QWidget* widget) const { return m_stack->indexOf(widget); } int TabStackedWidget::count() const { return m_comboTabBar->count(); } QWidget* TabStackedWidget::currentWidget() const { return m_stack->currentWidget(); } QWidget* TabStackedWidget::widget(int index) const { return m_stack->widget(index); } void TabStackedWidget::setCurrentIndex(int index) { m_comboTabBar->setCurrentIndex(index); } void TabStackedWidget::setCurrentWidget(QWidget* widget) { m_comboTabBar->setCurrentIndex(indexOf(widget)); } void TabStackedWidget::setUpLayout() { if (!m_comboTabBar->isVisible()) { m_dirtyTabBar = true; return; } m_comboTabBar->setElideMode(m_comboTabBar->elideMode()); m_dirtyTabBar = false; } bool TabStackedWidget::eventFilter(QObject* obj, QEvent* event) { if (m_dirtyTabBar & obj == m_comboTabBar && event->type() == QEvent::Show) setUpLayout(); return false; } void TabStackedWidget::keyPressEvent(QKeyEvent* event) { if ((event->key() == Qt::Key_Tab || event->key() == Qt::Key_Backtab) && count() > 1 && event->modifiers() & Qt::ControlModifier) { int pageCount{count()}; int page{currentIndex()}; int dx{(event->key() == Qt::Key_Backtab || event->modifiers() & Qt::ShiftModifier) ? -1 : 1}; for (int pass{0}; pass < pageCount; ++pass) { page += dx; if (page < 0) page = count() - 1; else if (page >= pageCount) page = 0; if (m_comboTabBar->isTabEnabled(page)) { setCurrentIndex(page); break; } } if (!QApplication::focusWidget()) m_comboTabBar->setFocus(); } else event->ignore(); } void TabStackedWidget::showTab(int index) { if (validIndex(index)) m_stack->setCurrentIndex(index); m_previousIndex = m_currentIndex; m_currentIndex = index; emit currentChanged(index); } void TabStackedWidget::tabWasMoved(int from, int to) { m_stack->blockSignals(true); QWidget* widget{m_stack->widget(from)}; m_stack->removeWidget(widget); m_stack->insertWidget(to, widget); m_stack->blockSignals(false); } void TabStackedWidget::tabWasRemoved(int index) { if (m_previousIndex == index) m_previousIndex = -1; else if (m_previousIndex > index) --m_previousIndex; if (m_currentIndex == index) m_currentIndex = -1; else if (m_currentIndex > index) --m_currentIndex; m_comboTabBar->removeTab(index); } bool TabStackedWidget::validIndex(int index) const { return (index < m_stack->count() && index >= 0); } void TabStackedWidget::selectTabOnRemove() { Q_ASSERT(count() > 1); int index{-1}; switch (m_comboTabBar->selectionBehaviorOnRemove()) { case QTabBar::SelectPreviousTab: if (validIndex(m_previousIndex)) { index == m_previousIndex; break; } case QTabBar::SelectLeftTab: index = currentIndex() - 1; if (!validIndex(index)) index = 1; break; case QTabBar::SelectRightTab: index = currentIndex() + 1; if (!validIndex(index)) index = currentIndex() - 1; break; default: break; } Q_ASSERT(validIndex(index)); setCurrentIndex(index); } }<commit_msg>Core/Widgets->Tab: (TabStackedWidget) [Fix] little mistake in a connection<commit_after>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2017 Victor DENIS (victordenis01@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. ** ***********************************************************************************/ #include "Widgets/Tab/TabStackedWidget.hpp" #include <QApplication> #include <QTimer> #include "Widgets/Tab/ComboTabBar.hpp" namespace Sn { TabStackedWidget::TabStackedWidget(QWidget* parent) : QWidget(parent), m_currentIndex(-1), m_previousIndex(-1) { m_layout = new QVBoxLayout(this); m_layout->setSpacing(0); m_layout->setContentsMargins(0, 0, 0, 0); m_stack = new QStackedWidget(this); m_layout->addWidget(m_stack); connect(m_stack, &QStackedWidget::widgetRemoved, this, &TabStackedWidget::tabWasRemoved); } TabStackedWidget::~TabStackedWidget() { // Empty } void TabStackedWidget::setTabBar(ComboTabBar* tab) { Q_ASSERT(tab); if (tab->parentWidget() != this) { tab->setParent(this); tab->show(); } delete m_comboTabBar; m_dirtyTabBar = true; m_comboTabBar = tab; setFocusProxy(m_comboTabBar); connect(m_comboTabBar, &ComboTabBar::currentChanged, this, &TabStackedWidget::showTab); connect(m_comboTabBar, &ComboTabBar::tabMoved, this, &TabStackedWidget::tabWasMoved); connect(m_comboTabBar, &ComboTabBar::overFlowChanged, this, &TabStackedWidget::setUpLayout); if (m_comboTabBar->tabsClosable()) connect(m_comboTabBar, &ComboTabBar::tabCloseRequested, this, &TabStackedWidget::tabCloseRequested); setDocumentMode(m_comboTabBar->documentMode()); m_comboTabBar->installEventFilter(this); setUpLayout(); } bool TabStackedWidget::documentMode() const { return m_comboTabBar->documentMode(); } void TabStackedWidget::setDocumentMode(bool enable) { m_comboTabBar->setDocumentMode(enable); m_comboTabBar->setDrawBase(enable); m_comboTabBar->setExpanding(!enable); } int TabStackedWidget::addTab(QWidget* widget, const QString& label, bool pinned) { return insertTab(-1, widget, label, pinned); } int TabStackedWidget::insertTab(int index, QWidget* widget, const QString& label, bool pinned) { if (!widget) return -1; if (pinned) { index = index < 0 ? m_comboTabBar->pinnedTabsCount() : qMin(index, m_comboTabBar->pinnedTabsCount()); index = m_stack->insertWidget(index, widget); m_comboTabBar->insertTab(index, QIcon(), label, true); } else { index = index < 0 ? -1 : qMax(index, m_comboTabBar->pinnedTabsCount()); index = m_stack->insertWidget(index, widget); m_comboTabBar->insertTab(index, QIcon(), label, false); } if (m_previousIndex >= index) ++m_previousIndex; if (m_currentIndex >= index) ++m_currentIndex; QTimer::singleShot(0, this, &TabStackedWidget::setUpLayout); } QString TabStackedWidget::tabText(int index) const { return m_comboTabBar->tabText(index); } void TabStackedWidget::setTabText(int index, const QString& label) { m_comboTabBar->setTabText(index, label); } QString TabStackedWidget::tabToolTip(int index) const { return m_comboTabBar->tabToolTip(index); } void TabStackedWidget::setTabToolTip(int index, const QString& tip) { m_comboTabBar->setTabToolTip(index, tip); } int TabStackedWidget::pinUnPinTab(int index, const QString& title) { QWidget* widget{m_stack->widget(index)}; QWidget* currentWidget{m_stack->currentWidget()}; if (!widget || !currentWidget) return -1; bool makePinned = index >= m_comboTabBar->pinnedTabsCount(); QWidget* button = m_comboTabBar->tabButton(index, m_comboTabBar->iconButtonPosition()); m_comboTabBar->m_blockCurrentChangedSignal = true; m_comboTabBar->setTabButton(index, m_comboTabBar->iconButtonPosition(), nullptr); m_stack->removeWidget(widget); int newIndex{insertTab(makePinned ? 0 : m_comboTabBar->pinnedTabsCount(), widget, title, makePinned)}; m_comboTabBar->setTabButton(newIndex, m_comboTabBar->iconButtonPosition(), button); m_comboTabBar->m_blockCurrentChangedSignal = false; setCurrentWidget(currentWidget); emit pinStateChanged(newIndex, makePinned); return newIndex; } void TabStackedWidget::removeTab(int index) { if (QWidget* widget = m_stack->widget(index)) { if (index == currentIndex() && count() > 1) selectTabOnRemove(); m_stack->removeWidget(widget); } } int TabStackedWidget::currentIndex() const { return m_comboTabBar->currentIndex(); } int TabStackedWidget::indexOf(QWidget* widget) const { return m_stack->indexOf(widget); } int TabStackedWidget::count() const { return m_comboTabBar->count(); } QWidget* TabStackedWidget::currentWidget() const { return m_stack->currentWidget(); } QWidget* TabStackedWidget::widget(int index) const { return m_stack->widget(index); } void TabStackedWidget::setCurrentIndex(int index) { m_comboTabBar->setCurrentIndex(index); } void TabStackedWidget::setCurrentWidget(QWidget* widget) { m_comboTabBar->setCurrentIndex(indexOf(widget)); } void TabStackedWidget::setUpLayout() { if (!m_comboTabBar->isVisible()) { m_dirtyTabBar = true; return; } m_comboTabBar->setElideMode(m_comboTabBar->elideMode()); m_dirtyTabBar = false; } bool TabStackedWidget::eventFilter(QObject* obj, QEvent* event) { if (m_dirtyTabBar & obj == m_comboTabBar && event->type() == QEvent::Show) setUpLayout(); return false; } void TabStackedWidget::keyPressEvent(QKeyEvent* event) { if ((event->key() == Qt::Key_Tab || event->key() == Qt::Key_Backtab) && count() > 1 && event->modifiers() & Qt::ControlModifier) { int pageCount{count()}; int page{currentIndex()}; int dx{(event->key() == Qt::Key_Backtab || event->modifiers() & Qt::ShiftModifier) ? -1 : 1}; for (int pass{0}; pass < pageCount; ++pass) { page += dx; if (page < 0) page = count() - 1; else if (page >= pageCount) page = 0; if (m_comboTabBar->isTabEnabled(page)) { setCurrentIndex(page); break; } } if (!QApplication::focusWidget()) m_comboTabBar->setFocus(); } else event->ignore(); } void TabStackedWidget::showTab(int index) { if (validIndex(index)) m_stack->setCurrentIndex(index); m_previousIndex = m_currentIndex; m_currentIndex = index; emit currentChanged(index); } void TabStackedWidget::tabWasMoved(int from, int to) { m_stack->blockSignals(true); QWidget* widget{m_stack->widget(from)}; m_stack->removeWidget(widget); m_stack->insertWidget(to, widget); m_stack->blockSignals(false); } void TabStackedWidget::tabWasRemoved(int index) { if (m_previousIndex == index) m_previousIndex = -1; else if (m_previousIndex > index) --m_previousIndex; if (m_currentIndex == index) m_currentIndex = -1; else if (m_currentIndex > index) --m_currentIndex; m_comboTabBar->removeTab(index); } bool TabStackedWidget::validIndex(int index) const { return (index < m_stack->count() && index >= 0); } void TabStackedWidget::selectTabOnRemove() { Q_ASSERT(count() > 1); int index{-1}; switch (m_comboTabBar->selectionBehaviorOnRemove()) { case QTabBar::SelectPreviousTab: if (validIndex(m_previousIndex)) { index == m_previousIndex; break; } case QTabBar::SelectLeftTab: index = currentIndex() - 1; if (!validIndex(index)) index = 1; break; case QTabBar::SelectRightTab: index = currentIndex() + 1; if (!validIndex(index)) index = currentIndex() - 1; break; default: break; } Q_ASSERT(validIndex(index)); setCurrentIndex(index); } }<|endoftext|>
<commit_before>/** \brief A MARC-21 filter uliity that replace URNs in 856u-fields with URLs * \author Oliver Obenland (oliver.obenland@uni-tuebingen.de) * \author Dr. Johannes Ruscheinski * * \copyright 2016-2018 Universitätsbibliothek Tübingen. All rights reserved. * * 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 <iostream> #include <string> #include <vector> #include "MARC.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [-v|--verbose] marc_input marc_output\n"; std::exit(EXIT_FAILURE); } inline bool IsHttpOrHttpsURL(const std::string &url_candidate) { return StringUtil::StartsWith(url_candidate, "http://") or StringUtil::StartsWith(url_candidate, "https://"); } // Returns the number of extracted 856u subfields. size_t ExtractAllHttpOrHttps856uSubfields(const MARC::Record &record, std::vector<std::string> * const _856u_urls) { for (const auto &_856_field : record.getTagRange("856")) { const std::string _856u_subfield_value(_856_field.getSubfields().getFirstSubfieldWithCode('u')); if (IsHttpOrHttpsURL(_856u_subfield_value)) _856u_urls->emplace_back(_856u_subfield_value); } return _856u_urls->size(); } inline std::string StripSchema(const std::string &url) { const auto colon_and_double_slash_start(url.find("://")); return (colon_and_double_slash_start == std::string::npos) ? url : url.substr(colon_and_double_slash_start + 3); } // Returns true if "test_string" is the suffix of "url" after stripping off the schema and domain name as well as // a single slash after the domain name. bool IsSuffixOfURL(const std::string &url, const std::string &test_string) { const bool starts_with_http(StringUtil::StartsWith(url, "http://")); if (not starts_with_http and not StringUtil::StartsWith(url, "https://")) return false; const std::string stripped_url(StripSchema(url)); const std::string stripped_test_string(StripSchema(test_string)); return StringUtil::EndsWith(stripped_url, stripped_test_string) or StringUtil::EndsWith(stripped_test_string, stripped_url); } // Returns true if "test_string" is a proper suffix of any of the URL's contained in "urls or vice versa". bool IsSuffixOfAnyURL(const std::unordered_set<std::string> &urls, const std::string &test_string) { for (const auto &url : urls) { if (IsSuffixOfURL(url, test_string) or IsSuffixOfURL(test_string, url)) return true; } return false; } bool CreateUrlsFrom024(MARC::Record * const record) { bool added_at_least_one_url(false); for (const auto &_024_field : record->getTagRange("024")) { if (_024_field.getFirstSubfieldWithCode('2') == "doi") { const std::string doi(_024_field.getFirstSubfieldWithCode('a')); if (not doi.empty()) { record->insertField("856", { { 'u', "https://doi.org/" + doi }, { 'x', "doi" } }); added_at_least_one_url = true; } } } return added_at_least_one_url; } void NormaliseURLs(const bool verbose, MARC::Reader * const reader, MARC::Writer * const writer) { unsigned count(0), modified_count(0), duplicate_skip_count(0); while (MARC::Record record = reader->read()) { ++count; bool modified_record(false); if (CreateUrlsFrom024(&record)) modified_record = true; std::vector<std::string> _856u_urls; ExtractAllHttpOrHttps856uSubfields(record, &_856u_urls); std::unordered_set<std::string> already_seen_links; auto _856_field(record.findTag("856")); while (_856_field != record.end() and _856_field->getTag() == "856") { MARC::Subfields _856_subfields(_856_field->getSubfields()); bool duplicate_link(false); if (_856_subfields.hasSubfield('u')) { std::string u_subfield(StringUtil::Trim(_856_subfields.getFirstSubfieldWithCode('u'))); if (already_seen_links.find(u_subfield) != already_seen_links.end()) { if (verbose) std::cout << "Found duplicate URL \"" << u_subfield << "\".\n"; duplicate_link = true; } else if (IsSuffixOfAnyURL(already_seen_links, u_subfield)) { if (verbose) std::cout << "Dropped field w/ duplicate URL suffix. (" << u_subfield << ")\n"; duplicate_link = true; already_seen_links.emplace(u_subfield); } else if (IsHttpOrHttpsURL(u_subfield)) already_seen_links.emplace(u_subfield); else { std::string new_http_replacement_link; if (StringUtil::StartsWith(u_subfield, "urn:")) new_http_replacement_link = "https://nbn-resolving.org/" + u_subfield; else if (StringUtil::StartsWith(u_subfield, "10900/")) new_http_replacement_link = "https://publikationen.uni-tuebingen.de/xmlui/handle/" + u_subfield; else new_http_replacement_link = "http://" + u_subfield; if (already_seen_links.find(new_http_replacement_link) == already_seen_links.cend()) { _856_subfields.replaceFirstSubfield('u', new_http_replacement_link); if (verbose) std::cout << "Replaced \"" << u_subfield << "\" with \"" << new_http_replacement_link << "\". (PPN: " << record.getControlNumber() << ")\n"; already_seen_links.insert(new_http_replacement_link); modified_record = true; } else duplicate_link = true; } } if (not duplicate_link) ++_856_field; else { ++duplicate_skip_count; if (verbose) std::cout << "Skipping duplicate, control numbers is " << record.getControlNumber() << ".\n"; _856_field = record.erase(_856_field); modified_record = true; } } if (modified_record) ++modified_count; writer->write(record); } std::cerr << "Read " << count << " records.\n"; std::cerr << "Modified " << modified_count << " record(s).\n"; std::cerr << "Skipped " << duplicate_skip_count << " duplicate links.\n"; } } // unnamed namespace int Main(int argc, char **argv) { if (argc < 2) Usage(); const bool verbose(std::strcmp("-v", argv[1]) == 0 or std::strcmp("--verbose", argv[1]) == 0); if (verbose) --argc, ++argv; if (argc < 2) Usage(); if (argc != 3) Usage(); auto marc_reader(MARC::Reader::Factory(argv[1])); auto marc_writer(MARC::Writer::Factory(argv[2])); NormaliseURLs(verbose, marc_reader.get(), marc_writer.get()); return EXIT_SUCCESS; } <commit_msg>Fixed an iterator-invalidation problem.<commit_after>/** \brief A MARC-21 filter uliity that replace URNs in 856u-fields with URLs * \author Oliver Obenland (oliver.obenland@uni-tuebingen.de) * \author Dr. Johannes Ruscheinski * * \copyright 2016-2018 Universitätsbibliothek Tübingen. All rights reserved. * * 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 <iostream> #include <string> #include <vector> #include "MARC.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [-v|--verbose] marc_input marc_output\n"; std::exit(EXIT_FAILURE); } inline bool IsHttpOrHttpsURL(const std::string &url_candidate) { return StringUtil::StartsWith(url_candidate, "http://") or StringUtil::StartsWith(url_candidate, "https://"); } // Returns the number of extracted 856u subfields. size_t ExtractAllHttpOrHttps856uSubfields(const MARC::Record &record, std::vector<std::string> * const _856u_urls) { for (const auto &_856_field : record.getTagRange("856")) { const std::string _856u_subfield_value(_856_field.getSubfields().getFirstSubfieldWithCode('u')); if (IsHttpOrHttpsURL(_856u_subfield_value)) _856u_urls->emplace_back(_856u_subfield_value); } return _856u_urls->size(); } inline std::string StripSchema(const std::string &url) { const auto colon_and_double_slash_start(url.find("://")); return (colon_and_double_slash_start == std::string::npos) ? url : url.substr(colon_and_double_slash_start + 3); } // Returns true if "test_string" is the suffix of "url" after stripping off the schema and domain name as well as // a single slash after the domain name. bool IsSuffixOfURL(const std::string &url, const std::string &test_string) { const bool starts_with_http(StringUtil::StartsWith(url, "http://")); if (not starts_with_http and not StringUtil::StartsWith(url, "https://")) return false; const std::string stripped_url(StripSchema(url)); const std::string stripped_test_string(StripSchema(test_string)); return StringUtil::EndsWith(stripped_url, stripped_test_string) or StringUtil::EndsWith(stripped_test_string, stripped_url); } // Returns true if "test_string" is a proper suffix of any of the URL's contained in "urls or vice versa". bool IsSuffixOfAnyURL(const std::unordered_set<std::string> &urls, const std::string &test_string) { for (const auto &url : urls) { if (IsSuffixOfURL(url, test_string) or IsSuffixOfURL(test_string, url)) return true; } return false; } bool CreateUrlsFrom024(MARC::Record * const record) { std::vector<std::string> _024_dois; for (const auto &_024_field : record->getTagRange("024")) { if (_024_field.getFirstSubfieldWithCode('2') == "doi") { const std::string doi(_024_field.getFirstSubfieldWithCode('a')); if (not doi.empty()) _024_dois.emplace_back(doi); } } for (const auto &_024_doi : _024_dois) record->insertField("856", { { 'u', "https://doi.org/" + _024_doi }, { 'x', "doi" } }); return not _024_dois.empty(); } void NormaliseURLs(const bool verbose, MARC::Reader * const reader, MARC::Writer * const writer) { unsigned count(0), modified_count(0), duplicate_skip_count(0); while (MARC::Record record = reader->read()) { ++count; bool modified_record(false); if (CreateUrlsFrom024(&record)) modified_record = true; std::vector<std::string> _856u_urls; ExtractAllHttpOrHttps856uSubfields(record, &_856u_urls); std::unordered_set<std::string> already_seen_links; auto _856_field(record.findTag("856")); while (_856_field != record.end() and _856_field->getTag() == "856") { MARC::Subfields _856_subfields(_856_field->getSubfields()); bool duplicate_link(false); if (_856_subfields.hasSubfield('u')) { std::string u_subfield(StringUtil::Trim(_856_subfields.getFirstSubfieldWithCode('u'))); if (already_seen_links.find(u_subfield) != already_seen_links.end()) { if (verbose) std::cout << "Found duplicate URL \"" << u_subfield << "\".\n"; duplicate_link = true; } else if (IsSuffixOfAnyURL(already_seen_links, u_subfield)) { if (verbose) std::cout << "Dropped field w/ duplicate URL suffix. (" << u_subfield << ")\n"; duplicate_link = true; already_seen_links.emplace(u_subfield); } else if (IsHttpOrHttpsURL(u_subfield)) already_seen_links.emplace(u_subfield); else { std::string new_http_replacement_link; if (StringUtil::StartsWith(u_subfield, "urn:")) new_http_replacement_link = "https://nbn-resolving.org/" + u_subfield; else if (StringUtil::StartsWith(u_subfield, "10900/")) new_http_replacement_link = "https://publikationen.uni-tuebingen.de/xmlui/handle/" + u_subfield; else new_http_replacement_link = "http://" + u_subfield; if (already_seen_links.find(new_http_replacement_link) == already_seen_links.cend()) { _856_subfields.replaceFirstSubfield('u', new_http_replacement_link); if (verbose) std::cout << "Replaced \"" << u_subfield << "\" with \"" << new_http_replacement_link << "\". (PPN: " << record.getControlNumber() << ")\n"; already_seen_links.insert(new_http_replacement_link); modified_record = true; } else duplicate_link = true; } } if (not duplicate_link) ++_856_field; else { ++duplicate_skip_count; if (verbose) std::cout << "Skipping duplicate, control numbers is " << record.getControlNumber() << ".\n"; _856_field = record.erase(_856_field); modified_record = true; } } if (modified_record) ++modified_count; writer->write(record); } std::cerr << "Read " << count << " records.\n"; std::cerr << "Modified " << modified_count << " record(s).\n"; std::cerr << "Skipped " << duplicate_skip_count << " duplicate links.\n"; } } // unnamed namespace int Main(int argc, char **argv) { if (argc < 2) Usage(); const bool verbose(std::strcmp("-v", argv[1]) == 0 or std::strcmp("--verbose", argv[1]) == 0); if (verbose) --argc, ++argv; if (argc < 2) Usage(); if (argc != 3) Usage(); auto marc_reader(MARC::Reader::Factory(argv[1])); auto marc_writer(MARC::Writer::Factory(argv[2])); NormaliseURLs(verbose, marc_reader.get(), marc_writer.get()); 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: NeonUri.cxx,v $ * $Revision: 1.24 $ * * 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_ucb.hxx" #include <string.h> #include <rtl/uri.hxx> #include <rtl/ustring.hxx> #include <rtl/ustrbuf.hxx> #include "NeonUri.hxx" #include "DAVException.hxx" #include "../inc/urihelper.hxx" using namespace webdav_ucp; char *scheme; char *host, *userinfo; unsigned int port; char *path, *query, *fragment; # if defined __SUNPRO_CC // FIXME: not sure whether initializing a ne_uri statically is supposed to work // the string fields of ne_uri are char*, not const char* # pragma disable_warn # endif namespace { const ne_uri g_sUriDefaultsHTTP = { "http", #if NEON_VERSION >= 0x0260 NULL, #endif NULL, DEFAULT_HTTP_PORT, #if NEON_VERSION >= 0x0260 NULL, #endif NULL, NULL }; const ne_uri g_sUriDefaultsHTTPS = { "https", #if NEON_VERSION >= 0x0260 NULL, #endif NULL, DEFAULT_HTTPS_PORT, #if NEON_VERSION >= 0x0260 NULL, #endif NULL, NULL }; const ne_uri g_sUriDefaultsFTP = { "ftp", #if NEON_VERSION >= 0x0260 NULL, #endif NULL, DEFAULT_FTP_PORT, #if NEON_VERSION >= 0x0260 NULL, #endif NULL, NULL }; } // namespace # if defined __SUNPRO_CC # pragma enable_warn #endif // ------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------- namespace { //TODO! rtl::OString::matchIgnoreAsciiCaseAsciiL() missing inline bool matchIgnoreAsciiCase(rtl::OString const & rStr1, sal_Char const * pStr2, sal_Int32 nStr2Len) SAL_THROW(()) { return rtl_str_shortenedCompareIgnoreAsciiCase_WithLength( rStr1.getStr(), rStr1.getLength(), pStr2, nStr2Len, nStr2Len) == 0; } } NeonUri::NeonUri( const ne_uri * inUri ) throw ( DAVException ) { if ( inUri == 0 ) throw DAVException( DAVException::DAV_INVALID_ARG ); char * uri = ne_uri_unparse( inUri ); if ( uri == 0 ) throw DAVException( DAVException::DAV_INVALID_ARG ); init( rtl::OString( uri ), inUri ); free( uri ); calculateURI(); } NeonUri::NeonUri( const rtl::OUString & inUri ) throw ( DAVException ) { if ( inUri.getLength() <= 0 ) throw DAVException( DAVException::DAV_INVALID_ARG ); // #i77023# rtl::OUString aEscapedUri( ucb_impl::urihelper::encodeURI( inUri ) ); rtl::OString theInputUri( aEscapedUri.getStr(), aEscapedUri.getLength(), RTL_TEXTENCODING_UTF8 ); ne_uri theUri; if ( ne_uri_parse( theInputUri.getStr(), &theUri ) != 0 ) { ne_uri_free( &theUri ); throw DAVException( DAVException::DAV_INVALID_ARG ); } init( theInputUri, &theUri ); ne_uri_free( &theUri ); calculateURI(); } void NeonUri::init( const rtl::OString & rUri, const ne_uri * pUri ) { // Complete URI. const ne_uri * pUriDefs = matchIgnoreAsciiCase( rUri, RTL_CONSTASCII_STRINGPARAM( "ftp:" ) ) ? &g_sUriDefaultsFTP : matchIgnoreAsciiCase( rUri, RTL_CONSTASCII_STRINGPARAM( "https:" ) ) ? &g_sUriDefaultsHTTPS : &g_sUriDefaultsHTTP; mScheme = rtl::OStringToOUString( pUri->scheme ? pUri->scheme : pUriDefs->scheme, RTL_TEXTENCODING_UTF8 ); mUserInfo = rtl::OStringToOUString( #if NEON_VERSION >= 0x0260 pUri->userinfo ? pUri->userinfo : pUriDefs->userinfo, #else pUri->authinfo ? pUri->authinfo : pUriDefs->authinfo, #endif RTL_TEXTENCODING_UTF8 ); mHostName = rtl::OStringToOUString( pUri->host ? pUri->host : pUriDefs->host, RTL_TEXTENCODING_UTF8 ); mPort = pUri->port > 0 ? pUri->port : pUriDefs->port; mPath = rtl::OStringToOUString( pUri->path ? pUri->path : pUriDefs->path, RTL_TEXTENCODING_UTF8 ); #if NEON_VERSION >= 0x0260 if ( pUri->query ) { mPath += rtl::OUString::createFromAscii( "?" ); mPath += rtl::OStringToOUString( pUri->query, RTL_TEXTENCODING_UTF8 ); } if ( pUri->fragment ) { mPath += rtl::OUString::createFromAscii( "#" ); mPath += rtl::OStringToOUString( pUri->fragment, RTL_TEXTENCODING_UTF8 ); } #endif } // ------------------------------------------------------------------- // Destructor // ------------------------------------------------------------------- NeonUri::~NeonUri( ) { } void NeonUri::calculateURI () { rtl::OUStringBuffer aBuf( mScheme ); aBuf.appendAscii( "://" ); if ( mUserInfo.getLength() > 0 ) { //TODO! differentiate between empty and missing userinfo aBuf.append( mUserInfo ); aBuf.appendAscii( "@" ); } // Is host a numeric IPv6 address? if ( ( mHostName.indexOf( ':' ) != -1 ) && ( mHostName[ 0 ] != sal_Unicode( '[' ) ) ) { aBuf.appendAscii( "[" ); aBuf.append( mHostName ); aBuf.appendAscii( "]" ); } else { aBuf.append( mHostName ); } // append port, but only, if not default port. bool bAppendPort = true; switch ( mPort ) { case DEFAULT_HTTP_PORT: bAppendPort = !mScheme.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "http" ) ); break; case DEFAULT_HTTPS_PORT: bAppendPort = !mScheme.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "https" ) ); break; case DEFAULT_FTP_PORT: bAppendPort = !mScheme.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ftp" ) ); break; } if ( bAppendPort ) { aBuf.appendAscii( ":" ); aBuf.append( rtl::OUString::valueOf( mPort ) ); } aBuf.append( mPath ); mURI = aBuf.makeStringAndClear(); } ::rtl::OUString NeonUri::GetPathBaseName () const { sal_Int32 nPos = mPath.lastIndexOf ('/'); sal_Int32 nTrail = 0; if (nPos == mPath.getLength () - 1) { // Trailing slash found. Skip. nTrail = 1; nPos = mPath.lastIndexOf ('/', nPos); } if (nPos != -1) { rtl::OUString aTemp( mPath.copy (nPos + 1, mPath.getLength () - nPos - 1 - nTrail) ); // query, fragment present? nPos = aTemp.indexOf( '?' ); if ( nPos == -1 ) nPos = aTemp.indexOf( '#' ); if ( nPos != -1 ) aTemp = aTemp.copy( 0, nPos ); return aTemp; } else return rtl::OUString::createFromAscii ("/"); } bool NeonUri::operator== ( const NeonUri & rOther ) const { return ( mURI == rOther.mURI ); } ::rtl::OUString NeonUri::GetPathBaseNameUnescaped () const { return unescape( GetPathBaseName() ); } ::rtl::OUString NeonUri::GetPathDirName () const { sal_Int32 nPos = mPath.lastIndexOf ('/'); if (nPos == mPath.getLength () - 1) { // Trailing slash found. Skip. nPos = mPath.lastIndexOf ('/', nPos); } if (nPos != -1) return mPath.copy (0, nPos + 1); else return rtl::OUString::createFromAscii ("/"); } void NeonUri::AppendPath (const rtl::OUString& rPath) { if (mPath.lastIndexOf ('/') != mPath.getLength () - 1) mPath += rtl::OUString::createFromAscii ("/"); mPath += rPath; calculateURI (); }; // static rtl::OUString NeonUri::escapeSegment( const rtl::OUString& segment ) { return rtl::Uri::encode( segment, rtl_UriCharClassPchar, rtl_UriEncodeIgnoreEscapes, RTL_TEXTENCODING_UTF8 ); } // static rtl::OUString NeonUri::unescape( const rtl::OUString& segment ) { return rtl::Uri::decode( segment, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 ); } // static rtl::OUString NeonUri::makeConnectionEndPointString( const rtl::OUString & rHostName, int nPort ) { rtl::OUStringBuffer aBuf; // Is host a numeric IPv6 address? if ( ( rHostName.indexOf( ':' ) != -1 ) && ( rHostName[ 0 ] != sal_Unicode( '[' ) ) ) { aBuf.appendAscii( "[" ); aBuf.append( rHostName ); aBuf.appendAscii( "]" ); } else { aBuf.append( rHostName ); } if ( ( nPort != DEFAULT_HTTP_PORT ) && ( nPort != DEFAULT_HTTPS_PORT ) ) { aBuf.appendAscii( ":" ); aBuf.append( rtl::OUString::valueOf( sal_Int32( nPort ) ) ); } return aBuf.makeStringAndClear(); } <commit_msg>INTEGRATION: CWS hr50 (1.23.4); FILE MERGED 2008/03/05 17:44:29 hr 1.23.4.1: #i86574#: fix warning (gcc-4.2.3)<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: NeonUri.cxx,v $ * $Revision: 1.25 $ * * 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_ucb.hxx" #include <string.h> #include <rtl/uri.hxx> #include <rtl/ustring.hxx> #include <rtl/ustrbuf.hxx> #include "NeonUri.hxx" #include "DAVException.hxx" #include "../inc/urihelper.hxx" using namespace webdav_ucp; char *scheme; char *host, *userinfo; unsigned int port; char *path, *query, *fragment; # if defined __SUNPRO_CC // FIXME: not sure whether initializing a ne_uri statically is supposed to work // the string fields of ne_uri are char*, not const char* # pragma disable_warn # endif #if defined __GNUC__ #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) /* Diagnostics pragma was introduced with gcc-4.2.1 */ #if GCC_VERSION > 40201 #pragma GCC diagnostic ignored "-Wwrite-strings" #endif #endif namespace { const ne_uri g_sUriDefaultsHTTP = { "http", #if NEON_VERSION >= 0x0260 NULL, #endif NULL, DEFAULT_HTTP_PORT, #if NEON_VERSION >= 0x0260 NULL, #endif NULL, NULL }; const ne_uri g_sUriDefaultsHTTPS = { "https", #if NEON_VERSION >= 0x0260 NULL, #endif NULL, DEFAULT_HTTPS_PORT, #if NEON_VERSION >= 0x0260 NULL, #endif NULL, NULL }; const ne_uri g_sUriDefaultsFTP = { "ftp", #if NEON_VERSION >= 0x0260 NULL, #endif NULL, DEFAULT_FTP_PORT, #if NEON_VERSION >= 0x0260 NULL, #endif NULL, NULL }; } // namespace # if defined __SUNPRO_CC # pragma enable_warn #endif // ------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------- namespace { //TODO! rtl::OString::matchIgnoreAsciiCaseAsciiL() missing inline bool matchIgnoreAsciiCase(rtl::OString const & rStr1, sal_Char const * pStr2, sal_Int32 nStr2Len) SAL_THROW(()) { return rtl_str_shortenedCompareIgnoreAsciiCase_WithLength( rStr1.getStr(), rStr1.getLength(), pStr2, nStr2Len, nStr2Len) == 0; } } NeonUri::NeonUri( const ne_uri * inUri ) throw ( DAVException ) { if ( inUri == 0 ) throw DAVException( DAVException::DAV_INVALID_ARG ); char * uri = ne_uri_unparse( inUri ); if ( uri == 0 ) throw DAVException( DAVException::DAV_INVALID_ARG ); init( rtl::OString( uri ), inUri ); free( uri ); calculateURI(); } NeonUri::NeonUri( const rtl::OUString & inUri ) throw ( DAVException ) { if ( inUri.getLength() <= 0 ) throw DAVException( DAVException::DAV_INVALID_ARG ); // #i77023# rtl::OUString aEscapedUri( ucb_impl::urihelper::encodeURI( inUri ) ); rtl::OString theInputUri( aEscapedUri.getStr(), aEscapedUri.getLength(), RTL_TEXTENCODING_UTF8 ); ne_uri theUri; if ( ne_uri_parse( theInputUri.getStr(), &theUri ) != 0 ) { ne_uri_free( &theUri ); throw DAVException( DAVException::DAV_INVALID_ARG ); } init( theInputUri, &theUri ); ne_uri_free( &theUri ); calculateURI(); } void NeonUri::init( const rtl::OString & rUri, const ne_uri * pUri ) { // Complete URI. const ne_uri * pUriDefs = matchIgnoreAsciiCase( rUri, RTL_CONSTASCII_STRINGPARAM( "ftp:" ) ) ? &g_sUriDefaultsFTP : matchIgnoreAsciiCase( rUri, RTL_CONSTASCII_STRINGPARAM( "https:" ) ) ? &g_sUriDefaultsHTTPS : &g_sUriDefaultsHTTP; mScheme = rtl::OStringToOUString( pUri->scheme ? pUri->scheme : pUriDefs->scheme, RTL_TEXTENCODING_UTF8 ); mUserInfo = rtl::OStringToOUString( #if NEON_VERSION >= 0x0260 pUri->userinfo ? pUri->userinfo : pUriDefs->userinfo, #else pUri->authinfo ? pUri->authinfo : pUriDefs->authinfo, #endif RTL_TEXTENCODING_UTF8 ); mHostName = rtl::OStringToOUString( pUri->host ? pUri->host : pUriDefs->host, RTL_TEXTENCODING_UTF8 ); mPort = pUri->port > 0 ? pUri->port : pUriDefs->port; mPath = rtl::OStringToOUString( pUri->path ? pUri->path : pUriDefs->path, RTL_TEXTENCODING_UTF8 ); #if NEON_VERSION >= 0x0260 if ( pUri->query ) { mPath += rtl::OUString::createFromAscii( "?" ); mPath += rtl::OStringToOUString( pUri->query, RTL_TEXTENCODING_UTF8 ); } if ( pUri->fragment ) { mPath += rtl::OUString::createFromAscii( "#" ); mPath += rtl::OStringToOUString( pUri->fragment, RTL_TEXTENCODING_UTF8 ); } #endif } // ------------------------------------------------------------------- // Destructor // ------------------------------------------------------------------- NeonUri::~NeonUri( ) { } void NeonUri::calculateURI () { rtl::OUStringBuffer aBuf( mScheme ); aBuf.appendAscii( "://" ); if ( mUserInfo.getLength() > 0 ) { //TODO! differentiate between empty and missing userinfo aBuf.append( mUserInfo ); aBuf.appendAscii( "@" ); } // Is host a numeric IPv6 address? if ( ( mHostName.indexOf( ':' ) != -1 ) && ( mHostName[ 0 ] != sal_Unicode( '[' ) ) ) { aBuf.appendAscii( "[" ); aBuf.append( mHostName ); aBuf.appendAscii( "]" ); } else { aBuf.append( mHostName ); } // append port, but only, if not default port. bool bAppendPort = true; switch ( mPort ) { case DEFAULT_HTTP_PORT: bAppendPort = !mScheme.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "http" ) ); break; case DEFAULT_HTTPS_PORT: bAppendPort = !mScheme.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "https" ) ); break; case DEFAULT_FTP_PORT: bAppendPort = !mScheme.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ftp" ) ); break; } if ( bAppendPort ) { aBuf.appendAscii( ":" ); aBuf.append( rtl::OUString::valueOf( mPort ) ); } aBuf.append( mPath ); mURI = aBuf.makeStringAndClear(); } ::rtl::OUString NeonUri::GetPathBaseName () const { sal_Int32 nPos = mPath.lastIndexOf ('/'); sal_Int32 nTrail = 0; if (nPos == mPath.getLength () - 1) { // Trailing slash found. Skip. nTrail = 1; nPos = mPath.lastIndexOf ('/', nPos); } if (nPos != -1) { rtl::OUString aTemp( mPath.copy (nPos + 1, mPath.getLength () - nPos - 1 - nTrail) ); // query, fragment present? nPos = aTemp.indexOf( '?' ); if ( nPos == -1 ) nPos = aTemp.indexOf( '#' ); if ( nPos != -1 ) aTemp = aTemp.copy( 0, nPos ); return aTemp; } else return rtl::OUString::createFromAscii ("/"); } bool NeonUri::operator== ( const NeonUri & rOther ) const { return ( mURI == rOther.mURI ); } ::rtl::OUString NeonUri::GetPathBaseNameUnescaped () const { return unescape( GetPathBaseName() ); } ::rtl::OUString NeonUri::GetPathDirName () const { sal_Int32 nPos = mPath.lastIndexOf ('/'); if (nPos == mPath.getLength () - 1) { // Trailing slash found. Skip. nPos = mPath.lastIndexOf ('/', nPos); } if (nPos != -1) return mPath.copy (0, nPos + 1); else return rtl::OUString::createFromAscii ("/"); } void NeonUri::AppendPath (const rtl::OUString& rPath) { if (mPath.lastIndexOf ('/') != mPath.getLength () - 1) mPath += rtl::OUString::createFromAscii ("/"); mPath += rPath; calculateURI (); }; // static rtl::OUString NeonUri::escapeSegment( const rtl::OUString& segment ) { return rtl::Uri::encode( segment, rtl_UriCharClassPchar, rtl_UriEncodeIgnoreEscapes, RTL_TEXTENCODING_UTF8 ); } // static rtl::OUString NeonUri::unescape( const rtl::OUString& segment ) { return rtl::Uri::decode( segment, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 ); } // static rtl::OUString NeonUri::makeConnectionEndPointString( const rtl::OUString & rHostName, int nPort ) { rtl::OUStringBuffer aBuf; // Is host a numeric IPv6 address? if ( ( rHostName.indexOf( ':' ) != -1 ) && ( rHostName[ 0 ] != sal_Unicode( '[' ) ) ) { aBuf.appendAscii( "[" ); aBuf.append( rHostName ); aBuf.appendAscii( "]" ); } else { aBuf.append( rHostName ); } if ( ( nPort != DEFAULT_HTTP_PORT ) && ( nPort != DEFAULT_HTTPS_PORT ) ) { aBuf.appendAscii( ":" ); aBuf.append( rtl::OUString::valueOf( sal_Int32( nPort ) ) ); } return aBuf.makeStringAndClear(); } <|endoftext|>
<commit_before>#pragma once #include <cstddef> #include <cstring> #include <limits> #include <vector> #include "queue.hpp" template<typename T> class DinicFlow { public: class Edge { public: Edge(const size_t from, const size_t to, const T capacity, const T flow) : from(from), to(to), cap(capacity), flow(flow) {} size_t from; size_t to; T cap; T flow; }; DinicFlow(const size_t n) : graph(n), queue(n), pointer(n), dist(n), used(n) {} void add_directed_edge(const size_t from, const size_t to, const T capacity) { return add_bidirectional_edge(from, to, capacity, 0); } void add_bidirectional_edge(size_t from, size_t to, T capacity, T backward_capacity) { push_edge(from, to, capacity, 0); push_edge(to, from, backward_capacity, 0); } Edge get_edge(const size_t id) const { return edges[id]; } static T weight_infinity() { return std::numeric_limits<T>::max() / 2; } T findFlow(const size_t from, const size_t to, const T infinity = weight_infinity()) { T flow = 0; while (bfs(from, to)) { pointer.assign(pointer.size(), 0); while (const T pushed = dfs(from, to, infinity)) { flow += pushed; } } return flow; } size_t edges_count() const { return edges.size(); } private: void push_edge(const size_t from, const size_t to, const T capacity, const T backwardCapacity) { graph[from].emplace_back(edges.size()); edges.emplace_back(from, to, capacity, 0); } bool bfs(const size_t from, const size_t to) { used.assign(used.size(), false); size_t qh = 0, qt = 0; queue.clear(); queue.push(from); used[from] = true; while (!queue.empty()) { const size_t vertex = queue.pop_front(); for (const size_t id : graph[vertex]) { Edge& edge = edges[id]; if (used[edge.to] || edge.cap == edge.flow) { continue; } used[edge.to] = true; dist[edge.to] = dist[vertex] + 1; queue.push(edge.to); } } return used[to]; } T dfs(const size_t vertex, const size_t to, const T mx) { if (mx == 0 || vertex == to) { return mx; } for (size_t& i = pointer[vertex]; i < graph[vertex].size(); ++i) { const size_t id = graph[vertex][i]; Edge& e = edges[id]; if (dist[e.to] == dist[vertex] + 1) { if (const T pushed = dfs(e.to, to, std::min(mx, e.cap - e.flow))) { e.flow += pushed; edges[id ^ 1].flow -= pushed; return pushed; } } } return 0; } std::vector<std::vector<size_t>> graph; std::vector<Edge> edges; Queue<size_t> queue; std::vector<size_t> pointer; std::vector<T> dist; std::vector<bool> used; };<commit_msg>Minor fixes in DinicFlow class.<commit_after>#pragma once #include <cstddef> #include <cstring> #include <limits> #include <vector> #include "queue.hpp" template<typename T> class DinicFlow { public: class Edge { public: Edge(const size_t from, const size_t to, const T capacity, const T flow) : from(from), to(to), cap(capacity), flow(flow) {} size_t from; size_t to; T cap; T flow; }; DinicFlow(const size_t n) : graph(n), queue(n), pointer(n), dist(n), used(n) {} void add_directed_edge(const size_t from, const size_t to, const T capacity) { return add_bidirectional_edge(from, to, capacity, 0); } void add_bidirectional_edge(size_t from, size_t to, T capacity, T backward_capacity) { push_edge(from, to, capacity, 0); push_edge(to, from, backward_capacity, 0); } Edge get_edge(const size_t id) const { return edges[id]; } static T weight_infinity() { return std::numeric_limits<T>::max() / 2; } T findFlow(const size_t from, const size_t to, const T infinity = weight_infinity()) { T flow = 0; while (bfs(from, to)) { pointer.assign(pointer.size(), 0); while (const T pushed = dfs(from, to, infinity)) { flow += pushed; } } return flow; } size_t edges_count() const { return edges.size(); } private: void push_edge(const size_t from, const size_t to, const T capacity, const T backwardCapacity) { graph[from].emplace_back(edges.size()); edges.emplace_back(from, to, capacity, 0); } bool bfs(const size_t from, const size_t to) { used.assign(used.size(), false); queue.clear(); queue.push(from); used[from] = true; while (!queue.empty()) { const size_t vertex = queue.pop_front(); for (const size_t id : graph[vertex]) { const Edge& edge = edges[id]; if (used[edge.to] || edge.cap == edge.flow) { continue; } used[edge.to] = true; dist[edge.to] = dist[vertex] + 1; queue.push(edge.to); } } return used[to]; } T dfs(const size_t vertex, const size_t to, const T mx) { if (mx == 0 || vertex == to) { return mx; } for (size_t& i = pointer[vertex]; i < graph[vertex].size(); ++i) { const size_t id = graph[vertex][i]; Edge& e = edges[id]; if (dist[e.to] == dist[vertex] + 1) { if (const T pushed = dfs(e.to, to, std::min(mx, e.cap - e.flow))) { e.flow += pushed; edges[id ^ 1].flow -= pushed; return pushed; } } } return 0; } std::vector<std::vector<size_t>> graph; std::vector<Edge> edges; Queue<size_t> queue; std::vector<size_t> pointer; std::vector<T> dist; std::vector<bool> used; }; <|endoftext|>
<commit_before>/** @file * * @ingroup dspLibrary * * @brief Container object that holds some audio in a chunk of memory. * * @see TTMatrix, TTAudioSignal * * @authors Timothy Place & Nathan Wolek * * @copyright Copyright © 2003-2012, Timothy Place & Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSampleMatrix.h" #define thisTTClass TTSampleMatrix #define thisTTClassName "samplematrix" #define thisTTClassTags "audio, buffer" TTObjectPtr TTSampleMatrix::instantiate(TTSymbol& name, TTValue& arguments) { return new TTSampleMatrix(arguments); } extern "C" void TTSampleMatrix::registerClass() { TTClassRegister(thisTTClassName, thisTTClassTags, TTSampleMatrix::instantiate); } TTSampleMatrix::TTSampleMatrix(TTValue& arguments) : TTMatrix(arguments), mSampleRate(44100.0) { this->setTypeWithoutResize(kTypeFloat64); this->setElementCountWithoutResize(1); this->resize(); addAttributeWithGetterAndSetter(NumChannels, kTypeUInt16); addAttributeWithGetterAndSetter(Length, kTypeFloat64); addAttributeWithGetterAndSetter(LengthInSamples, kTypeUInt64); addAttribute(SampleRate, kTypeFloat64); addMessage(normalize); addMessageWithArguments(fill); addMessageWithArguments(getValueAtIndex); registerMessage("peek", (TTMethod)&TTSampleMatrix::getValueAtIndex); registerMessage("peeki", (TTMethod)&TTSampleMatrix::getValueAtIndex); addMessageWithArguments(setValueAtIndex); registerMessage("poke", (TTMethod)&TTSampleMatrix::setValueAtIndex); // TODO: more messages to implement // "readFile" (requires libsndfile straightening-out) // "writeFile" (requires libsndfile straightening-out) // a way to query attributes: for example what is the sr and bpm of an AIFF file? } TTSampleMatrix::~TTSampleMatrix() { ; } TTErr TTSampleMatrix::setNumChannels(const TTValue& newNumChannels) { TTValue v(mLengthInSamples, TTUInt32(newNumChannels)); return setDimensions(v); } TTErr TTSampleMatrix::getNumChannels(TTValue& returnedChannelCount) { returnedChannelCount = mNumChannels; return kTTErrNone; } TTErr TTSampleMatrix::setLength(const TTValue& newLength) { TTValue newLengthInSamples = TTFloat64(newLength) * mSampleRate * 0.001; return setRowCount(newLengthInSamples); } TTErr TTSampleMatrix::getLength(TTValue& returnedLength) { returnedLength = (mLengthInSamples / mSampleRate) * 1000.0; return kTTErrNone; } TTErr TTSampleMatrix::setLengthInSamples(const TTValue& newLengthInSamples) { return setRowCount(newLengthInSamples); } TTErr TTSampleMatrix::getLengthInSamples(TTValue& returnedLengthInSamples) { returnedLengthInSamples = mLengthInSamples; return kTTErrNone; } TTErr TTSampleMatrix::getValueAtIndex(const TTValue& index, TTValue &output) { TTUInt32 sampleIndex; TTUInt16 sampleChannel = 0; TTSampleValue sampleValue; TTUInt8 i = 0; TTErr err; index.get(i++, sampleIndex); if (index.getSize() > 2) // TODO: sure would be nice to change the name of this method to "size" or something... index.get(i++, sampleChannel); err = peek(sampleIndex, sampleChannel, sampleValue); if (!err) output.set(i++, sampleValue); return err; } TTErr TTSampleMatrix::peek(TTRowID index, TTColumnID channel, TTSampleValue& value) { makeInBounds(index, channel); get2d(index, channel, value); return kTTErrNone; } // a first attempt at interpolation for the SampleMatrix. should be viewed as temporary. // needs to be fleshed out with different options... TTErr TTSampleMatrix::peeki(const TTFloat64 index, const TTUInt16 channel, TTSampleValue& value) { // variables needed TTUInt64 indexThisInteger = TTUInt64(index); TTUInt64 indexNextInteger = indexThisInteger + 1; TTFloat64 indexFractionalPart = index - indexThisInteger; TTSampleValue valueThisInteger, valueNextInteger; // TODO: perhaps we should range check the input here first... get2d(indexThisInteger, channel, valueThisInteger); get2d(indexNextInteger, channel, valueNextInteger); // simple linear interpolation adapted from TTDelay value = (valueNextInteger * (1.0 - indexFractionalPart)) + (valueThisInteger * indexFractionalPart); return kTTErrNone; } /** Set the sample value for a given index. The first number passed in the index parameter will be interpreted as the sample index. If there are three numbers passed, then the second number, if passed, will designate the channel index (defaults to zero). The final value will be used as the sample value that will be copied to the designated index. */ TTErr TTSampleMatrix::setValueAtIndex(const TTValue& index, TTValue& unusedOutput) { TTUInt32 sampleIndex; TTUInt16 sampleChannel = 0; TTSampleValue sampleValue; TTUInt8 i = 0; index.get(i++, sampleIndex); if (index.getSize() > 2) index.get(i++, sampleChannel); index.get(i++, sampleValue); return poke(sampleIndex, sampleChannel, sampleValue); } TTErr TTSampleMatrix::poke(const TTUInt64 index, const TTUInt16 channel, const TTSampleValue value) { // TODO: perhaps we should range check the input here first... set2d(index, channel, value); return kTTErrNone; } TTErr TTSampleMatrix::fill(const TTValue& value, TTValue& unusedOutput) { TTSymbol fillAlgorithm = value; if (fillAlgorithm == kTTSym_sine) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, sin(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0)))); } } else if (fillAlgorithm == kTTSym_sineMod) { // (modulator version: ranges from 0.0 to 1.0, rather than -1.0 to 1.0) for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, 0.5 + (0.5 * sin(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0))))); } } else if (fillAlgorithm == kTTSym_cosine) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, cos(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0)))); } } else if (fillAlgorithm == kTTSym_cosineMod) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, 0.5 + (0.5 * cos(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0))))); } } else if (fillAlgorithm == kTTSym_ramp) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, -1.0 + (2.0 * (float(i) / mLengthInSamples))); } } else if (fillAlgorithm == kTTSym_rampMod) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, float(i) / mLengthInSamples); } } else if (fillAlgorithm == kTTSym_sawtooth) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(mLengthInSamples-i, channel+1, -1.0 + (2.0 * (float(i) / mLengthInSamples))); } } else if (fillAlgorithm == kTTSym_sawtoothMod) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(mLengthInSamples-i, channel+1, float(i) / mLengthInSamples); } } else if (fillAlgorithm == kTTSym_triangle) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt32 i=0; i < mLengthInSamples/2; i++) { set2d(i+1, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples))); set2d(mLengthInSamples-i, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples))); } } } else if (fillAlgorithm == kTTSym_triangleMod) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt32 i=0; i < mLengthInSamples/2; i++) { set2d(i+1, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples))); set2d(mLengthInSamples-i, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples))); } } } return kTTErrNone; } TTErr TTSampleMatrix::normalize(const TTValue& aValue) { TTFloat64 normalizeTo = 1.0; TTRowID m = mLengthInSamples; // mFrameLength TTColumnID n = mNumChannels; // mNumChannels TTSampleValuePtr samples = (TTSampleValuePtr)getLockedPointer(); TTFloat64 peakValue = 0.0; TTFloat64 scalar; if (aValue.getSize() && TTFloat64(aValue) > 0.0) normalizeTo = aValue; for (int k=0; k<m*n; k++) { TTFloat64 magnitude = abs(samples[k]); if (magnitude > peakValue) peakValue = magnitude; } scalar = normalizeTo / peakValue; for (int k=0; k<m*n; k++) samples[k] *= scalar; releaseLockedPointer(); return kTTErrNone; } <commit_msg>SampleMatrix:setNumChannels() update<commit_after>/** @file * * @ingroup dspLibrary * * @brief Container object that holds some audio in a chunk of memory. * * @see TTMatrix, TTAudioSignal * * @authors Timothy Place & Nathan Wolek * * @copyright Copyright © 2003-2012, Timothy Place & Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSampleMatrix.h" #define thisTTClass TTSampleMatrix #define thisTTClassName "samplematrix" #define thisTTClassTags "audio, buffer" TTObjectPtr TTSampleMatrix::instantiate(TTSymbol& name, TTValue& arguments) { return new TTSampleMatrix(arguments); } extern "C" void TTSampleMatrix::registerClass() { TTClassRegister(thisTTClassName, thisTTClassTags, TTSampleMatrix::instantiate); } TTSampleMatrix::TTSampleMatrix(TTValue& arguments) : TTMatrix(arguments), mSampleRate(44100.0) { this->setTypeWithoutResize(kTypeFloat64); this->setElementCountWithoutResize(1); this->resize(); addAttributeWithGetterAndSetter(NumChannels, kTypeUInt16); addAttributeWithGetterAndSetter(Length, kTypeFloat64); addAttributeWithGetterAndSetter(LengthInSamples, kTypeUInt64); addAttribute(SampleRate, kTypeFloat64); addMessage(normalize); addMessageWithArguments(fill); addMessageWithArguments(getValueAtIndex); registerMessage("peek", (TTMethod)&TTSampleMatrix::getValueAtIndex); registerMessage("peeki", (TTMethod)&TTSampleMatrix::getValueAtIndex); addMessageWithArguments(setValueAtIndex); registerMessage("poke", (TTMethod)&TTSampleMatrix::setValueAtIndex); // TODO: more messages to implement // "readFile" (requires libsndfile straightening-out) // "writeFile" (requires libsndfile straightening-out) // a way to query attributes: for example what is the sr and bpm of an AIFF file? } TTSampleMatrix::~TTSampleMatrix() { ; } TTErr TTSampleMatrix::setNumChannels(const TTValue& newNumChannels) { return setColumnCount(newNumChannels); } TTErr TTSampleMatrix::getNumChannels(TTValue& returnedChannelCount) { returnedChannelCount = mNumChannels; return kTTErrNone; } TTErr TTSampleMatrix::setLength(const TTValue& newLength) { TTValue newLengthInSamples = TTFloat64(newLength) * mSampleRate * 0.001; return setRowCount(newLengthInSamples); } TTErr TTSampleMatrix::getLength(TTValue& returnedLength) { returnedLength = (mLengthInSamples / mSampleRate) * 1000.0; return kTTErrNone; } TTErr TTSampleMatrix::setLengthInSamples(const TTValue& newLengthInSamples) { return setRowCount(newLengthInSamples); } TTErr TTSampleMatrix::getLengthInSamples(TTValue& returnedLengthInSamples) { returnedLengthInSamples = mLengthInSamples; return kTTErrNone; } TTErr TTSampleMatrix::getValueAtIndex(const TTValue& index, TTValue &output) { TTUInt32 sampleIndex; TTUInt16 sampleChannel = 0; TTSampleValue sampleValue; TTUInt8 i = 0; TTErr err; index.get(i++, sampleIndex); if (index.getSize() > 2) // TODO: sure would be nice to change the name of this method to "size" or something... index.get(i++, sampleChannel); err = peek(sampleIndex, sampleChannel, sampleValue); if (!err) output.set(i++, sampleValue); return err; } TTErr TTSampleMatrix::peek(TTRowID index, TTColumnID channel, TTSampleValue& value) { makeInBounds(index, channel); get2d(index, channel, value); return kTTErrNone; } // a first attempt at interpolation for the SampleMatrix. should be viewed as temporary. // needs to be fleshed out with different options... TTErr TTSampleMatrix::peeki(const TTFloat64 index, const TTUInt16 channel, TTSampleValue& value) { // variables needed TTUInt64 indexThisInteger = TTUInt64(index); TTUInt64 indexNextInteger = indexThisInteger + 1; TTFloat64 indexFractionalPart = index - indexThisInteger; TTSampleValue valueThisInteger, valueNextInteger; // TODO: perhaps we should range check the input here first... get2d(indexThisInteger, channel, valueThisInteger); get2d(indexNextInteger, channel, valueNextInteger); // simple linear interpolation adapted from TTDelay value = (valueNextInteger * (1.0 - indexFractionalPart)) + (valueThisInteger * indexFractionalPart); return kTTErrNone; } /** Set the sample value for a given index. The first number passed in the index parameter will be interpreted as the sample index. If there are three numbers passed, then the second number, if passed, will designate the channel index (defaults to zero). The final value will be used as the sample value that will be copied to the designated index. */ TTErr TTSampleMatrix::setValueAtIndex(const TTValue& index, TTValue& unusedOutput) { TTUInt32 sampleIndex; TTUInt16 sampleChannel = 0; TTSampleValue sampleValue; TTUInt8 i = 0; index.get(i++, sampleIndex); if (index.getSize() > 2) index.get(i++, sampleChannel); index.get(i++, sampleValue); return poke(sampleIndex, sampleChannel, sampleValue); } TTErr TTSampleMatrix::poke(const TTUInt64 index, const TTUInt16 channel, const TTSampleValue value) { // TODO: perhaps we should range check the input here first... set2d(index, channel, value); return kTTErrNone; } TTErr TTSampleMatrix::fill(const TTValue& value, TTValue& unusedOutput) { TTSymbol fillAlgorithm = value; if (fillAlgorithm == kTTSym_sine) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, sin(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0)))); } } else if (fillAlgorithm == kTTSym_sineMod) { // (modulator version: ranges from 0.0 to 1.0, rather than -1.0 to 1.0) for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, 0.5 + (0.5 * sin(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0))))); } } else if (fillAlgorithm == kTTSym_cosine) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, cos(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0)))); } } else if (fillAlgorithm == kTTSym_cosineMod) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, 0.5 + (0.5 * cos(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0))))); } } else if (fillAlgorithm == kTTSym_ramp) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, -1.0 + (2.0 * (float(i) / mLengthInSamples))); } } else if (fillAlgorithm == kTTSym_rampMod) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(i+1, channel+1, float(i) / mLengthInSamples); } } else if (fillAlgorithm == kTTSym_sawtooth) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(mLengthInSamples-i, channel+1, -1.0 + (2.0 * (float(i) / mLengthInSamples))); } } else if (fillAlgorithm == kTTSym_sawtoothMod) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt64 i=0; i<mLengthInSamples; i++) set2d(mLengthInSamples-i, channel+1, float(i) / mLengthInSamples); } } else if (fillAlgorithm == kTTSym_triangle) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt32 i=0; i < mLengthInSamples/2; i++) { set2d(i+1, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples))); set2d(mLengthInSamples-i, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples))); } } } else if (fillAlgorithm == kTTSym_triangleMod) { for (TTUInt16 channel=0; channel<mNumChannels; channel++) { for (TTUInt32 i=0; i < mLengthInSamples/2; i++) { set2d(i+1, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples))); set2d(mLengthInSamples-i, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples))); } } } return kTTErrNone; } TTErr TTSampleMatrix::normalize(const TTValue& aValue) { TTFloat64 normalizeTo = 1.0; TTRowID m = mLengthInSamples; // mFrameLength TTColumnID n = mNumChannels; // mNumChannels TTSampleValuePtr samples = (TTSampleValuePtr)getLockedPointer(); TTFloat64 peakValue = 0.0; TTFloat64 scalar; if (aValue.getSize() && TTFloat64(aValue) > 0.0) normalizeTo = aValue; for (int k=0; k<m*n; k++) { TTFloat64 magnitude = abs(samples[k]); if (magnitude > peakValue) peakValue = magnitude; } scalar = normalizeTo / peakValue; for (int k=0; k<m*n; k++) samples[k] *= scalar; releaseLockedPointer(); return kTTErrNone; } <|endoftext|>
<commit_before>#include "interative_base.hpp" TEST_F(InteractiveTest, ctrlc1) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); std::string str = "throw 34"; str += CTRL_C; this->send(str.c_str()); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "throw 34\n" + PROMPT)); this->send(CTRL_D); ASSERT_NO_FATAL_FAILURE(this->waitAndExpect(0, WaitStatus::EXITED, "\n")); } TEST_F(InteractiveTest, ctrlc2) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("cat"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "cat\n")); sleep(1); this->send(CTRL_C); std::string err = strsignal(SIGINT); err += "\n"; if (platform::platform() == platform::PlatformType::CYGWIN) { ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT, err)); } else { ASSERT_NO_FATAL_FAILURE(this->expect("^C%\n" + PROMPT, err)); } ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 128 + SIGINT)); } TEST_F(InteractiveTest, ctrlc3) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("cat < /dev/zero > /dev/null"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "cat < /dev/zero > /dev/null\n")); sleep(1); this->send(CTRL_C); std::string err = strsignal(SIGINT); err += "\n"; if (platform::platform() == platform::PlatformType::CYGWIN) { ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT, err)); } else { ASSERT_NO_FATAL_FAILURE(this->expect("^C%\n" + PROMPT, err)); } ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 128 + SIGINT)); } TEST_F(InteractiveTest, ctrlc4) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("read"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "read\n")); sleep(1); this->send(CTRL_C); std::string err = format(R"(ydsh: read: 0: %s [runtime error] SystemError: %s from (builtin):8 'function _DEF_SIGINT()' from (stdin):1 '<toplevel>()' )", strerror(EINTR), strsignal(SIGINT)); if (platform::platform() == platform::PlatformType::CYGWIN) { ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT, err)); } else { ASSERT_NO_FATAL_FAILURE(this->expect("^C%\n" + PROMPT, err)); } ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 1)); } TEST_F(InteractiveTest, ctrlc5) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("read | grep hoge"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "read | grep hoge\n")); sleep(1); this->send(CTRL_C); std::string err = strsignal(SIGINT); err += "\n"; if (platform::platform() == platform::PlatformType::CYGWIN) { ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT, err)); } else { ASSERT_NO_FATAL_FAILURE(this->expect("^C%\n" + PROMPT, err)); } ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 128 + SIGINT)); } TEST_F(InteractiveTest, expand_ctrlc1) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("echo " "{/*/../*/../*/../*/../*/../*/../*/../*/../*,/*/../*/../*/../*/../*/../*/../*/../" "*/../*,/*/../*/../*/../*/../*/../*/../*/../*/../*}"); ASSERT_NO_FATAL_FAILURE( this->expect(PROMPT + "echo " "{/*/../*/../*/../*/../*/../*/../*/../*/../*,/*/../*/../*/../*/../*/../" "*/../*/../*/../*,/*/../*/../*/../*/../*/../*/../*/../*/../*}\n")); sleep(1); this->send(CTRL_C); std::string err = format(R"([runtime error] SystemError: glob expansion is canceled, caused by `%s' from (stdin):1 '<toplevel>()' )", strerror(EINTR)); if (platform::platform() == platform::PlatformType::CYGWIN) { ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT, err)); } else { ASSERT_NO_FATAL_FAILURE(this->expect("^C%\n" + PROMPT, err)); } ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 1)); } TEST_F(InteractiveTest, expand_ctrlc2) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("echo {1..9999999999}"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "echo {1..9999999999}\n")); this->send(CTRL_C); std::string err = format(R"([runtime error] SystemError: brace expansion is canceled, caused by `%s' from (stdin):1 '<toplevel>()' )", strerror(EINTR)); if (platform::platform() == platform::PlatformType::CYGWIN) { ASSERT_NO_FATAL_FAILURE(this->withTimeout(400, [&] { this->expect(PROMPT, err); })); } else { ASSERT_NO_FATAL_FAILURE(this->withTimeout(400, [&] { this->expect("^C%\n" + PROMPT, err); })); } ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 1)); } TEST_F(InteractiveTest, wait_ctrlc1) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndExpect("var j = while(true){} &")); this->sendLine("$j.wait()"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "$j.wait()\n")); sleep(1); this->send(CTRL_C); std::string err = format(R"([runtime error] SystemError: wait failed, caused by `%s' from (stdin):2 '<toplevel>()' )", strerror(EINTR)); if (platform::platform() == platform::PlatformType::CYGWIN) { ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT, err)); } else { ASSERT_NO_FATAL_FAILURE(this->expect("^C%\n" + PROMPT, err)); } ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 1)); } TEST_F(InteractiveTest, wait_ctrlc2) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndExpect("while(true){} &", ": Job = %1")); this->sendLine("fg"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "fg\n")); sleep(1); this->send(CTRL_C); std::string err = strsignal(SIGINT); err += "\n"; if (platform::platform() == platform::PlatformType::CYGWIN) { ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT, err)); } else { ASSERT_NO_FATAL_FAILURE(this->expect("^C%\n" + PROMPT, err)); } ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 128 + SIGINT)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<commit_msg>cleanup interactive test cases<commit_after>#include "interative_base.hpp" TEST_F(InteractiveTest, ctrlc1) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); std::string str = "throw 34"; str += CTRL_C; this->send(str.c_str()); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "throw 34\n" + PROMPT)); this->send(CTRL_D); ASSERT_NO_FATAL_FAILURE(this->waitAndExpect(0, WaitStatus::EXITED, "\n")); } static std::string promptAfterCtrlC(const std::string &prompt) { std::string value; if (platform::platform() != platform::PlatformType::CYGWIN) { value += "^C%\n"; } value += prompt; return value; } TEST_F(InteractiveTest, ctrlc2) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("cat"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "cat\n")); sleep(1); this->send(CTRL_C); std::string err = strsignal(SIGINT); err += "\n"; ASSERT_NO_FATAL_FAILURE(this->expect(promptAfterCtrlC(PROMPT), err)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 128 + SIGINT)); } TEST_F(InteractiveTest, ctrlc3) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("cat < /dev/zero > /dev/null"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "cat < /dev/zero > /dev/null\n")); sleep(1); this->send(CTRL_C); std::string err = strsignal(SIGINT); err += "\n"; ASSERT_NO_FATAL_FAILURE(this->expect(promptAfterCtrlC(PROMPT), err)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 128 + SIGINT)); } TEST_F(InteractiveTest, ctrlc4) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("read"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "read\n")); sleep(1); this->send(CTRL_C); std::string err = format(R"(ydsh: read: 0: %s [runtime error] SystemError: %s from (builtin):8 'function _DEF_SIGINT()' from (stdin):1 '<toplevel>()' )", strerror(EINTR), strsignal(SIGINT)); ASSERT_NO_FATAL_FAILURE(this->expect(promptAfterCtrlC(PROMPT), err)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 1)); } TEST_F(InteractiveTest, ctrlc5) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("read | grep hoge"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "read | grep hoge\n")); sleep(1); this->send(CTRL_C); std::string err = strsignal(SIGINT); err += "\n"; ASSERT_NO_FATAL_FAILURE(this->expect(promptAfterCtrlC(PROMPT), err)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 128 + SIGINT)); } TEST_F(InteractiveTest, expand_ctrlc1) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("echo " "{/*/../*/../*/../*/../*/../*/../*/../*/../*,/*/../*/../*/../*/../*/../*/../*/../" "*/../*,/*/../*/../*/../*/../*/../*/../*/../*/../*}"); ASSERT_NO_FATAL_FAILURE( this->expect(PROMPT + "echo " "{/*/../*/../*/../*/../*/../*/../*/../*/../*,/*/../*/../*/../*/../*/../" "*/../*/../*/../*,/*/../*/../*/../*/../*/../*/../*/../*/../*}\n")); sleep(1); this->send(CTRL_C); std::string err = format(R"([runtime error] SystemError: glob expansion is canceled, caused by `%s' from (stdin):1 '<toplevel>()' )", strerror(EINTR)); ASSERT_NO_FATAL_FAILURE(this->expect(promptAfterCtrlC(PROMPT), err)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 1)); } TEST_F(InteractiveTest, expand_ctrlc2) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); this->sendLine("echo {1..9999999999}"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "echo {1..9999999999}\n")); this->send(CTRL_C); std::string err = format(R"([runtime error] SystemError: brace expansion is canceled, caused by `%s' from (stdin):1 '<toplevel>()' )", strerror(EINTR)); ASSERT_NO_FATAL_FAILURE(this->expect(promptAfterCtrlC(PROMPT), err)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 1)); } TEST_F(InteractiveTest, wait_ctrlc1) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndExpect("var j = while(true){} &")); this->sendLine("$j.wait()"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "$j.wait()\n")); sleep(1); this->send(CTRL_C); std::string err = format(R"([runtime error] SystemError: wait failed, caused by `%s' from (stdin):2 '<toplevel>()' )", strerror(EINTR)); ASSERT_NO_FATAL_FAILURE(this->expect(promptAfterCtrlC(PROMPT), err)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 1)); } TEST_F(InteractiveTest, wait_ctrlc2) { this->invoke("--quiet", "--norc"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndExpect("while(true){} &", ": Job = %1")); this->sendLine("fg"); ASSERT_NO_FATAL_FAILURE(this->expect(PROMPT + "fg\n")); sleep(1); this->send(CTRL_C); std::string err = strsignal(SIGINT); err += "\n"; ASSERT_NO_FATAL_FAILURE(this->expect(promptAfterCtrlC(PROMPT), err)); ASSERT_NO_FATAL_FAILURE(this->sendLineAndWait("exit", 128 + SIGINT)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2016 Colin Hill // // 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 "Engine.h" #include "Hect/Core/Configuration.h" #include "Hect/Graphics/Renderer.h" #include "Hect/IO/DataValueDecoder.h" #include "Hect/Runtime/Platform.h" #include "Hect/Scene/Component.h" #include "Hect/Scene/ComponentRegistry.h" #include "Hect/Scene/Scene.h" #include "Hect/Scene/SceneRegistry.h" #include "Hect/Timing/Timer.h" #include "Hect/Timing/TimeSpan.h" #include "Hect/Generated/RegisterTypes.h" #include <fstream> #include <streambuf> #include <tclap/CmdLine.h> #include <unordered_map> #ifdef HECT_USE_VLD #include <vld.h> #endif using namespace hect; namespace { static Engine* _instance = nullptr; } Engine& Engine::instance() { if (!_instance) { throw InvalidOperation("An engine instance has not been instantiated"); } return *_instance; } void Engine::preInitialize() { } void Engine::postUninitialize() { } Engine::Engine(int argc, char* const argv[]) { if (_instance) { throw InvalidOperation("An engine instance has already been instantiated"); } _instance = this; // Parse command line arguments CommandLineArguments arguments = parseCommandLineArgument(argc, argv); // Load the settings specified on the command-line if (!arguments.settingsFilePath.empty()) { _settings = loadConfig(arguments.settingsFilePath); } setConfiguredLogLevels(); // Register all of the Hect types registerTypes(); // Ignore false positive memory leaks from static variables #ifdef HECT_USE_VLD VLDMarkAllLeaksAsReported(); #endif // Create file system _fileSystem.reset(new FileSystem(argc, argv)); _fileSystem->setWriteDirectory(_fileSystem->baseDirectory()); // Create platform _platform.reset(new Platform()); // Mount the archives specified in the settings for (const DataValue& archive : _settings["archives"]) { if (!archive["path"].isNull()) { _fileSystem->mountArchive(archive["path"].asString(), archive["mountPoint"].asString()); } } // Create the task pool size_t threadCount = _settings["taskPool"]["threadCount"].orDefault(2).asInt(); _taskPool.reset(new TaskPool(threadCount)); // Create the asset cache bool concurrent = _settings["assetCache"]["concurrent"].orDefault(false).asBool(); _assetCache.reset(new AssetCache(*_fileSystem, concurrent)); const DataValue& videoModeValue = _settings["videoMode"]; if (!videoModeValue.isNull()) { // Load video mode VideoMode videoMode; try { DataValueDecoder decoder(videoModeValue); decoder >> decodeValue(videoMode); } catch (const DecodeError& error) { HECT_ERROR(format("Invalid video mode: %s", error.what())); } // Create window and renderers _window.reset(new Window("Hect", videoMode)); _renderer.reset(new Renderer()); _vectorRenderer.reset(new VectorRenderer(*_renderer)); } } Engine::~Engine() { _instance = nullptr; } int Engine::main() { const DataValue& sceneValue = _settings["scene"]; if (sceneValue.isNull()) { HECT_ERROR("No scene specified in settings"); } else { const Path scenePath = sceneValue.asString(); // Peek at the scene type to be able to create the scene object of the // correct type SceneTypeId typeId; { AssetDecoder decoder(assetCache(), scenePath); if (decoder.isBinaryStream()) { decoder >> decodeValue("sceneType", typeId); } else { Name typeName; decoder >> decodeValue("sceneType", typeName); typeId = SceneRegistry::typeIdOf(typeName); } } // Create the scene auto scene = SceneRegistry::create(typeId); // Decode the scene AssetDecoder decoder(assetCache(), scenePath); scene->decode(decoder); playScene(*scene); } return 0; } void Engine::playScene(Scene& scene) { Timer timer; TimeSpan accumulator; TimeSpan delta; TimeSpan timeStep = TimeSpan::fromSeconds(1.0 / 60.0); double timeStepSeconds = timeStep.seconds(); int64_t timeStepMicroseconds = timeStep.microseconds(); while (_platform->handleEvents() && scene.active()) { TimeSpan deltaTime = timer.elapsed(); timer.reset(); accumulator += deltaTime; delta += deltaTime; while (scene.active() && accumulator.microseconds() >= timeStepMicroseconds) { scene.tick(timeStepSeconds); delta = TimeSpan(); accumulator -= timeStep; } scene.render(*_window); _window->swapBuffers(); } } bool Engine::hasMouse() { assert(_platform); return _platform->hasMouse(); } Mouse& Engine::mouse() { assert(_platform); return _platform->mouse(); } bool Engine::hasKeyboard() { assert(_platform); return _platform->hasKeyboard(); } Keyboard& Engine::keyboard() { assert(_platform); return _platform->keyboard(); } bool Engine::hasJoystick(JoystickIndex index) { assert(_platform); return _platform->hasJoystick(index); } Joystick& Engine::joystick(JoystickIndex index) { assert(_platform); return _platform->joystick(index); } FileSystem& Engine::fileSystem() { assert(_fileSystem); return *_fileSystem; } Window& Engine::window() { if (!_window) { throw InvalidOperation("No available window"); } return *_window; } Renderer& Engine::renderer() { assert(_renderer); return *_renderer; } VectorRenderer& Engine::vectorRenderer() { assert(_vectorRenderer); return *_vectorRenderer; } TaskPool& Engine::taskPool() { assert(_taskPool); return *_taskPool; } AssetCache& Engine::assetCache() { assert(_assetCache); return *_assetCache; } const DataValue& Engine::settings() { return _settings; } DataValue Engine::loadConfig(const Path& settingsFilePath) { try { // Read the file to a YAML string std::string yaml; { std::ifstream stream(settingsFilePath.asString().data()); yaml.assign(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()); } DataValue settings; settings.decodeFromYaml(yaml); // Load additional settings files std::vector<DataValue> includedConfigs; for (const DataValue& settingsFilePath : settings["include"]) { DataValue settings = loadConfig(settingsFilePath.asString()); includedConfigs.push_back(std::move(settings)); } // Merge additional settingss back to the main settings for (const DataValue& includedConfig : includedConfigs) { for (std::string& memberName : includedConfig.memberNames()) { settings.addMember(memberName, includedConfig[memberName]); } } return settings; } catch (const std::exception& exception) { throw FatalError(format("Failed to load settings file '%s': %s", settingsFilePath.asString().data(), exception.what())); } } void Engine::setConfiguredLogLevels() { std::unordered_map<std::string, LogLevel> stringToLogLevel; stringToLogLevel["Info"] = LogLevel::Info; stringToLogLevel["Debug"] = LogLevel::Debug; stringToLogLevel["Warning"] = LogLevel::Warning; stringToLogLevel["Error"] = LogLevel::Error; stringToLogLevel["Trace"] = LogLevel::Trace; const DataValue& levels = _settings["logging"]["levels"]; if (!levels.isNull()) { for (const DataValue& level : levels) { if (level.isString()) { const std::string& levelString = level.asString(); auto it = stringToLogLevel.find(levelString); if (it != stringToLogLevel.end()) { LogLevel logLevel = it->second; setLogLevelEnabled(logLevel, true); } } } } } Engine::CommandLineArguments Engine::parseCommandLineArgument(int argc, char* const argv[]) { std::vector<std::string> argumentStrings { argv[0] }; // If there is only one argument given then assume it is a settings file path if (argc == 2) { argumentStrings.push_back("--settings"); } // Add the remaining arguments for (int i = 1; i < argc; ++i) { argumentStrings.push_back(argv[i]); } try { TCLAP::CmdLine cmd("Hect Engine"); TCLAP::ValueArg<std::string> settingsArg { "s", "settings", "A settings file load", false, "", "string" }; cmd.add(settingsArg); cmd.parse(argumentStrings); CommandLineArguments arguments; arguments.settingsFilePath = settingsArg.getValue(); return arguments; } catch (const std::exception& exception) { throw FatalError(exception.what()); } } <commit_msg>Make Engine perform a single tick before entering the main loop<commit_after>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2016 Colin Hill // // 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 "Engine.h" #include "Hect/Core/Configuration.h" #include "Hect/Graphics/Renderer.h" #include "Hect/IO/DataValueDecoder.h" #include "Hect/Runtime/Platform.h" #include "Hect/Scene/Component.h" #include "Hect/Scene/ComponentRegistry.h" #include "Hect/Scene/Scene.h" #include "Hect/Scene/SceneRegistry.h" #include "Hect/Timing/Timer.h" #include "Hect/Timing/TimeSpan.h" #include "Hect/Generated/RegisterTypes.h" #include <fstream> #include <streambuf> #include <tclap/CmdLine.h> #include <unordered_map> #ifdef HECT_USE_VLD #include <vld.h> #endif using namespace hect; namespace { static Engine* _instance = nullptr; } Engine& Engine::instance() { if (!_instance) { throw InvalidOperation("An engine instance has not been instantiated"); } return *_instance; } void Engine::preInitialize() { } void Engine::postUninitialize() { } Engine::Engine(int argc, char* const argv[]) { if (_instance) { throw InvalidOperation("An engine instance has already been instantiated"); } _instance = this; // Parse command line arguments CommandLineArguments arguments = parseCommandLineArgument(argc, argv); // Load the settings specified on the command-line if (!arguments.settingsFilePath.empty()) { _settings = loadConfig(arguments.settingsFilePath); } setConfiguredLogLevels(); // Register all of the Hect types registerTypes(); // Ignore false positive memory leaks from static variables #ifdef HECT_USE_VLD VLDMarkAllLeaksAsReported(); #endif // Create file system _fileSystem.reset(new FileSystem(argc, argv)); _fileSystem->setWriteDirectory(_fileSystem->baseDirectory()); // Create platform _platform.reset(new Platform()); // Mount the archives specified in the settings for (const DataValue& archive : _settings["archives"]) { if (!archive["path"].isNull()) { _fileSystem->mountArchive(archive["path"].asString(), archive["mountPoint"].asString()); } } // Create the task pool size_t threadCount = _settings["taskPool"]["threadCount"].orDefault(2).asInt(); _taskPool.reset(new TaskPool(threadCount)); // Create the asset cache bool concurrent = _settings["assetCache"]["concurrent"].orDefault(false).asBool(); _assetCache.reset(new AssetCache(*_fileSystem, concurrent)); const DataValue& videoModeValue = _settings["videoMode"]; if (!videoModeValue.isNull()) { // Load video mode VideoMode videoMode; try { DataValueDecoder decoder(videoModeValue); decoder >> decodeValue(videoMode); } catch (const DecodeError& error) { HECT_ERROR(format("Invalid video mode: %s", error.what())); } // Create window and renderers _window.reset(new Window("Hect", videoMode)); _renderer.reset(new Renderer()); _vectorRenderer.reset(new VectorRenderer(*_renderer)); } } Engine::~Engine() { _instance = nullptr; } int Engine::main() { const DataValue& sceneValue = _settings["scene"]; if (sceneValue.isNull()) { HECT_ERROR("No scene specified in settings"); } else { const Path scenePath = sceneValue.asString(); // Peek at the scene type to be able to create the scene object of the // correct type SceneTypeId typeId; { AssetDecoder decoder(assetCache(), scenePath); if (decoder.isBinaryStream()) { decoder >> decodeValue("sceneType", typeId); } else { Name typeName; decoder >> decodeValue("sceneType", typeName); typeId = SceneRegistry::typeIdOf(typeName); } } // Create the scene auto scene = SceneRegistry::create(typeId); // Decode the scene AssetDecoder decoder(assetCache(), scenePath); scene->decode(decoder); playScene(*scene); } return 0; } void Engine::playScene(Scene& scene) { Timer timer; TimeSpan accumulator; TimeSpan delta; TimeSpan timeStep = TimeSpan::fromSeconds(1.0 / 60.0); double timeStepSeconds = timeStep.seconds(); int64_t timeStepMicroseconds = timeStep.microseconds(); // Perform one initial tick before entering the main loop scene.tick(timeStepSeconds); while (_platform->handleEvents() && scene.active()) { TimeSpan deltaTime = timer.elapsed(); timer.reset(); accumulator += deltaTime; delta += deltaTime; while (scene.active() && accumulator.microseconds() >= timeStepMicroseconds) { scene.tick(timeStepSeconds); delta = TimeSpan(); accumulator -= timeStep; } scene.render(*_window); _window->swapBuffers(); } } bool Engine::hasMouse() { assert(_platform); return _platform->hasMouse(); } Mouse& Engine::mouse() { assert(_platform); return _platform->mouse(); } bool Engine::hasKeyboard() { assert(_platform); return _platform->hasKeyboard(); } Keyboard& Engine::keyboard() { assert(_platform); return _platform->keyboard(); } bool Engine::hasJoystick(JoystickIndex index) { assert(_platform); return _platform->hasJoystick(index); } Joystick& Engine::joystick(JoystickIndex index) { assert(_platform); return _platform->joystick(index); } FileSystem& Engine::fileSystem() { assert(_fileSystem); return *_fileSystem; } Window& Engine::window() { if (!_window) { throw InvalidOperation("No available window"); } return *_window; } Renderer& Engine::renderer() { assert(_renderer); return *_renderer; } VectorRenderer& Engine::vectorRenderer() { assert(_vectorRenderer); return *_vectorRenderer; } TaskPool& Engine::taskPool() { assert(_taskPool); return *_taskPool; } AssetCache& Engine::assetCache() { assert(_assetCache); return *_assetCache; } const DataValue& Engine::settings() { return _settings; } DataValue Engine::loadConfig(const Path& settingsFilePath) { try { // Read the file to a YAML string std::string yaml; { std::ifstream stream(settingsFilePath.asString().data()); yaml.assign(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()); } DataValue settings; settings.decodeFromYaml(yaml); // Load additional settings files std::vector<DataValue> includedConfigs; for (const DataValue& settingsFilePath : settings["include"]) { DataValue settings = loadConfig(settingsFilePath.asString()); includedConfigs.push_back(std::move(settings)); } // Merge additional settingss back to the main settings for (const DataValue& includedConfig : includedConfigs) { for (std::string& memberName : includedConfig.memberNames()) { settings.addMember(memberName, includedConfig[memberName]); } } return settings; } catch (const std::exception& exception) { throw FatalError(format("Failed to load settings file '%s': %s", settingsFilePath.asString().data(), exception.what())); } } void Engine::setConfiguredLogLevels() { std::unordered_map<std::string, LogLevel> stringToLogLevel; stringToLogLevel["Info"] = LogLevel::Info; stringToLogLevel["Debug"] = LogLevel::Debug; stringToLogLevel["Warning"] = LogLevel::Warning; stringToLogLevel["Error"] = LogLevel::Error; stringToLogLevel["Trace"] = LogLevel::Trace; const DataValue& levels = _settings["logging"]["levels"]; if (!levels.isNull()) { for (const DataValue& level : levels) { if (level.isString()) { const std::string& levelString = level.asString(); auto it = stringToLogLevel.find(levelString); if (it != stringToLogLevel.end()) { LogLevel logLevel = it->second; setLogLevelEnabled(logLevel, true); } } } } } Engine::CommandLineArguments Engine::parseCommandLineArgument(int argc, char* const argv[]) { std::vector<std::string> argumentStrings { argv[0] }; // If there is only one argument given then assume it is a settings file path if (argc == 2) { argumentStrings.push_back("--settings"); } // Add the remaining arguments for (int i = 1; i < argc; ++i) { argumentStrings.push_back(argv[i]); } try { TCLAP::CmdLine cmd("Hect Engine"); TCLAP::ValueArg<std::string> settingsArg { "s", "settings", "A settings file load", false, "", "string" }; cmd.add(settingsArg); cmd.parse(argumentStrings); CommandLineArguments arguments; arguments.settingsFilePath = settingsArg.getValue(); return arguments; } catch (const std::exception& exception) { throw FatalError(exception.what()); } } <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2018 Roman Lebedev 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 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; withexpected 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 "common/Spline.h" // for Spline #include <gtest/gtest.h> // for AssertionResult, DeathTest, Test, AssertHe... using rawspeed::Spline; namespace rawspeed_test { #ifndef NDEBUG TEST(SplineDeathTest, AtLeastTwoPoints) { ASSERT_DEATH({ Spline<>::calculateCurve({}); }, "at least two points"); ASSERT_DEATH({ Spline<>::calculateCurve({{0, {}}}); }, "at least two points"); ASSERT_EXIT( { Spline<>::calculateCurve({{0, {}}, {65535, {}}}); exit(0); }, ::testing::ExitedWithCode(0), ""); } TEST(SplineDeathTest, XIsFullRange) { ASSERT_DEATH( { Spline<>::calculateCurve({{1, {}}, {65535, {}}}); }, "front.*0"); ASSERT_DEATH( { Spline<>::calculateCurve({{0, {}}, {65534, {}}}); }, "back.*65535"); } TEST(SplineDeathTest, YIsLimited) { ASSERT_DEATH( { Spline<>::calculateCurve({{0, {}}, {32767, -1}, {65535, {}}}); }, "y >= .*min"); ASSERT_DEATH( { Spline<>::calculateCurve({{0, {}}, {32767, 65536}, {65535, {}}}); }, "y <= .*max"); } TEST(SplineDeathTest, XIsStrictlyIncreasing) { ASSERT_DEATH( { Spline<>::calculateCurve({{0, {}}, {0, {}}, {65535, {}}}); }, "strictly increasing"); ASSERT_DEATH( { Spline<>::calculateCurve( {{0, {}}, {32767, {}}, {32767, {}}, {65535, {}}}); }, "strictly increasing"); ASSERT_DEATH( { Spline<>::calculateCurve({{0, {}}, {65535, {}}, {65535, {}}}); }, "strictly increasing"); ASSERT_DEATH( { Spline<>::calculateCurve( {{0, {}}, {32767, {}}, {32766, {}}, {65535, {}}}); }, "strictly increasing"); } #endif TEST(SplineTest, IntegerIdentityTest) { const auto s = Spline<>::calculateCurve({{0, 0}, {65535, 65535}}); ASSERT_FALSE(s.empty()); ASSERT_EQ(s.size(), 65536); for (auto x = 0U; x < s.size(); ++x) ASSERT_EQ(s[x], x); } TEST(SplineTest, IntegerReverseIdentityTest) { const auto s = Spline<>::calculateCurve({{0, 65535}, {65535, 0}}); ASSERT_FALSE(s.empty()); ASSERT_EQ(s.size(), 65536); for (auto x = 0U; x < s.size(); ++x) { ASSERT_EQ(s[x], 65535 - x) << " Where x is: " << x; } } } // namespace rawspeed_test <commit_msg>SplineTest: dumb [reverse] identity test for doubles<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2018 Roman Lebedev 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 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; withexpected 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 "common/Spline.h" // for Spline #include <gtest/gtest.h> // for AssertionResult, DeathTest, Test, AssertHe... #include <type_traits> // for is_same using rawspeed::Spline; namespace rawspeed_test { TEST(SplineStaticTest, DefaultIsUshort16) { static_assert(std::is_same<Spline<>::value_type, rawspeed::ushort16>::value, "wrong default type"); } #ifndef NDEBUG TEST(SplineDeathTest, AtLeastTwoPoints) { ASSERT_DEATH({ Spline<>::calculateCurve({}); }, "at least two points"); ASSERT_DEATH({ Spline<>::calculateCurve({{0, {}}}); }, "at least two points"); ASSERT_EXIT( { Spline<>::calculateCurve({{0, {}}, {65535, {}}}); exit(0); }, ::testing::ExitedWithCode(0), ""); } TEST(SplineDeathTest, XIsFullRange) { ASSERT_DEATH( { Spline<>::calculateCurve({{1, {}}, {65535, {}}}); }, "front.*0"); ASSERT_DEATH( { Spline<>::calculateCurve({{0, {}}, {65534, {}}}); }, "back.*65535"); } TEST(SplineDeathTest, YIsLimited) { ASSERT_DEATH( { Spline<>::calculateCurve({{0, {}}, {32767, -1}, {65535, {}}}); }, "y >= .*min"); ASSERT_DEATH( { Spline<>::calculateCurve({{0, {}}, {32767, 65536}, {65535, {}}}); }, "y <= .*max"); } TEST(SplineDeathTest, XIsStrictlyIncreasing) { ASSERT_DEATH( { Spline<>::calculateCurve({{0, {}}, {0, {}}, {65535, {}}}); }, "strictly increasing"); ASSERT_DEATH( { Spline<>::calculateCurve( {{0, {}}, {32767, {}}, {32767, {}}, {65535, {}}}); }, "strictly increasing"); ASSERT_DEATH( { Spline<>::calculateCurve({{0, {}}, {65535, {}}, {65535, {}}}); }, "strictly increasing"); ASSERT_DEATH( { Spline<>::calculateCurve( {{0, {}}, {32767, {}}, {32766, {}}, {65535, {}}}); }, "strictly increasing"); } #endif TEST(SplineTest, IntegerIdentityTest) { const auto s = Spline<>::calculateCurve({{0, 0}, {65535, 65535}}); ASSERT_FALSE(s.empty()); ASSERT_EQ(s.size(), 65536); for (auto x = 0U; x < s.size(); ++x) ASSERT_EQ(s[x], x); } TEST(SplineTest, IntegerReverseIdentityTest) { const auto s = Spline<>::calculateCurve({{0, 65535}, {65535, 0}}); ASSERT_FALSE(s.empty()); ASSERT_EQ(s.size(), 65536); for (auto x = 0U; x < s.size(); ++x) { ASSERT_EQ(s[x], 65535 - x) << " Where x is: " << x; } } TEST(SplineTest, DoubleIdentityTest) { const auto s = Spline<double>::calculateCurve({{0, 0}, {65535, 65535}}); ASSERT_FALSE(s.empty()); ASSERT_EQ(s.size(), 65536); for (auto x = 0U; x < s.size(); ++x) { const double expected = x; ASSERT_DOUBLE_EQ(s[x], expected); ASSERT_EQ(s[x], expected); } } TEST(SplineTest, DoubleReverseIdentityTest) { const auto s = Spline<double>::calculateCurve({{0, 65535}, {65535, 0}}); ASSERT_FALSE(s.empty()); ASSERT_EQ(s.size(), 65536); for (auto x = 0U; x < s.size(); ++x) { const double expected = 65535 - x; ASSERT_DOUBLE_EQ(s[x], expected); ASSERT_EQ(s[x], expected); } } } // namespace rawspeed_test <|endoftext|>
<commit_before>#include "game/ui/base/researchselect.h" #include "forms/form.h" #include "forms/graphic.h" #include "forms/graphicbutton.h" #include "forms/label.h" #include "forms/listbox.h" #include "forms/ui.h" #include "framework/data.h" #include "framework/event.h" #include "framework/framework.h" #include "framework/keycodes.h" #include "game/state/city/base.h" #include "game/state/city/research.h" #include "game/state/gamestate.h" #include "game/state/rules/aequipmenttype.h" #include "game/state/rules/city/vammotype.h" #include "game/state/rules/city/vehicletype.h" #include "game/state/rules/city/vequipmenttype.h" #include "game/state/shared/organisation.h" #include "game/ui/general/messagebox.h" #include "library/strings_format.h" namespace OpenApoc { ResearchSelect::ResearchSelect(sp<GameState> state, sp<Lab> lab) : Stage(), form(ui().getForm("researchselect")), lab(lab), state(state) { progressImage = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 63)); } ResearchSelect::~ResearchSelect() = default; void ResearchSelect::begin() { current_topic = this->lab->current_project; form->findControlTyped<Label>("TEXT_FUNDS")->setText(state->getPlayerBalance()); auto title = form->findControlTyped<Label>("TEXT_TITLE"); auto progress = form->findControlTyped<Label>("TEXT_PROGRESS"); auto skill = form->findControlTyped<Label>("TEXT_SKILL"); switch (this->lab->type) { case ResearchTopic::Type::BioChem: title->setText(tr("Select Biochemistry Project")); progress->setText(tr("Progress")); skill->setText(tr("Skill")); break; case ResearchTopic::Type::Physics: title->setText(tr("Select Physics Project")); progress->setText(tr("Progress")); skill->setText(tr("Skill")); break; case ResearchTopic::Type::Engineering: title->setText(tr("Select Manufacturing Project")); progress->setText(tr("Unit Cost")); skill->setText(tr("Skill Hours")); break; default: title->setText(tr("Select Unknown Project")); break; } this->populateResearchList(); this->redrawResearchList(); auto research_list = form->findControlTyped<ListBox>("LIST"); research_list->AlwaysEmitSelectionEvents = true; research_list->addCallback(FormEventType::ListBoxChangeSelected, [this](FormsEvent *e) { LogInfo("Research selection change"); auto list = std::static_pointer_cast<ListBox>(e->forms().RaisedBy); auto topic = list->getSelectedData<ResearchTopic>(); if (topic->current_lab) { LogInfo("Topic already in progress"); } else { if (topic->isComplete()) { LogInfo("Topic already complete"); auto message_box = mksp<MessageBox>(tr("PROJECT COMPLETE"), tr("This project is already complete."), MessageBox::ButtonOptions::Ok); fw().stageQueueCommand({StageCmd::Command::PUSH, message_box}); return; } if (topic->required_lab_size == ResearchTopic::LabSize::Large && this->lab->size == ResearchTopic::LabSize::Small) { LogInfo("Topic is large and lab is small"); auto message_box = mksp<MessageBox>(tr("PROJECT TOO LARGE"), tr("This project requires an advanced lab or workshop."), MessageBox::ButtonOptions::Ok); fw().stageQueueCommand({StageCmd::Command::PUSH, message_box}); return; } if (this->lab->type == ResearchTopic::Type::Engineering && topic->cost > state->player->balance) { LogInfo("Cannot afford to manufacture"); auto message_box = mksp<MessageBox>( tr("FUNDS EXCEEDED"), tr("Production costs exceed your available funds."), MessageBox::ButtonOptions::Ok); fw().stageQueueCommand({StageCmd::Command::PUSH, message_box}); return; } } current_topic = topic; this->redrawResearchList(); }); research_list->addCallback(FormEventType::ListBoxChangeHover, [this](FormsEvent *e) { LogInfo("Research display on hover change"); auto list = std::static_pointer_cast<ListBox>(e->forms().RaisedBy); auto topic = list->getHoveredData<ResearchTopic>(); auto title = this->form->findControlTyped<Label>("TEXT_SELECTED_TITLE"); auto description = this->form->findControlTyped<Label>("TEXT_SELECTED_DESCRIPTION"); auto pic = this->form->findControlTyped<Graphic>("GRAPHIC_SELECTED"); if (topic) { title->setText(tr(topic->name)); description->setText(tr(topic->description)); if (topic->picture) { pic->setImage(topic->picture); } else { if (topic->type == ResearchTopic::Type::Engineering) { switch (topic->item_type) { case ResearchTopic::ItemType::VehicleEquipment: pic->setImage( this->state->vehicle_equipment[topic->itemId]->equipscreen_sprite); break; case ResearchTopic::ItemType::VehicleEquipmentAmmo: pic->setImage(nullptr); break; case ResearchTopic::ItemType::AgentEquipment: pic->setImage( this->state->agent_equipment[topic->itemId]->equipscreen_sprite); break; case ResearchTopic::ItemType::Craft: pic->setImage( this->state->vehicle_types[topic->itemId]->equip_icon_small); break; } } else { if (!topic->dependencies.items.agentItemsRequired.empty()) { pic->setImage(topic->dependencies.items.agentItemsRequired.begin() ->first->equipscreen_sprite); } else if (!topic->dependencies.items.vehicleItemsRequired.empty()) { pic->setImage(topic->dependencies.items.vehicleItemsRequired.begin() ->first->equipscreen_sprite); } else { pic->setImage(nullptr); } } } } else { title->setText(""); description->setText(""); pic->setImage(nullptr); } this->redrawResearchList(); }); auto ok_button = form->findControlTyped<GraphicButton>("BUTTON_OK"); ok_button->addCallback(FormEventType::ButtonClick, [this](FormsEvent *) { LogInfo("Research selection OK pressed, applying selection"); Lab::setResearch({state.get(), this->lab}, {state.get(), current_topic}, state); }); } void ResearchSelect::redrawResearchList() { for (auto &pair : control_map) { if (current_topic == pair.first) { pair.second->BackgroundColour = {127, 0, 0, 255}; } else { pair.second->BackgroundColour = {0, 0, 0, 0}; } } } void ResearchSelect::populateResearchList() { auto research_list = form->findControlTyped<ListBox>("LIST"); research_list->clear(); research_list->ItemSize = 20; research_list->ItemSpacing = 1; for (auto &t : state->research.topic_list) { if (t->type != this->lab->type) { continue; } if ((!t->dependencies.satisfied(state->current_base) && t->started == false) || t->hidden) { continue; } // FIXME: When we get font coloring, set light blue color for topics too large a size bool too_large = (t->required_lab_size == ResearchTopic::LabSize::Large && this->lab->size == ResearchTopic::LabSize::Small); std::ignore = too_large; auto control = mksp<Control>(); control->Size = {544, 20}; auto topic_name = control->createChild<Label>((t->name), ui().getFont("smalfont")); topic_name->Size = {200, 18}; topic_name->Location = {6, 2}; if (this->lab->type == ResearchTopic::Type::Engineering || ((this->lab->type == ResearchTopic::Type::BioChem || this->lab->type == ResearchTopic::Type::Physics) && t->isComplete())) { UString progress_text; if (this->lab->type == ResearchTopic::Type::Engineering) progress_text = format("$%d", t->cost); else progress_text = tr("Complete"); auto progress_label = control->createChild<Label>(progress_text, ui().getFont("smalfont")); progress_label->Size = {100, 18}; progress_label->Location = {234, 2}; } else { float projectProgress = clamp((float)t->man_hours_progress / (float)t->man_hours, 0.0f, 1.0f); auto progressBg = control->createChild<Graphic>(progressImage); progressBg->Size = {102, 6}; progressBg->Location = {234, 6}; auto progressBar = control->createChild<Graphic>(); progressBar->Size = {101, 6}; progressBar->Location = {234, 6}; auto progressImage = mksp<RGBImage>(progressBar->Size); int redWidth = progressBar->Size.x * projectProgress; { RGBImageLock l(progressImage); for (int y = 0; y < 2; y++) { for (int x = 0; x < progressBar->Size.x; x++) { if (x < redWidth) l.set({x, y}, {255, 0, 0, 255}); } } } progressBar->setImage(progressImage); } int skill_total = 0; switch (this->lab->type) { case ResearchTopic::Type::BioChem: case ResearchTopic::Type::Physics: if (t->current_lab) skill_total = t->current_lab->getTotalSkill(); break; case ResearchTopic::Type::Engineering: skill_total = t->man_hours; break; default: break; } auto skill_total_label = control->createChild<Label>(format("%d", skill_total), ui().getFont("smalfont")); skill_total_label->Size = {50, 18}; skill_total_label->Location = {328, 2}; skill_total_label->TextHAlign = HorizontalAlignment::Right; UString labSize; switch (t->required_lab_size) { case ResearchTopic::LabSize::Small: labSize = tr("Small"); break; case ResearchTopic::LabSize::Large: labSize = tr("Large"); break; default: labSize = tr("UNKNOWN"); break; } auto lab_size_label = control->createChild<Label>(labSize, ui().getFont("smalfont")); lab_size_label->Size = {100, 18}; lab_size_label->Location = {439, 2}; control->setData(t); research_list->addItem(control); control_map[t] = control; } } void ResearchSelect::pause() {} void ResearchSelect::resume() {} void ResearchSelect::finish() {} void ResearchSelect::eventOccurred(Event *e) { form->eventOccured(e); if (e->type() == EVENT_KEY_DOWN) { if (e->keyboard().KeyCode == SDLK_ESCAPE) { fw().stageQueueCommand({StageCmd::Command::POP}); return; } } if (e->type() == EVENT_FORM_INTERACTION) { if (e->forms().EventFlag == FormEventType::ButtonClick) { if (e->forms().RaisedBy->Name == "BUTTON_OK") { fw().stageQueueCommand({StageCmd::Command::POP}); return; } } } } void ResearchSelect::update() { form->update(); } void ResearchSelect::render() { fw().stageGetPrevious(this->shared_from_this())->render(); form->render(); } bool ResearchSelect::isTransition() { return false; } }; // namespace OpenApoc <commit_msg>Clear unselected topic's background in research selection form.<commit_after>#include "game/ui/base/researchselect.h" #include "forms/form.h" #include "forms/graphic.h" #include "forms/graphicbutton.h" #include "forms/label.h" #include "forms/listbox.h" #include "forms/ui.h" #include "framework/data.h" #include "framework/event.h" #include "framework/framework.h" #include "framework/keycodes.h" #include "game/state/city/base.h" #include "game/state/city/research.h" #include "game/state/gamestate.h" #include "game/state/rules/aequipmenttype.h" #include "game/state/rules/city/vammotype.h" #include "game/state/rules/city/vehicletype.h" #include "game/state/rules/city/vequipmenttype.h" #include "game/state/shared/organisation.h" #include "game/ui/general/messagebox.h" #include "library/strings_format.h" namespace OpenApoc { ResearchSelect::ResearchSelect(sp<GameState> state, sp<Lab> lab) : Stage(), form(ui().getForm("researchselect")), lab(lab), state(state) { progressImage = fw().data->loadImage(format( "PCK:xcom3/ufodata/newbut.pck:xcom3/ufodata/newbut.tab:%d:xcom3/ufodata/research.pcx", 63)); } ResearchSelect::~ResearchSelect() = default; void ResearchSelect::begin() { current_topic = this->lab->current_project; form->findControlTyped<Label>("TEXT_FUNDS")->setText(state->getPlayerBalance()); auto title = form->findControlTyped<Label>("TEXT_TITLE"); auto progress = form->findControlTyped<Label>("TEXT_PROGRESS"); auto skill = form->findControlTyped<Label>("TEXT_SKILL"); switch (this->lab->type) { case ResearchTopic::Type::BioChem: title->setText(tr("Select Biochemistry Project")); progress->setText(tr("Progress")); skill->setText(tr("Skill")); break; case ResearchTopic::Type::Physics: title->setText(tr("Select Physics Project")); progress->setText(tr("Progress")); skill->setText(tr("Skill")); break; case ResearchTopic::Type::Engineering: title->setText(tr("Select Manufacturing Project")); progress->setText(tr("Unit Cost")); skill->setText(tr("Skill Hours")); break; default: title->setText(tr("Select Unknown Project")); break; } this->populateResearchList(); this->redrawResearchList(); auto research_list = form->findControlTyped<ListBox>("LIST"); research_list->AlwaysEmitSelectionEvents = true; research_list->addCallback(FormEventType::ListBoxChangeSelected, [this](FormsEvent *e) { LogInfo("Research selection change"); auto list = std::static_pointer_cast<ListBox>(e->forms().RaisedBy); auto topic = list->getSelectedData<ResearchTopic>(); if (topic->current_lab) { LogInfo("Topic already in progress"); } else { if (topic->isComplete()) { LogInfo("Topic already complete"); auto message_box = mksp<MessageBox>(tr("PROJECT COMPLETE"), tr("This project is already complete."), MessageBox::ButtonOptions::Ok); fw().stageQueueCommand({StageCmd::Command::PUSH, message_box}); return; } if (topic->required_lab_size == ResearchTopic::LabSize::Large && this->lab->size == ResearchTopic::LabSize::Small) { LogInfo("Topic is large and lab is small"); auto message_box = mksp<MessageBox>(tr("PROJECT TOO LARGE"), tr("This project requires an advanced lab or workshop."), MessageBox::ButtonOptions::Ok); fw().stageQueueCommand({StageCmd::Command::PUSH, message_box}); return; } if (this->lab->type == ResearchTopic::Type::Engineering && topic->cost > state->player->balance) { LogInfo("Cannot afford to manufacture"); auto message_box = mksp<MessageBox>( tr("FUNDS EXCEEDED"), tr("Production costs exceed your available funds."), MessageBox::ButtonOptions::Ok); fw().stageQueueCommand({StageCmd::Command::PUSH, message_box}); return; } } if (current_topic && topic != current_topic) { control_map[current_topic]->setDirty(); } current_topic = topic; this->redrawResearchList(); }); research_list->addCallback(FormEventType::ListBoxChangeHover, [this](FormsEvent *e) { LogInfo("Research display on hover change"); auto list = std::static_pointer_cast<ListBox>(e->forms().RaisedBy); auto topic = list->getHoveredData<ResearchTopic>(); auto title = this->form->findControlTyped<Label>("TEXT_SELECTED_TITLE"); auto description = this->form->findControlTyped<Label>("TEXT_SELECTED_DESCRIPTION"); auto pic = this->form->findControlTyped<Graphic>("GRAPHIC_SELECTED"); if (topic) { title->setText(tr(topic->name)); description->setText(tr(topic->description)); if (topic->picture) { pic->setImage(topic->picture); } else { if (topic->type == ResearchTopic::Type::Engineering) { switch (topic->item_type) { case ResearchTopic::ItemType::VehicleEquipment: pic->setImage( this->state->vehicle_equipment[topic->itemId]->equipscreen_sprite); break; case ResearchTopic::ItemType::VehicleEquipmentAmmo: pic->setImage(nullptr); break; case ResearchTopic::ItemType::AgentEquipment: pic->setImage( this->state->agent_equipment[topic->itemId]->equipscreen_sprite); break; case ResearchTopic::ItemType::Craft: pic->setImage( this->state->vehicle_types[topic->itemId]->equip_icon_small); break; } } else { if (!topic->dependencies.items.agentItemsRequired.empty()) { pic->setImage(topic->dependencies.items.agentItemsRequired.begin() ->first->equipscreen_sprite); } else if (!topic->dependencies.items.vehicleItemsRequired.empty()) { pic->setImage(topic->dependencies.items.vehicleItemsRequired.begin() ->first->equipscreen_sprite); } else { pic->setImage(nullptr); } } } } else { title->setText(""); description->setText(""); pic->setImage(nullptr); } this->redrawResearchList(); }); auto ok_button = form->findControlTyped<GraphicButton>("BUTTON_OK"); ok_button->addCallback(FormEventType::ButtonClick, [this](FormsEvent *) { LogInfo("Research selection OK pressed, applying selection"); Lab::setResearch({state.get(), this->lab}, {state.get(), current_topic}, state); }); } void ResearchSelect::redrawResearchList() { for (auto &pair : control_map) { if (current_topic == pair.first) { pair.second->BackgroundColour = {127, 0, 0, 255}; } else { pair.second->BackgroundColour = {0, 0, 0, 0}; } } } void ResearchSelect::populateResearchList() { auto research_list = form->findControlTyped<ListBox>("LIST"); research_list->clear(); research_list->ItemSize = 20; research_list->ItemSpacing = 1; for (auto &t : state->research.topic_list) { if (t->type != this->lab->type) { continue; } if ((!t->dependencies.satisfied(state->current_base) && t->started == false) || t->hidden) { continue; } // FIXME: When we get font coloring, set light blue color for topics too large a size bool too_large = (t->required_lab_size == ResearchTopic::LabSize::Large && this->lab->size == ResearchTopic::LabSize::Small); std::ignore = too_large; auto control = mksp<Control>(); control->Size = {544, 20}; auto topic_name = control->createChild<Label>((t->name), ui().getFont("smalfont")); topic_name->Size = {200, 18}; topic_name->Location = {6, 2}; if (this->lab->type == ResearchTopic::Type::Engineering || ((this->lab->type == ResearchTopic::Type::BioChem || this->lab->type == ResearchTopic::Type::Physics) && t->isComplete())) { UString progress_text; if (this->lab->type == ResearchTopic::Type::Engineering) progress_text = format("$%d", t->cost); else progress_text = tr("Complete"); auto progress_label = control->createChild<Label>(progress_text, ui().getFont("smalfont")); progress_label->Size = {100, 18}; progress_label->Location = {234, 2}; } else { float projectProgress = clamp((float)t->man_hours_progress / (float)t->man_hours, 0.0f, 1.0f); auto progressBg = control->createChild<Graphic>(progressImage); progressBg->Size = {102, 6}; progressBg->Location = {234, 6}; auto progressBar = control->createChild<Graphic>(); progressBar->Size = {101, 6}; progressBar->Location = {234, 6}; auto progressImage = mksp<RGBImage>(progressBar->Size); int redWidth = progressBar->Size.x * projectProgress; { RGBImageLock l(progressImage); for (int y = 0; y < 2; y++) { for (int x = 0; x < progressBar->Size.x; x++) { if (x < redWidth) l.set({x, y}, {255, 0, 0, 255}); } } } progressBar->setImage(progressImage); } int skill_total = 0; switch (this->lab->type) { case ResearchTopic::Type::BioChem: case ResearchTopic::Type::Physics: if (t->current_lab) skill_total = t->current_lab->getTotalSkill(); break; case ResearchTopic::Type::Engineering: skill_total = t->man_hours; break; default: break; } auto skill_total_label = control->createChild<Label>(format("%d", skill_total), ui().getFont("smalfont")); skill_total_label->Size = {50, 18}; skill_total_label->Location = {328, 2}; skill_total_label->TextHAlign = HorizontalAlignment::Right; UString labSize; switch (t->required_lab_size) { case ResearchTopic::LabSize::Small: labSize = tr("Small"); break; case ResearchTopic::LabSize::Large: labSize = tr("Large"); break; default: labSize = tr("UNKNOWN"); break; } auto lab_size_label = control->createChild<Label>(labSize, ui().getFont("smalfont")); lab_size_label->Size = {100, 18}; lab_size_label->Location = {439, 2}; control->setData(t); research_list->addItem(control); control_map[t] = control; } if (current_topic) { research_list->setSelected(control_map[current_topic]); } } void ResearchSelect::pause() {} void ResearchSelect::resume() {} void ResearchSelect::finish() {} void ResearchSelect::eventOccurred(Event *e) { form->eventOccured(e); if (e->type() == EVENT_KEY_DOWN) { if (e->keyboard().KeyCode == SDLK_ESCAPE) { fw().stageQueueCommand({StageCmd::Command::POP}); return; } } if (e->type() == EVENT_FORM_INTERACTION) { if (e->forms().EventFlag == FormEventType::ButtonClick) { if (e->forms().RaisedBy->Name == "BUTTON_OK") { fw().stageQueueCommand({StageCmd::Command::POP}); return; } } } } void ResearchSelect::update() { form->update(); } void ResearchSelect::render() { fw().stageGetPrevious(this->shared_from_this())->render(); form->render(); } bool ResearchSelect::isTransition() { return false; } }; // namespace OpenApoc <|endoftext|>
<commit_before>#include "utils/GLFWApp.h" #include <string> #include "utils/Shader.h" class UniformOrder: public GLFWApp { public: void Init(GLFWwindow*) override { const std::string vs = R"(in vec4 a_position; void main(){ gl_Position = a_position; })"; const std::string fs = R"(#version 100 #extension GL_EXT_blend_func_extended : require precision highp float; uniform vec4 src; uniform vec4 src1; void main() { gl_FragData[0] = src; gl_SecondaryFragDataEXT[0] = src1; })"; mProgram = CompileProgram(vs, fs); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); } void Frame() override { glViewport(0, 0, 640, 480); glClearColor(0.5, 0.5, 0.5, 0.5); glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFuncSeparate(GL_SRC1_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC1_COLOR, GL_ONE_MINUS_SRC1_ALPHA); glUseProgram(mProgram); GLint location = glGetUniformLocation(mProgram, "src"); glUniform4f(location, 1.0, 1.0, 1.0, 1.0); GLint location2 = glGetUniformLocation(mProgram, "src1"); glUniform4f(location2, 0.3, 0.6, 0.9, 0.7); GLfloat vertices[] = { 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, }; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vertices); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 3); } void Destroy() override { } GLuint mProgram; }; int main(int argc, const char** argv) { return GLFWApp::Run(new UniformOrder); } <commit_msg>Repro case for the gl_ext_extended_blend_func intel bug<commit_after>#include "utils/GLFWApp.h" #include <string> #include "utils/Shader.h" class UniformOrder: public GLFWApp { public: void Init(GLFWwindow*) override { const std::string vs = R"(#version 100 attribute vec4 a_position; void main(){ gl_Position = a_position; })"; const std::string fs = R"(#version 100 #extension GL_EXT_blend_func_extended : require precision highp float; uniform vec4 src; uniform vec4 src1; void main() { // Works // gl_FragColor = src; // gl_SecondaryFragColorEXT = src1; // Doesn't on Intel Mesa gl_FragData[0] = src; gl_SecondaryFragDataEXT[0] = src1; })"; mProgram = CompileProgram(vs, fs); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); } void Frame() override { glViewport(0, 0, 640, 480); glClearColor(0.5, 0.5, 0.5, 0.5); glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFuncSeparate(GL_SRC1_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC1_COLOR, GL_ONE_MINUS_SRC1_ALPHA); glUseProgram(mProgram); GLint location = glGetUniformLocation(mProgram, "src"); glUniform4f(location, 1.0, 1.0, 1.0, 1.0); GLint location2 = glGetUniformLocation(mProgram, "src1"); glUniform4f(location2, 0.3, 0.6, 0.9, 0.7); GLfloat vertices[] = { 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, }; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vertices); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 3); } void Destroy() override { } GLuint mProgram; }; int main(int argc, const char** argv) { return GLFWApp::Run(new UniformOrder); } <|endoftext|>
<commit_before>// Copyright 2014 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 "config.h" #include "bindings/core/v8/ScriptPromiseProperty.h" #include "bindings/core/v8/DOMWrapperWorld.h" #include "bindings/core/v8/ScriptFunction.h" #include "bindings/core/v8/ScriptPromise.h" #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/ScriptValue.h" #include "bindings/core/v8/V8Binding.h" #include "core/dom/Document.h" #include "core/events/Event.h" #include "core/testing/DummyPageHolder.h" #include "core/testing/GCObservation.h" #include "wtf/OwnPtr.h" #include "wtf/PassOwnPtr.h" #include "wtf/PassRefPtr.h" #include "wtf/RefPtr.h" #include <gtest/gtest.h> #include <v8.h> using namespace WebCore; namespace { class NotReached : public ScriptFunction { public: NotReached() : ScriptFunction(v8::Isolate::GetCurrent()) { } private: virtual ScriptValue call(ScriptValue) OVERRIDE; }; ScriptValue NotReached::call(ScriptValue) { EXPECT_TRUE(false) << "'Unreachable' code was reached"; return ScriptValue(); } class StubFunction : public ScriptFunction { public: StubFunction(ScriptValue&, size_t& callCount); private: virtual ScriptValue call(ScriptValue) OVERRIDE; ScriptValue& m_value; size_t& m_callCount; }; StubFunction::StubFunction(ScriptValue& value, size_t& callCount) : ScriptFunction(v8::Isolate::GetCurrent()) , m_value(value) , m_callCount(callCount) { } ScriptValue StubFunction::call(ScriptValue arg) { m_value = arg; m_callCount++; return ScriptValue(); } class ScriptPromisePropertyTest : public ::testing::Test { protected: ScriptPromisePropertyTest() : m_page(DummyPageHolder::create(IntSize(1, 1))) { } virtual ~ScriptPromisePropertyTest() { destroyContext(); } Document& document() { return m_page->document(); } v8::Isolate* isolate() { return toIsolate(&document()); } ScriptState* scriptState() { return ScriptState::forMainWorld(document().frame()); } void destroyContext() { m_page.clear(); gc(); } void gc() { v8::Isolate::GetCurrent()->RequestGarbageCollectionForTesting(v8::Isolate::kFullGarbageCollection); } PassOwnPtr<ScriptFunction> notReached() { return adoptPtr(new NotReached()); } PassOwnPtr<ScriptFunction> stub(ScriptValue& value, size_t& callCount) { return adoptPtr(new StubFunction(value, callCount)); } // These tests use Event because it is simple to manufacture lots // of events, and 'Ready' because it is an available property name // that won't bloat V8HiddenValue with a test property name. ScriptValue wrap(PassRefPtrWillBeRawPtr<Event> event) { ScriptState::Scope scope(scriptState()); return ScriptValue(scriptState(), V8ValueTraits<Event>::toV8Value(event, scriptState()->context()->Global(), isolate())); } typedef ScriptPromiseProperty<RefPtrWillBeMember<Event>, Event*, Event*> Property; PassRefPtrWillBeRawPtr<Property> newProperty() { return Property::create(&document(), Event::create(), Property::Ready); } private: OwnPtr<DummyPageHolder> m_page; }; TEST_F(ScriptPromisePropertyTest, Promise_IsStableObject) { RefPtr<Property> p(newProperty()); ScriptPromise v = p->promise(DOMWrapperWorld::mainWorld()); ScriptPromise w = p->promise(DOMWrapperWorld::mainWorld()); EXPECT_EQ(v, w); EXPECT_FALSE(v.isEmpty()); EXPECT_EQ(Property::Pending, p->state()); } TEST_F(ScriptPromisePropertyTest, Promise_IsStableObjectAfterSettling) { RefPtr<Property> p(newProperty()); ScriptPromise v = p->promise(DOMWrapperWorld::mainWorld()); RefPtrWillBeRawPtr<Event> value(Event::create()); p->resolve(value.get()); EXPECT_EQ(Property::Resolved, p->state()); ScriptPromise w = p->promise(DOMWrapperWorld::mainWorld()); EXPECT_EQ(v, w); EXPECT_FALSE(v.isEmpty()); } TEST_F(ScriptPromisePropertyTest, Promise_DoesNotImpedeGarbageCollection) { RefPtrWillBePersistent<Event> holder(Event::create()); ScriptValue holderWrapper = wrap(holder); RefPtr<Property> p(Property::create(&document(), holder.get(), Property::Ready)); RefPtrWillBePersistent<GCObservation> observation; { ScriptState::Scope scope(scriptState()); observation = GCObservation::create(p->promise(DOMWrapperWorld::mainWorld()).v8Value()); } gc(); EXPECT_FALSE(observation->wasCollected()); holderWrapper.clear(); gc(); EXPECT_TRUE(observation->wasCollected()); EXPECT_EQ(Property::Pending, p->state()); } TEST_F(ScriptPromisePropertyTest, Resolve_ResolvesScriptPromise) { RefPtr<Property> p(newProperty()); ScriptPromise promise = p->promise(DOMWrapperWorld::mainWorld()); ScriptValue value; size_t nResolveCalls = 0; { ScriptState::Scope scope(scriptState()); promise.then(stub(value, nResolveCalls), notReached()); } RefPtrWillBeRawPtr<Event> event(Event::create()); p->resolve(event.get()); EXPECT_EQ(Property::Resolved, p->state()); isolate()->RunMicrotasks(); EXPECT_EQ(1u, nResolveCalls); EXPECT_EQ(wrap(event), value); } TEST_F(ScriptPromisePropertyTest, Reject_RejectsScriptPromise) { RefPtr<Property> p(newProperty()); RefPtrWillBeRawPtr<Event> event(Event::create()); p->reject(event.get()); EXPECT_EQ(Property::Rejected, p->state()); ScriptValue value; size_t nRejectCalls = 0; { ScriptState::Scope scope(scriptState()); p->promise(DOMWrapperWorld::mainWorld()).then(notReached(), stub(value, nRejectCalls)); } isolate()->RunMicrotasks(); EXPECT_EQ(1u, nRejectCalls); EXPECT_EQ(wrap(event), value); } TEST_F(ScriptPromisePropertyTest, Promise_DeadContext) { RefPtr<Property> p(newProperty()); RefPtrWillBeRawPtr<Event> event(Event::create()); p->resolve(event.get()); EXPECT_EQ(Property::Resolved, p->state()); destroyContext(); EXPECT_TRUE(p->promise(DOMWrapperWorld::mainWorld()).isEmpty()); } TEST_F(ScriptPromisePropertyTest, Resolve_DeadContext) { RefPtr<Property> p(newProperty()); { ScriptState::Scope scope(scriptState()); p->promise(DOMWrapperWorld::mainWorld()).then(notReached(), notReached()); } destroyContext(); RefPtrWillBeRawPtr<Event> event(Event::create()); p->resolve(event.get()); EXPECT_EQ(Property::Pending, p->state()); v8::Isolate::GetCurrent()->RunMicrotasks(); } } // namespace <commit_msg>ScriptPromisePropertyTest: Invoke Oilpan GC in memory-related tests too.<commit_after>// Copyright 2014 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 "config.h" #include "bindings/core/v8/ScriptPromiseProperty.h" #include "bindings/core/v8/DOMWrapperWorld.h" #include "bindings/core/v8/ScriptFunction.h" #include "bindings/core/v8/ScriptPromise.h" #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/ScriptValue.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8GCController.h" #include "core/dom/Document.h" #include "core/events/Event.h" #include "core/testing/DummyPageHolder.h" #include "core/testing/GCObservation.h" #include "wtf/OwnPtr.h" #include "wtf/PassOwnPtr.h" #include "wtf/PassRefPtr.h" #include "wtf/RefPtr.h" #include <gtest/gtest.h> #include <v8.h> using namespace WebCore; namespace { class NotReached : public ScriptFunction { public: NotReached() : ScriptFunction(v8::Isolate::GetCurrent()) { } private: virtual ScriptValue call(ScriptValue) OVERRIDE; }; ScriptValue NotReached::call(ScriptValue) { EXPECT_TRUE(false) << "'Unreachable' code was reached"; return ScriptValue(); } class StubFunction : public ScriptFunction { public: StubFunction(ScriptValue&, size_t& callCount); private: virtual ScriptValue call(ScriptValue) OVERRIDE; ScriptValue& m_value; size_t& m_callCount; }; StubFunction::StubFunction(ScriptValue& value, size_t& callCount) : ScriptFunction(v8::Isolate::GetCurrent()) , m_value(value) , m_callCount(callCount) { } ScriptValue StubFunction::call(ScriptValue arg) { m_value = arg; m_callCount++; return ScriptValue(); } class ScriptPromisePropertyTest : public ::testing::Test { protected: ScriptPromisePropertyTest() : m_page(DummyPageHolder::create(IntSize(1, 1))) { } virtual ~ScriptPromisePropertyTest() { destroyContext(); } Document& document() { return m_page->document(); } v8::Isolate* isolate() { return toIsolate(&document()); } ScriptState* scriptState() { return ScriptState::forMainWorld(document().frame()); } void destroyContext() { m_page.clear(); gc(); } void gc() { V8GCController::collectGarbage(v8::Isolate::GetCurrent()); } PassOwnPtr<ScriptFunction> notReached() { return adoptPtr(new NotReached()); } PassOwnPtr<ScriptFunction> stub(ScriptValue& value, size_t& callCount) { return adoptPtr(new StubFunction(value, callCount)); } // These tests use Event because it is simple to manufacture lots // of events, and 'Ready' because it is an available property name // that won't bloat V8HiddenValue with a test property name. ScriptValue wrap(PassRefPtrWillBeRawPtr<Event> event) { ScriptState::Scope scope(scriptState()); return ScriptValue(scriptState(), V8ValueTraits<Event>::toV8Value(event, scriptState()->context()->Global(), isolate())); } typedef ScriptPromiseProperty<RefPtrWillBeMember<Event>, Event*, Event*> Property; PassRefPtrWillBeRawPtr<Property> newProperty() { return Property::create(&document(), Event::create(), Property::Ready); } private: OwnPtr<DummyPageHolder> m_page; }; TEST_F(ScriptPromisePropertyTest, Promise_IsStableObject) { RefPtr<Property> p(newProperty()); ScriptPromise v = p->promise(DOMWrapperWorld::mainWorld()); ScriptPromise w = p->promise(DOMWrapperWorld::mainWorld()); EXPECT_EQ(v, w); EXPECT_FALSE(v.isEmpty()); EXPECT_EQ(Property::Pending, p->state()); } TEST_F(ScriptPromisePropertyTest, Promise_IsStableObjectAfterSettling) { RefPtr<Property> p(newProperty()); ScriptPromise v = p->promise(DOMWrapperWorld::mainWorld()); RefPtrWillBeRawPtr<Event> value(Event::create()); p->resolve(value.get()); EXPECT_EQ(Property::Resolved, p->state()); ScriptPromise w = p->promise(DOMWrapperWorld::mainWorld()); EXPECT_EQ(v, w); EXPECT_FALSE(v.isEmpty()); } TEST_F(ScriptPromisePropertyTest, Promise_DoesNotImpedeGarbageCollection) { RefPtrWillBePersistent<Event> holder(Event::create()); ScriptValue holderWrapper = wrap(holder); RefPtr<Property> p(Property::create(&document(), holder.get(), Property::Ready)); RefPtrWillBePersistent<GCObservation> observation; { ScriptState::Scope scope(scriptState()); observation = GCObservation::create(p->promise(DOMWrapperWorld::mainWorld()).v8Value()); } gc(); EXPECT_FALSE(observation->wasCollected()); holderWrapper.clear(); gc(); EXPECT_TRUE(observation->wasCollected()); EXPECT_EQ(Property::Pending, p->state()); } TEST_F(ScriptPromisePropertyTest, Resolve_ResolvesScriptPromise) { RefPtr<Property> p(newProperty()); ScriptPromise promise = p->promise(DOMWrapperWorld::mainWorld()); ScriptValue value; size_t nResolveCalls = 0; { ScriptState::Scope scope(scriptState()); promise.then(stub(value, nResolveCalls), notReached()); } RefPtrWillBeRawPtr<Event> event(Event::create()); p->resolve(event.get()); EXPECT_EQ(Property::Resolved, p->state()); isolate()->RunMicrotasks(); EXPECT_EQ(1u, nResolveCalls); EXPECT_EQ(wrap(event), value); } TEST_F(ScriptPromisePropertyTest, Reject_RejectsScriptPromise) { RefPtr<Property> p(newProperty()); RefPtrWillBeRawPtr<Event> event(Event::create()); p->reject(event.get()); EXPECT_EQ(Property::Rejected, p->state()); ScriptValue value; size_t nRejectCalls = 0; { ScriptState::Scope scope(scriptState()); p->promise(DOMWrapperWorld::mainWorld()).then(notReached(), stub(value, nRejectCalls)); } isolate()->RunMicrotasks(); EXPECT_EQ(1u, nRejectCalls); EXPECT_EQ(wrap(event), value); } TEST_F(ScriptPromisePropertyTest, Promise_DeadContext) { RefPtr<Property> p(newProperty()); RefPtrWillBeRawPtr<Event> event(Event::create()); p->resolve(event.get()); EXPECT_EQ(Property::Resolved, p->state()); destroyContext(); EXPECT_TRUE(p->promise(DOMWrapperWorld::mainWorld()).isEmpty()); } TEST_F(ScriptPromisePropertyTest, Resolve_DeadContext) { RefPtr<Property> p(newProperty()); { ScriptState::Scope scope(scriptState()); p->promise(DOMWrapperWorld::mainWorld()).then(notReached(), notReached()); } destroyContext(); RefPtrWillBeRawPtr<Event> event(Event::create()); p->resolve(event.get()); EXPECT_EQ(Property::Pending, p->state()); v8::Isolate::GetCurrent()->RunMicrotasks(); } } // namespace <|endoftext|>
<commit_before>#include "MarkovRunManager.h" MarkovRunManager* MarkovRunManager::_instance = nullptr; MarkovRunManager* MarkovRunManager::getInstance( ) { if (_instance == nullptr) _instance = new MarkovRunManager(); return _instance; } MarkovRunManager::MarkovRunManager(): _input_word(""), _steps_made(0), _word_after_last_step(""), _is_debug_mode(false) { } int MarkovRunManager::getStepNumberOfValue(QString word) { // QSet<StepResult>::iterator i; // for (i = _steps_history.begin(); i != _steps_history.end(); ++i) // { // StepResult curr = *i; // if(curr._output == word) // return curr._step_id; // } QSet<StepResult>::iterator it = qFind(_steps_history.begin(), _steps_history.end(), StepResult(word,0)); if (it != _steps_history.end()) return (*it)._step_id; return -1; } bool MarkovRunManager::choseAndUseRule(QString& word, MarkovRule& rule) { //get rule const MarkovRule* markov_rule = _algorithm.getRuleFor(word); rule = *markov_rule; QString res=""; //use rule if(markov_rule != nullptr) { res = _algorithm.useRule(word,rule); word = res; return true; } return false; } bool MarkovRunManager::findAndApplyNextRule() { if (_steps_history.contains(StepResult(_word_after_last_step,0))) { if(_is_debug_mode) { int prev_same_stem = getStepNumberOfValue(_input_word); QString description = "The result of step#"+prev_same_stem; description+=" is same as on the step #"; description+=_steps_made; RunError error("Algorithm never terminates", description, 102); emit debugFinishFail(_input_word,error,_steps_made); } else { int prev_same_stem = getStepNumberOfValue(_input_word); QString description = "The result of step#"+prev_same_stem; description+=" is same as on the step #"; description+=_steps_made; RunError error("Algorithm never terminates", description, 102); emit runWithoutDebugFinishFail(_input_word,error,_steps_made); } return false; } if(_word_after_last_step.size()>2000) { if(_is_debug_mode) { QString description = "Result can not be longer than 2000 symbols. On step #"+_steps_made; description+=" input become "; description+=_word_after_last_step.size(); RunError error("Too long result", description, 101); emit debugFinishFail(_input_word,error,_steps_made); } else { QString description = "Result can not be longer than 2000 symbols. On step #"+_steps_made; description+=" input become "; description+=_word_after_last_step.size(); RunError error("Too long result", description, 101); emit runWithoutDebugFinishFail(_input_word,error,_steps_made); } return false; } //Go through MarkovRules and select which fits. //If there are no rules then emit debugFinishSuccess or //runWithoutDebugFinishSuccess depending on run mode. //Use as _word_after_last_step as output word. QString word = _word_after_last_step; MarkovRule rule; if(!choseAndUseRule(word, rule)) { //there are no rules if(_is_debug_mode) { emit debugFinishSuccess(_input_word, word, _steps_made); } else { emit runWithoutDebugFinishSuccess(_input_word, word, _steps_made); } } ++_steps_made; if(_is_debug_mode) { emit debugStepFinished(_steps_made, _word_after_last_step, word, rule); } _word_after_last_step = word; _steps_history.insert(StepResult(_word_after_last_step,_steps_made)); if(_is_debug_mode) { if(_break_points.contains(rule.getLineNumber())) { emit debugBreakPointReached(rule.getLineNumber()); return false; } } //If rule is final then emit debugFinishSuccess or //runWithoutDebugFinishSuccess depending on run mode. //Use as _word_after_last_step as output word. return false. if(rule.isFinalRule()) { if(_is_debug_mode) { emit debugFinishSuccess(_input_word, _word_after_last_step, _steps_made); } else { emit runWithoutDebugFinishSuccess(_input_word, _word_after_last_step, _steps_made); } return false; } return true; } void MarkovRunManager::setAlgorithm(MarkovAlgorithm algorithm) { _algorithm = algorithm; } void MarkovRunManager::setCanRunSourceCode(bool can) { emit canRunSourceCode(can); } void MarkovRunManager::runWithoutDebug(QString input_word) { _steps_made = 0; _steps_history.clear(); _input_word = input_word; _word_after_last_step = input_word; _is_debug_mode = false; while(findAndApplyNextRule()) { if(_steps_made%100 == 0) { emit runStepsMade(_steps_made); } } } void MarkovRunManager::runWithDebug(QString input_word) { _steps_made = 0; _steps_history.clear(); _input_word = input_word; _word_after_last_step = input_word; _is_debug_mode = true; while(findAndApplyNextRule()) { } } void MarkovRunManager::addBreakPoint(int line_number) { _break_points.insert(line_number); } void MarkovRunManager::removeBreakPoint(int line_number) { QSet<int>::iterator i = _break_points.begin(); while (i != _break_points.end()) { if ((*i)== line_number) { i = _break_points.erase(i); } } } void MarkovRunManager::debugNextStep() { findAndApplyNextRule(); } void MarkovRunManager::debugContinue() { while(findAndApplyNextRule()) { } } void MarkovRunManager::debugStop() { if(_is_debug_mode) { RunError error("Debug stopped by the user","",103); emit debugFinishFail(_input_word,error,_steps_made); } else { RunError error("Debug stopped by the user","",103); emit runWithoutDebugFinishFail(_input_word, error,_steps_made); } } bool operator<(const StepResult& a, const StepResult& b) { return a._output < b._output; } bool operator==(const StepResult& a, const StepResult& b) { return a._output == b._output; } <commit_msg>close #29<commit_after>#include "MarkovRunManager.h" MarkovRunManager* MarkovRunManager::_instance = nullptr; MarkovRunManager* MarkovRunManager::getInstance( ) { if (_instance == nullptr) _instance = new MarkovRunManager(); return _instance; } MarkovRunManager::MarkovRunManager(): _input_word(""), _steps_made(0), _word_after_last_step(""), _is_debug_mode(false) { } int MarkovRunManager::getStepNumberOfValue(QString word) { // QSet<StepResult>::iterator i; // for (i = _steps_history.begin(); i != _steps_history.end(); ++i) // { // StepResult curr = *i; // if(curr._output == word) // return curr._step_id; // } QSet<StepResult>::iterator it = qFind(_steps_history.begin(), _steps_history.end(), StepResult(word,0)); if (it != _steps_history.end()) return (*it)._step_id; return -1; } bool MarkovRunManager::choseAndUseRule(QString& word, MarkovRule& rule) { //get rule const MarkovRule* markov_rule = _algorithm.getRuleFor(word); QString res=""; //use rule if(markov_rule != nullptr) { rule = *markov_rule; res = _algorithm.useRule(word,rule); word = res; return true; } return false; } bool MarkovRunManager::findAndApplyNextRule() { if(_word_after_last_step.size()>2000) { if(_is_debug_mode) { QString description = "Result can not be longer than 2000 symbols. On step #"+_steps_made; description+=" input become "; description+=_word_after_last_step.size(); RunError error("Too long result", description, 101); emit debugFinishFail(_input_word,error,_steps_made); } else { QString description = "Result can not be longer than 2000 symbols. On step #"+_steps_made; description+=" input become "; description+=_word_after_last_step.size(); RunError error("Too long result", description, 101); emit runWithoutDebugFinishFail(_input_word,error,_steps_made); } return false; } //Go through MarkovRules and select which fits. //If there are no rules then emit debugFinishSuccess or //runWithoutDebugFinishSuccess depending on run mode. //Use as _word_after_last_step as output word. QString word = _word_after_last_step; MarkovRule rule; if(!choseAndUseRule(word, rule)) { //there are no rules if(_is_debug_mode) { emit debugFinishSuccess(_input_word, word, _steps_made); } else { emit runWithoutDebugFinishSuccess(_input_word, word, _steps_made); } } ++_steps_made; if(_is_debug_mode) { emit debugStepFinished(_steps_made, _word_after_last_step, word, rule); } _word_after_last_step = word; if (_steps_history.contains(StepResult(_word_after_last_step,0))) { if(_is_debug_mode) { int prev_same_stem = getStepNumberOfValue(_input_word); QString description = "The result of step#"+prev_same_stem; description+=" is same as on the step #"; description+=_steps_made; RunError error("Algorithm never terminates", description, 102); emit debugFinishFail(_input_word,error,_steps_made); } else { int prev_same_stem = getStepNumberOfValue(_input_word); QString description = "The result of step#"+prev_same_stem; description+=" is same as on the step #"; description+=_steps_made; RunError error("Algorithm never terminates", description, 102); emit runWithoutDebugFinishFail(_input_word,error,_steps_made); } return false; } _steps_history.insert(StepResult(_word_after_last_step,_steps_made)); if(_is_debug_mode) { if(_break_points.contains(rule.getLineNumber())) { emit debugBreakPointReached(rule.getLineNumber()); return false; } } //If rule is final then emit debugFinishSuccess or //runWithoutDebugFinishSuccess depending on run mode. //Use as _word_after_last_step as output word. return false. if(rule.isFinalRule()) { if(_is_debug_mode) { emit debugFinishSuccess(_input_word, _word_after_last_step, _steps_made); } else { emit runWithoutDebugFinishSuccess(_input_word, _word_after_last_step, _steps_made); } return false; } return true; } void MarkovRunManager::setAlgorithm(MarkovAlgorithm algorithm) { _algorithm = algorithm; } void MarkovRunManager::setCanRunSourceCode(bool can) { emit canRunSourceCode(can); } void MarkovRunManager::runWithoutDebug(QString input_word) { _steps_made = 0; _steps_history.clear(); _input_word = input_word; _word_after_last_step = input_word; _is_debug_mode = false; while(findAndApplyNextRule()) { if(_steps_made%100 == 0) { emit runStepsMade(_steps_made); } } } void MarkovRunManager::runWithDebug(QString input_word) { _steps_made = 0; _steps_history.clear(); _input_word = input_word; _word_after_last_step = input_word; _is_debug_mode = true; while(findAndApplyNextRule()) { } } void MarkovRunManager::addBreakPoint(int line_number) { _break_points.insert(line_number); } void MarkovRunManager::removeBreakPoint(int line_number) { QSet<int>::iterator i = _break_points.begin(); while (i != _break_points.end()) { if ((*i)== line_number) { i = _break_points.erase(i); } } } void MarkovRunManager::debugNextStep() { findAndApplyNextRule(); } void MarkovRunManager::debugContinue() { while(findAndApplyNextRule()) { } } void MarkovRunManager::debugStop() { if(_is_debug_mode) { RunError error("Debug stopped by the user","",103); emit debugFinishFail(_input_word,error,_steps_made); } else { RunError error("Debug stopped by the user","",103); emit runWithoutDebugFinishFail(_input_word, error,_steps_made); } } bool operator<(const StepResult& a, const StepResult& b) { return a._output < b._output; } bool operator==(const StepResult& a, const StepResult& b) { return a._output == b._output; } <|endoftext|>
<commit_before> #include "tasksystem.hpp" #include "filters.hpp" #include <iostream> #include <cstring> void tag(int argc, char *argv[], sptm::TaskSystem* ts) { if(argc != 4) { std::cerr << "Invalid use of tag command." << std::endl; return; } ts->clearFilters(); sptm::TagFilter filter(argv[3], true); ts->addFilter(&filter); std::vector<sptm::Task*> tasks = ts->applyFilters(); for(sptm::Task* tk : tasks) tk->addTag(argv[2]); } void search(int argc, char *argv[], sptm::TaskSystem* ts) { if(argc <= 2) { std::cerr << "Missing arguments to search command." << std::endl; return; } ts->clearFilters(); for(int i = 2; i < argc; ++i) { sptm::TagFilter filter(argv[i], true); if(argv[i][0] == '-') filter.set(argv[i] + 1, false); ts->addFilter(&filter); } std::vector<sptm::Task*> tasks = ts->applyFilters(); for(sptm::Task* tk : tasks) std::cout << "Task " << tk->stored_id() << " : \"" << tk->action() << "\"." << std::endl; } int main(int argc, char *argv[]) { if(argc <= 1) { std::cerr << "Argument required." << std::endl; return 1; } sptm::TaskSystem ts; ts.config(sptm::TaskSystem::DEFSRC, "Lucas8"); ts.config(sptm::TaskSystem::DEFDST, "Lucas8"); ts.config(sptm::TaskSystem::DEFEXE, "Lucas8"); std::string home = std::getenv("HOME"); ts.config(sptm::TaskSystem::DONEPATH, home + "/.sptm/done"); ts.config(sptm::TaskSystem::UNDONEPATH, home + "/.sptm/undone"); if(!ts.load()) { std::cerr << "Couldn't load SPTM files." << std::endl; return 1; } if(strcmp(argv[1], "tag") == 0) tag(argc, argv, &ts); else if(strcmp(argv[1], "search") == 0) search(argc, argv, &ts); else { std::cerr << "Invalid command." << std::endl; return 1; } return 0; } <commit_msg>Added saving at the end of the test program.<commit_after> #include "tasksystem.hpp" #include "filters.hpp" #include <iostream> #include <cstring> void tag(int argc, char *argv[], sptm::TaskSystem* ts) { if(argc != 4) { std::cerr << "Invalid use of tag command." << std::endl; return; } ts->clearFilters(); sptm::TagFilter filter(argv[3], true); ts->addFilter(&filter); std::vector<sptm::Task*> tasks = ts->applyFilters(); for(sptm::Task* tk : tasks) tk->addTag(argv[2]); } void search(int argc, char *argv[], sptm::TaskSystem* ts) { if(argc <= 2) { std::cerr << "Missing arguments to search command." << std::endl; return; } ts->clearFilters(); for(int i = 2; i < argc; ++i) { sptm::TagFilter filter(argv[i], true); if(argv[i][0] == '-') filter.set(argv[i] + 1, false); ts->addFilter(&filter); } std::vector<sptm::Task*> tasks = ts->applyFilters(); for(sptm::Task* tk : tasks) std::cout << "Task " << tk->stored_id() << " : \"" << tk->action() << "\"." << std::endl; } int main(int argc, char *argv[]) { if(argc <= 1) { std::cerr << "Argument required." << std::endl; return 1; } sptm::TaskSystem ts; ts.config(sptm::TaskSystem::DEFSRC, "Lucas8"); ts.config(sptm::TaskSystem::DEFDST, "Lucas8"); ts.config(sptm::TaskSystem::DEFEXE, "Lucas8"); std::string home = std::getenv("HOME"); ts.config(sptm::TaskSystem::DONEPATH, home + "/.sptm/done"); ts.config(sptm::TaskSystem::UNDONEPATH, home + "/.sptm/undone"); if(!ts.load()) { std::cerr << "Couldn't load SPTM files." << std::endl; return 1; } if(strcmp(argv[1], "tag") == 0) tag(argc, argv, &ts); else if(strcmp(argv[1], "search") == 0) search(argc, argv, &ts); else { std::cerr << "Invalid command." << std::endl; return 1; } if(!ts.save()) { std::cerr << "Couldn't save changes." << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>// This is a collection of useful code for solving problems that // involve modular linear equations. Note that all of the // algorithms described here work on nonnegative integers. #include <iostream> #include <vector> #include <algorithm> using namespace std; typedef vector<int> VI; typedef pair<int,int> PII; // return a % b (positive value) int mod(int a, int b) { return ((a%b)+b)%b; } // computes gcd(a,b) int gcd(int a, int b) { int tmp; while(b){a%=b; tmp=a; a=b; b=tmp;} return a; } // computes lcm(a,b) int lcm(int a, int b) { return a/gcd(a,b)*b; } // returns d = gcd(a,b); finds x,y such that d = ax + by int extended_euclid(int a, int b, int &x, int &y) { int xx = y = 0; int yy = x = 1; while (b) { int q = a/b; int t = b; b = a%b; a = t; t = xx; xx = x-q*xx; x = t; t = yy; yy = y-q*yy; y = t; } return a; } // finds all solutions to ax = b (mod n) VI modular_linear_equation_solver(int a, int b, int n) { int x, y; VI solutions; int d = extended_euclid(a, n, x, y); if (!(b%d)) { x = mod (x*(b/d), n); for (int i = 0; i < d; i++) solutions.push_back(mod(x + i*(n/d), n)); } return solutions; } // computes b such that ab = 1 (mod n), returns -1 on failure int mod_inverse(int a, int n) { int x, y; int d = extended_euclid(a, n, x, y); if (d > 1) return -1; return mod(x,n); } // Chinese remainder theorem (special case): find z such that // z % x = a, z % y = b. Here, z is unique modulo M = lcm(x,y). // Return (z,M). On failure, M = -1. PII chinese_remainder_theorem(int x, int a, int y, int b) { int s, t; int d = extended_euclid(x, y, s, t); if (a%d != b%d) return make_pair(0, -1); return make_pair(mod(s*b*x+t*a*y,x*y)/d, x*y/d); } // Chinese remainder theorem: find z such that // z % x[i] = a[i] for all i. Note that the solution is // unique modulo M = lcm_i (x[i]). Return (z,M). On // failure, M = -1. Note that we do not require the a[i]'s // to be relatively prime. PII chinese_remainder_theorem(const VI &x, const VI &a) { PII ret = make_pair(a[0], x[0]); for (int i = 1; i < x.size(); i++) { ret = chinese_remainder_theorem(ret.second, ret.first, x[i], a[i]); if (ret.second == -1) break; } return ret; } // computes x and y such that ax + by = c; on failure, x = y =-1 void linear_diophantine(int a, int b, int c, int &x, int &y) { int d = gcd(a,b); if (c%d) { x = y = -1; } else { x = c/d * mod_inverse(a/d, b/d); y = (c-a*x)/b; } } int main() { // expected: 2 cout << gcd(14, 30) << endl; // expected: 2 -2 1 int x, y; int d = extended_euclid(14, 30, x, y); cout << d << " " << x << " " << y << endl; // expected: 95 45 VI sols = modular_linear_equation_solver(14, 30, 100); for (int i = 0; i < (int) sols.size(); i++) cout << sols[i] << " "; cout << endl; // expected: 8 cout << mod_inverse(8, 9) << endl; // expected: 23 56 // 11 12 int xs[] = {3, 5, 7, 4, 6}; int as[] = {2, 3, 2, 3, 5}; PII ret = chinese_remainder_theorem(VI (xs, xs+3), VI(as, as+3)); cout << ret.first << " " << ret.second << endl; ret = chinese_remainder_theorem (VI(xs+3, xs+5), VI(as+3, as+5)); cout << ret.first << " " << ret.second << endl; // expected: 5 -15 linear_diophantine(7, 2, 5, x, y); cout << x << " " << y << endl; } <commit_msg>Update Euclid.cpp<commit_after>// This is a collection of useful code for solving problems that // involve modular linear equations. Note that all of the // algorithms described here work on nonnegative integers. #include <iostream> #include <vector> #include <algorithm> using namespace std; typedef vector<int> VI; typedef pair<int,int> PII; // return a % b (positive value) int mod(int a, int b) { return ((a%b)+b)%b; } // computes gcd(a,b) int gcd(int a, int b) { while(b){a%=b; swap(a,b);} return a; } // computes lcm(a,b) int lcm(int a, int b) { return a/gcd(a,b)*b; } // returns d = gcd(a,b); finds x,y such that d = ax + by int extended_euclid(int a, int b, int &x, int &y) { int xx = y = 0; int yy = x = 1; while (b) { int q = a/b; int t = b; b = a%b; a = t; t = xx; xx = x-q*xx; x = t; t = yy; yy = y-q*yy; y = t; } return a; } // finds all solutions to ax = b (mod n) VI modular_linear_equation_solver(int a, int b, int n) { int x, y; VI solutions; int d = extended_euclid(a, n, x, y); if (!(b%d)) { x = mod (x*(b/d), n); for (int i = 0; i < d; i++) solutions.push_back(mod(x + i*(n/d), n)); } return solutions; } // computes b such that ab = 1 (mod n), returns -1 on failure int mod_inverse(int a, int n) { int x, y; int d = extended_euclid(a, n, x, y); if (d > 1) return -1; return mod(x,n); } // Chinese remainder theorem (special case): find z such that // z % x = a, z % y = b. Here, z is unique modulo M = lcm(x,y). // Return (z,M). On failure, M = -1. PII chinese_remainder_theorem(int x, int a, int y, int b) { int s, t; int d = extended_euclid(x, y, s, t); if (a%d != b%d) return make_pair(0, -1); return make_pair(mod(s*b*x+t*a*y,x*y)/d, x*y/d); } // Chinese remainder theorem: find z such that // z % x[i] = a[i] for all i. Note that the solution is // unique modulo M = lcm_i (x[i]). Return (z,M). On // failure, M = -1. Note that we do not require the a[i]'s // to be relatively prime. PII chinese_remainder_theorem(const VI &x, const VI &a) { PII ret = make_pair(a[0], x[0]); for (int i = 1; i < x.size(); i++) { ret = chinese_remainder_theorem(ret.second, ret.first, x[i], a[i]); if (ret.second == -1) break; } return ret; } // computes x and y such that ax + by = c; on failure, x = y =-1 void linear_diophantine(int a, int b, int c, int &x, int &y) { int d = gcd(a,b); if (c%d) { x = y = -1; } else { x = c/d * mod_inverse(a/d, b/d); y = (c-a*x)/b; } } int main() { // expected: 2 cout << gcd(14, 30) << endl; // expected: 2 -2 1 int x, y; int d = extended_euclid(14, 30, x, y); cout << d << " " << x << " " << y << endl; // expected: 95 45 VI sols = modular_linear_equation_solver(14, 30, 100); for (int i = 0; i < (int) sols.size(); i++) cout << sols[i] << " "; cout << endl; // expected: 8 cout << mod_inverse(8, 9) << endl; // expected: 23 56 // 11 12 int xs[] = {3, 5, 7, 4, 6}; int as[] = {2, 3, 2, 3, 5}; PII ret = chinese_remainder_theorem(VI (xs, xs+3), VI(as, as+3)); cout << ret.first << " " << ret.second << endl; ret = chinese_remainder_theorem (VI(xs+3, xs+5), VI(as+3, as+5)); cout << ret.first << " " << ret.second << endl; // expected: 5 -15 linear_diophantine(7, 2, 5, x, y); cout << x << " " << y << endl; } <|endoftext|>
<commit_before>#include "decomm_inst.h" using decomm::DecommInst; enum buildtype_t { BUILD = 1, DECOMM = 2}; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - DecommInst::DecommInst(cyclus::Context* ctx) : cyclus::Institution(ctx), target_commod(""), target_fac(""), num_to_build(0){ } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - DecommInst::~DecommInst() {} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Tick(){ using cyclus::toolkit::Commodity; Commodity commod = Commodity(target_commod); int time = context()->time(); double demand = sdmanager_.Demand(commod, time); double supply = sdmanager_.Supply(commod); double unmetdemand = demand - supply; LOG(cyclus::LEV_INFO3, "DcmIst") << "DecommInst: " << prototype() << " at time: " << time << " has the following values regaring " << " commodity: " << target_commod; LOG(cyclus::LEV_INFO3, "DcmIst") << " *demand = " << demand; LOG(cyclus::LEV_INFO3, "DcmIst") << " *supply = " << supply; LOG(cyclus::LEV_INFO3, "DcmIst") << " *unmetdemand = " << unmetdemand; int n = NToBuild(unmetdemand); if( n < 0 ) { Decommission(n); } else if (n > 0) { Build(n); } cyclus::Institution::Tick(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::EnterNotify(){ /// enter the simulation and register any children present cyclus::Institution::EnterNotify(); std::set<cyclus::Agent*>::iterator it; for (it = cyclus::Agent::children().begin(); it != cyclus::Agent::children().end(); ++it) { Agent* a = *it; Register_(a); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::BuildNotify(Agent* m){ /// register a new child Register_(m); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::DecomNotify(Agent* m){ /// unregister a decommissioned child Unregister_(m); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Decommission(Agent* to_decomm) { context()->SchedDecom(to_decomm, context()->time() + 1); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Decommission(int n){ n = abs(n); std::set<cyclus::Agent*>::iterator next; for (int i = 0; i < n; ++i ){ next = target_facs.begin(); target_facs.erase(next); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Build(int n) { for( int i = 0; i != n; ++i ){ context()->SchedBuild(this, target_fac, context()->time() + 1); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int DecommInst::NToBuild(double avail) { // convert material availability to a number of facilities to build. int n = 0; if (DecisionLogic(avail)) { n += num_to_build; } // need some logic to decrement avail. return n; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double DecommInst::MaterialAvailable(cyclus::toolkit::Commodity commod){ // use the commodityproducermanager to determine material available double n = 0; return n; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Register_(cyclus::Agent* agent){ /// register a child using cyclus::toolkit::CommodityProducerManager; using cyclus::toolkit::Builder; // if it's a commodity producer manager register it that way CommodityProducerManager* cpm_cast = dynamic_cast<CommodityProducerManager*>(agent); if (cpm_cast != NULL) { LOG(cyclus::LEV_INFO3, "DcmIst") << "Registering agent " << agent->prototype() << agent->id() << " as a commodity producer manager."; sdmanager_.RegisterProducerManager(cpm_cast); } // if it's a builder, register it that way Builder* b_cast = dynamic_cast<Builder*>(agent); if (b_cast != NULL) { LOG(cyclus::LEV_INFO3, "DcmIst") << "Registering agent " << agent->prototype() << agent->id() << " as a builder."; buildmanager_.Register(b_cast); } // if it's one of the facilities to decommision, register that cyclus::Facility* fac_cast = dynamic_cast<cyclus::Facility*>(agent); if (fac_cast != NULL && agent->prototype() == target_fac) { LOG(cyclus::LEV_INFO3, "DcmIst") << "Registering agent " << agent->prototype() << agent->id() << " as a target facility."; target_facs.insert(fac_cast); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Unregister_(cyclus::Agent* agent){ /// unregister a child using cyclus::toolkit::CommodityProducerManager; using cyclus::toolkit::Builder; CommodityProducerManager* cpm_cast = dynamic_cast<CommodityProducerManager*>(agent); if (cpm_cast != NULL){ sdmanager_.UnregisterProducerManager(cpm_cast); } Builder* b_cast = dynamic_cast<Builder*>(agent); if (b_cast != NULL){ buildmanager_.Unregister(b_cast); } cyclus::Facility* fac_cast = dynamic_cast<cyclus::Facility*>(agent); if (fac_cast != NULL && agent->prototype() == target_fac){ target_facs.erase(agent); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool DecommInst::DecisionLogic(double avail){ bool d = false; return d; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - extern "C" cyclus::Agent* ConstructDecommInst(cyclus::Context* ctx) { return new DecommInst(ctx); } <commit_msg>using placeholder for demand function, test passes<commit_after>#include "decomm_inst.h" using decomm::DecommInst; enum buildtype_t { BUILD = 1, DECOMM = 2}; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - DecommInst::DecommInst(cyclus::Context* ctx) : cyclus::Institution(ctx), target_commod(""), target_fac(""), num_to_build(0){ sdmanager_ = cyclus::toolkit::SupplyDemandManager(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - DecommInst::~DecommInst() {} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Tick(){ using cyclus::toolkit::Commodity; Commodity commod = Commodity(target_commod); int time = context()->time(); // double demand = sdmanager_.Demand(commod, time); double demand = 2; double supply = sdmanager_.Supply(commod); // double unmetdemand = demand - supply; // // LOG(cyclus::LEV_INFO3, "DcmIst") << "DecommInst: " << prototype() // << " at time: " << time // << " has the following values regaring " // << " commodity: " << target_commod; // LOG(cyclus::LEV_INFO3, "DcmIst") << " *demand = " << demand; // LOG(cyclus::LEV_INFO3, "DcmIst") << " *supply = " << supply; // LOG(cyclus::LEV_INFO3, "DcmIst") << " *unmetdemand = " << unmetdemand; // // int n = NToBuild(unmetdemand); // // if( n < 0 ) { // Decommission(n); // } else if (n > 0) { // Build(n); // } cyclus::Institution::Tick(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::EnterNotify(){ /// enter the simulation and register any children present cyclus::Institution::EnterNotify(); std::set<cyclus::Agent*>::iterator it; for (it = cyclus::Agent::children().begin(); it != cyclus::Agent::children().end(); ++it) { Agent* a = *it; Register_(a); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::BuildNotify(Agent* m){ /// register a new child Register_(m); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::DecomNotify(Agent* m){ /// unregister a decommissioned child Unregister_(m); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Decommission(Agent* to_decomm) { context()->SchedDecom(to_decomm, context()->time() + 1); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Decommission(int n){ n = abs(n); std::set<cyclus::Agent*>::iterator next; for (int i = 0; i < n; ++i ){ next = target_facs.begin(); target_facs.erase(next); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Build(int n) { for( int i = 0; i != n; ++i ){ context()->SchedBuild(this, target_fac, context()->time() + 1); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int DecommInst::NToBuild(double avail) { // convert material availability to a number of facilities to build. int n = 0; if (DecisionLogic(avail)) { n += num_to_build; } // need some logic to decrement avail. return n; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double DecommInst::MaterialAvailable(cyclus::toolkit::Commodity commod){ // use the commodityproducermanager to determine material available double n = 0; return n; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Register_(cyclus::Agent* agent){ /// register a child using cyclus::toolkit::CommodityProducerManager; using cyclus::toolkit::Builder; // if it's a commodity producer manager register it that way CommodityProducerManager* cpm_cast = dynamic_cast<CommodityProducerManager*>(agent); if (cpm_cast != NULL) { LOG(cyclus::LEV_INFO3, "DcmIst") << "Registering agent " << agent->prototype() << agent->id() << " as a commodity producer manager."; sdmanager_.RegisterProducerManager(cpm_cast); } // if it's a builder, register it that way Builder* b_cast = dynamic_cast<Builder*>(agent); if (b_cast != NULL) { LOG(cyclus::LEV_INFO3, "DcmIst") << "Registering agent " << agent->prototype() << agent->id() << " as a builder."; buildmanager_.Register(b_cast); } // if it's one of the facilities to decommision, register that cyclus::Facility* fac_cast = dynamic_cast<cyclus::Facility*>(agent); if (fac_cast != NULL && agent->prototype() == target_fac) { LOG(cyclus::LEV_INFO3, "DcmIst") << "Registering agent " << agent->prototype() << agent->id() << " as a target facility."; target_facs.insert(fac_cast); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void DecommInst::Unregister_(cyclus::Agent* agent){ /// unregister a child using cyclus::toolkit::CommodityProducerManager; using cyclus::toolkit::Builder; CommodityProducerManager* cpm_cast = dynamic_cast<CommodityProducerManager*>(agent); if (cpm_cast != NULL){ sdmanager_.UnregisterProducerManager(cpm_cast); } Builder* b_cast = dynamic_cast<Builder*>(agent); if (b_cast != NULL){ buildmanager_.Unregister(b_cast); } cyclus::Facility* fac_cast = dynamic_cast<cyclus::Facility*>(agent); if (fac_cast != NULL && agent->prototype() == target_fac){ target_facs.erase(agent); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool DecommInst::DecisionLogic(double avail){ bool d = false; return d; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - extern "C" cyclus::Agent* ConstructDecommInst(cyclus::Context* ctx) { return new DecommInst(ctx); } <|endoftext|>
<commit_before>// Copyright (c) 2016-2020 The ZCash developers // Copyright (c) 2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet/test/wallet_test_fixture.h" #include "wallet/wallet.h" #include "rpc/server.h" #include "rpc/client.h" #include "sapling/key_io_sapling.h" #include "sapling/address.hpp" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> #include <boost/format.hpp> #include <boost/filesystem.hpp> #include <univalue.h> extern UniValue CallRPC(std::string args); // Implemented in rpc_tests.cpp BOOST_FIXTURE_TEST_SUITE(sapling_rpc_wallet_tests, WalletTestingSetup) /** * This test covers RPC command validateaddress */ BOOST_AUTO_TEST_CASE(rpc_wallet_sapling_validateaddress) { SelectParams(CBaseChainParams::MAIN); LOCK2(cs_main, pwalletMain->cs_wallet); UniValue retValue; // Check number of args BOOST_CHECK_THROW(CallRPC("validateaddress"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("validateaddress toomany args"), std::runtime_error); // Wallet should be empty: std::set<libzcash::SaplingPaymentAddress> addrs; pwalletMain->GetSaplingPaymentAddresses(addrs); BOOST_CHECK(addrs.size()==0); // This Sapling address is not valid, it belongs to another network BOOST_CHECK_NO_THROW(retValue = CallRPC("validateaddress ptestsapling1nrn6exksuqtpld9gu6fwdz4hwg54h2x37gutdds89pfyg6mtjf63km45a8eare5qla45cj75vs8")); UniValue resultObj = retValue.get_obj(); bool b = find_value(resultObj, "isvalid").get_bool(); BOOST_CHECK_EQUAL(b, false); // This Sapling address is valid, but the spending key is not in this wallet BOOST_CHECK_NO_THROW(retValue = CallRPC("validateaddress ps1u87kylcmn28yclnx2uy0psnvuhs2xn608ukm6n2nshrpg2nzyu3n62ls8j77m9cgp40dx40evej")); resultObj = retValue.get_obj(); b = find_value(resultObj, "isvalid").get_bool(); BOOST_CHECK_EQUAL(b, true); BOOST_CHECK_EQUAL(find_value(resultObj, "type").get_str(), "sapling"); b = find_value(resultObj, "ismine").get_bool(); BOOST_CHECK_EQUAL(b, false); BOOST_CHECK_EQUAL(find_value(resultObj, "diversifier").get_str(), "e1fd627f1b9a8e4c7e6657"); BOOST_CHECK_EQUAL(find_value(resultObj, "diversifiedtransmissionkey").get_str(), "d35e0d0897edbd3cf02b3d2327622a14c685534dbd2d3f4f4fa3e0e56cc2f008"); } // Check if address is of given type and spendable from our wallet. void CheckHaveAddr(const libzcash::PaymentAddress& addr) { BOOST_CHECK(IsValidPaymentAddress(addr)); auto addr_of_type = boost::get<libzcash::SaplingPaymentAddress>(&addr); BOOST_ASSERT(addr_of_type != nullptr); BOOST_CHECK(pwalletMain->HaveSpendingKeyForPaymentAddress(*addr_of_type)); } BOOST_AUTO_TEST_CASE(rpc_wallet_getnewshieldedaddress) { UniValue addr; LOCK2(cs_main, pwalletMain->cs_wallet); if (!pwalletMain->HasSaplingSPKM()) { pwalletMain->SetupSPKM(false); } // No parameter defaults to sapling address addr = CallRPC("getnewshieldedaddress"); CheckHaveAddr(KeyIO::DecodePaymentAddress(addr.get_str())); // Too many arguments will throw with the help BOOST_CHECK_THROW(CallRPC("getnewshieldedaddress many args"), std::runtime_error); } BOOST_AUTO_TEST_CASE(rpc_wallet_encrypted_wallet_sapzkeys) { LOCK2(cs_main, pwalletMain->cs_wallet); UniValue retValue; int n = 100; if(!pwalletMain->HasSaplingSPKM()) { pwalletMain->SetupSPKM(false); } // wallet should currently be empty std::set<libzcash::SaplingPaymentAddress> addrs; pwalletMain->GetSaplingPaymentAddresses(addrs); BOOST_CHECK(addrs.empty()); // create keys for (int i = 0; i < n; i++) { CallRPC("getnewshieldedaddress"); } // Verify we can list the keys imported BOOST_CHECK_NO_THROW(retValue = CallRPC("listshieldedaddresses")); UniValue arr = retValue.get_array(); BOOST_CHECK((int) arr.size() == n); // Verify that the wallet encryption RPC is disabled // TODO: We don't have the experimental mode to disable the encryptwallet disable. //BOOST_CHECK_THROW(CallRPC("encryptwallet passphrase"), std::runtime_error); // Encrypt the wallet (we can't call RPC encryptwallet as that shuts down node) SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = "hello"; boost::filesystem::current_path(GetArg("-datadir","/tmp/thisshouldnothappen")); BOOST_CHECK(pwalletMain->EncryptWallet(strWalletPass)); // Verify we can still list the keys imported BOOST_CHECK_NO_THROW(retValue = CallRPC("listshieldedaddresses")); arr = retValue.get_array(); BOOST_CHECK((int) arr.size() == n); // Try to add a new key, but we can't as the wallet is locked BOOST_CHECK_THROW(CallRPC("getnewshieldedaddress"), std::runtime_error); // We can't call RPC walletpassphrase as that invokes RPCRunLater which breaks tests. // So we manually unlock. BOOST_CHECK(pwalletMain->Unlock(strWalletPass)); // Now add a key BOOST_CHECK_NO_THROW(CallRPC("getnewshieldedaddress")); // Verify the key has been added BOOST_CHECK_NO_THROW(retValue = CallRPC("listshieldedaddresses")); arr = retValue.get_array(); BOOST_CHECK((int) arr.size() == n+1); // We can't simulate over RPC the wallet closing and being reloaded // but there are tests for this in gtest. } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Test: sapling wallet import/export keys implemented.<commit_after>// Copyright (c) 2016-2020 The ZCash developers // Copyright (c) 2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet/test/wallet_test_fixture.h" #include "wallet/wallet.h" #include "rpc/server.h" #include "rpc/client.h" #include "sapling/key_io_sapling.h" #include "sapling/address.hpp" #include <unordered_set> #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> #include <boost/format.hpp> #include <boost/filesystem.hpp> #include <univalue.h> extern UniValue CallRPC(std::string args); // Implemented in rpc_tests.cpp // Remember: this method will be moved to an utility file in the short future. For now, it's in sapling_keystore_tests.cpp extern libzcash::SaplingExtendedSpendingKey GetTestMasterSaplingSpendingKey(); BOOST_FIXTURE_TEST_SUITE(sapling_rpc_wallet_tests, WalletTestingSetup) /** * This test covers RPC command validateaddress */ BOOST_AUTO_TEST_CASE(rpc_wallet_sapling_validateaddress) { SelectParams(CBaseChainParams::MAIN); LOCK2(cs_main, pwalletMain->cs_wallet); UniValue retValue; // Check number of args BOOST_CHECK_THROW(CallRPC("validateaddress"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("validateaddress toomany args"), std::runtime_error); // Wallet should be empty: std::set<libzcash::SaplingPaymentAddress> addrs; pwalletMain->GetSaplingPaymentAddresses(addrs); BOOST_CHECK(addrs.size()==0); // This Sapling address is not valid, it belongs to another network BOOST_CHECK_NO_THROW(retValue = CallRPC("validateaddress ptestsapling1nrn6exksuqtpld9gu6fwdz4hwg54h2x37gutdds89pfyg6mtjf63km45a8eare5qla45cj75vs8")); UniValue resultObj = retValue.get_obj(); bool b = find_value(resultObj, "isvalid").get_bool(); BOOST_CHECK_EQUAL(b, false); // This Sapling address is valid, but the spending key is not in this wallet BOOST_CHECK_NO_THROW(retValue = CallRPC("validateaddress ps1u87kylcmn28yclnx2uy0psnvuhs2xn608ukm6n2nshrpg2nzyu3n62ls8j77m9cgp40dx40evej")); resultObj = retValue.get_obj(); b = find_value(resultObj, "isvalid").get_bool(); BOOST_CHECK_EQUAL(b, true); BOOST_CHECK_EQUAL(find_value(resultObj, "type").get_str(), "sapling"); b = find_value(resultObj, "ismine").get_bool(); BOOST_CHECK_EQUAL(b, false); BOOST_CHECK_EQUAL(find_value(resultObj, "diversifier").get_str(), "e1fd627f1b9a8e4c7e6657"); BOOST_CHECK_EQUAL(find_value(resultObj, "diversifiedtransmissionkey").get_str(), "d35e0d0897edbd3cf02b3d2327622a14c685534dbd2d3f4f4fa3e0e56cc2f008"); } /* * This test covers RPC commands listsaplingaddresses, importsaplingkey, exportsaplingkey */ BOOST_AUTO_TEST_CASE(rpc_wallet_sapling_importexport) { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->SetupSPKM(false); UniValue retValue; int n1 = 1000; // number of times to import/export int n2 = 1000; // number of addresses to create and list // error if no args BOOST_CHECK_THROW(CallRPC("importsaplingkey"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("exportsaplingkey"), std::runtime_error); // error if too many args BOOST_CHECK_THROW(CallRPC("importsaplingkey way too many args"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("exportsaplingkey toomany args"), std::runtime_error); // error if invalid args auto sk = libzcash::SproutSpendingKey::random(); std::string prefix = std::string("importsaplingkey ") + KeyIO::EncodeSpendingKey(sk) + " yes "; BOOST_CHECK_THROW(CallRPC(prefix + "-1"), std::runtime_error); BOOST_CHECK_THROW(CallRPC(prefix + "2147483647"), std::runtime_error); // allowed, but > height of active chain tip BOOST_CHECK_THROW(CallRPC(prefix + "2147483648"), std::runtime_error); // not allowed, > int32 used for nHeight BOOST_CHECK_THROW(CallRPC(prefix + "100badchars"), std::runtime_error); // wallet should currently be empty std::set<libzcash::SaplingPaymentAddress> saplingAddrs; pwalletMain->GetSaplingPaymentAddresses(saplingAddrs); BOOST_CHECK(saplingAddrs.empty()); auto m = GetTestMasterSaplingSpendingKey(); // verify import and export key for (int i = 0; i < n1; i++) { // create a random Sapling key locally auto testSaplingSpendingKey = m.Derive(i); auto testSaplingPaymentAddress = testSaplingSpendingKey.DefaultAddress(); std::string testSaplingAddr = KeyIO::EncodePaymentAddress(testSaplingPaymentAddress); std::string testSaplingKey = KeyIO::EncodeSpendingKey(testSaplingSpendingKey); BOOST_CHECK_NO_THROW(CallRPC(std::string("importsaplingkey ") + testSaplingKey)); BOOST_CHECK_NO_THROW(retValue = CallRPC(std::string("exportsaplingkey ") + testSaplingAddr)); BOOST_CHECK_EQUAL(retValue.get_str(), testSaplingKey); } // Verify we can list the keys imported BOOST_CHECK_NO_THROW(retValue = CallRPC("listshieldedaddresses")); UniValue arr = retValue.get_array(); BOOST_CHECK((int) arr.size() == n1); // Put addresses into a set std::unordered_set<std::string> myaddrs; for (const UniValue& element : arr.getValues()) { myaddrs.insert(element.get_str()); } // Make new addresses for the set for (int i=0; i<n2; i++) { myaddrs.insert(KeyIO::EncodePaymentAddress(pwalletMain->GenerateNewSaplingZKey())); } // Verify number of addresses stored in wallet is n1+n2 int numAddrs = myaddrs.size(); BOOST_CHECK(numAddrs == n1 + n2); pwalletMain->GetSaplingPaymentAddresses(saplingAddrs); BOOST_CHECK((int) saplingAddrs.size() == numAddrs); // Ask wallet to list addresses BOOST_CHECK_NO_THROW(retValue = CallRPC("listshieldedaddresses")); arr = retValue.get_array(); BOOST_CHECK((int) arr.size() == numAddrs); // Create a set from them std::unordered_set<std::string> listaddrs; for (const UniValue& element : arr.getValues()) { listaddrs.insert(element.get_str()); } // Verify the two sets of addresses are the same BOOST_CHECK((int) listaddrs.size() == numAddrs); BOOST_CHECK(myaddrs == listaddrs); } // Check if address is of given type and spendable from our wallet. void CheckHaveAddr(const libzcash::PaymentAddress& addr) { BOOST_CHECK(IsValidPaymentAddress(addr)); auto addr_of_type = boost::get<libzcash::SaplingPaymentAddress>(&addr); BOOST_ASSERT(addr_of_type != nullptr); BOOST_CHECK(pwalletMain->HaveSpendingKeyForPaymentAddress(*addr_of_type)); } BOOST_AUTO_TEST_CASE(rpc_wallet_getnewshieldedaddress) { UniValue addr; LOCK2(cs_main, pwalletMain->cs_wallet); if (!pwalletMain->HasSaplingSPKM()) { pwalletMain->SetupSPKM(false); } // No parameter defaults to sapling address addr = CallRPC("getnewshieldedaddress"); CheckHaveAddr(KeyIO::DecodePaymentAddress(addr.get_str())); // Too many arguments will throw with the help BOOST_CHECK_THROW(CallRPC("getnewshieldedaddress many args"), std::runtime_error); } BOOST_AUTO_TEST_CASE(rpc_wallet_encrypted_wallet_sapzkeys) { LOCK2(cs_main, pwalletMain->cs_wallet); UniValue retValue; int n = 100; if(!pwalletMain->HasSaplingSPKM()) { pwalletMain->SetupSPKM(false); } // wallet should currently be empty std::set<libzcash::SaplingPaymentAddress> addrs; pwalletMain->GetSaplingPaymentAddresses(addrs); BOOST_CHECK(addrs.empty()); // create keys for (int i = 0; i < n; i++) { CallRPC("getnewshieldedaddress"); } // Verify we can list the keys imported BOOST_CHECK_NO_THROW(retValue = CallRPC("listshieldedaddresses")); UniValue arr = retValue.get_array(); BOOST_CHECK((int) arr.size() == n); // Verify that the wallet encryption RPC is disabled // TODO: We don't have the experimental mode to disable the encryptwallet disable. //BOOST_CHECK_THROW(CallRPC("encryptwallet passphrase"), std::runtime_error); // Encrypt the wallet (we can't call RPC encryptwallet as that shuts down node) SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = "hello"; boost::filesystem::current_path(GetArg("-datadir","/tmp/thisshouldnothappen")); BOOST_CHECK(pwalletMain->EncryptWallet(strWalletPass)); // Verify we can still list the keys imported BOOST_CHECK_NO_THROW(retValue = CallRPC("listshieldedaddresses")); arr = retValue.get_array(); BOOST_CHECK((int) arr.size() == n); // Try to add a new key, but we can't as the wallet is locked BOOST_CHECK_THROW(CallRPC("getnewshieldedaddress"), std::runtime_error); // We can't call RPC walletpassphrase as that invokes RPCRunLater which breaks tests. // So we manually unlock. BOOST_CHECK(pwalletMain->Unlock(strWalletPass)); // Now add a key BOOST_CHECK_NO_THROW(CallRPC("getnewshieldedaddress")); // Verify the key has been added BOOST_CHECK_NO_THROW(retValue = CallRPC("listshieldedaddresses")); arr = retValue.get_array(); BOOST_CHECK((int) arr.size() == n+1); // We can't simulate over RPC the wallet closing and being reloaded // but there are tests for this in gtest. } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* * DepthSense SDK for Python and SimpleCV * ----------------------------------------------------------------------------- * file: depthsense.cxx * author: Abdi Dahir * modified: May 9 2014 * vim: set fenc=utf-8:ts=4:sw=4:expandtab: * * Python hooks happen here. This is the main file. * ----------------------------------------------------------------------------- */ // Python Module includes #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <numpy/arrayobject.h> // MS completly untested #ifdef _MSC_VER #include <windows.h> #endif // C includes #include <stdio.h> #ifndef _MSC_VER #include <stdint.h> #include <unistd.h> #endif #include <sys/types.h> #include <stdlib.h> #include <string.h> // C++ includes #include <exception> #include <iostream> #include <fstream> //#include <thread> // Application includes #include "initdepthsense.h" // #include "imageproccessing.h" // internal map copies uint8_t colourMapClone[640*480*3]; int16_t depthMapClone[320*240]; int16_t vertexMapClone[320*240*3]; float accelMapClone[3]; float uvMapClone[320*240*2]; float vertexFMapClone[320*240*3]; uint8_t syncMapClone[320*240*3]; int16_t nPrintMap[320*240*3]; int16_t vPrintMap[320*240*3]; uint8_t depthColouredMapClone[320*240*3]; int16_t dConvolveResultClone[320*240]; uint8_t cConvolveResultClone[640*480]; uint8_t greyResultClone[640*480]; int16_t normalResultClone[320*240*3]; using namespace std; // Minor processing (kind of hard to move) // static void saveMap(char *map, char* file) // { // (void) map; // //TODO: Make this a not shitty and specific function // //TODO: memcpy and loop based on name in map? // ofstream f; // f.open(file); // cout << "Writing to file: " << file << endl; // int16_t vx; int16_t vy; int16_t vz; // // int16_t nx; int16_t ny; int16_t nz; // for(int i=0; i < dH; i++) { // for(int j=0; j < dW; j++) { // vx = vPrintMap[i*dW*3 + j*3 + 0]; // vy = vPrintMap[i*dW*3 + j*3 + 1]; // vz = vPrintMap[i*dW*3 + j*3 + 2]; // if (vz != 32001) { // f << vx << "," << vy << "," << vz << endl; // } // } // } // cout << "Complete!" << endl; // f.close(); // } void buildSyncMap() { int ci, cj; uint8_t colx; uint8_t coly; uint8_t colz; float uvx; float uvy; for(int i=0; i < dH; i++) { for(int j=0; j < dW; j++) { uvx = uvMapClone[i*dW*2 + j*2 + 0]; uvy = uvMapClone[i*dW*2 + j*2 + 1]; colx = 0; coly = 0; colz = 0; if((uvx > 0 && uvx < 1 && uvy > 0 && uvy < 1) && (depthMapClone[i*dW + j] < 32000)){ ci = (int) (uvy * ((float) cH)); cj = (int) (uvx * ((float) cW)); colx = colourMapClone[ci*cW*3 + cj*3 + 0]; coly = colourMapClone[ci*cW*3 + cj*3 + 1]; colz = colourMapClone[ci*cW*3 + cj*3 + 2]; } syncMapClone[i*dW*3 + j*3 + 0] = colx; syncMapClone[i*dW*3 + j*3 + 1] = coly; syncMapClone[i*dW*3 + j*3 + 2] = colz; } } } void buildDepthColoured() { for(int i=0; i < dH; i++) { for(int j=0; j < dW; j++) { //TODO: Make this not complete shit //colour = ((uint32_t)depthCMap[i*dW + j]) * 524; // convert approx 2^15 bits of data to 2^24 bits //colour = 16777216.0*(((double)depthCMap[i*dW + j])/31999.0); // 2^24 * zval/~2^15(zrange) //cout << depth << " " << depthCMap[i*dW + j] << endl; //depthColouredMap[i*dW*3 + j*3 + 0] = (uint8_t) ((colour << (32 - 8*1)) >> (32 - 8)); //depthColouredMap[i*dW*3 + j*3 + 1] = (uint8_t) ((colour << (32 - 8*2)) >> (32 - 8)); //depthColouredMap[i*dW*3 + j*3 + 2] = (uint8_t) ((colour << (32 - 8*3)) >> (32 - 8)); depthColouredMap[i*dW*3 + j*3 + 0] = (uint8_t) (((depthCMap[i*dW + j] << (16 - 5*1)) >> (16 - 5)) << 3); depthColouredMap[i*dW*3 + j*3 + 1] = (uint8_t) (((depthCMap[i*dW + j] << (16 - 5*2)) >> (16 - 5)) << 3); depthColouredMap[i*dW*3 + j*3 + 2] = (uint8_t) (((depthCMap[i*dW + j] << (16 - 5*3)) >> (16 - 5)) << 3); } } } // Python Callbacks static PyObject *getColour(PyObject *self, PyObject *args) { npy_intp dims[3] = {cH, cW, 3}; memcpy(colourMapClone, colourFullMap, cshmsz*3); return PyArray_SimpleNewFromData(3, dims, NPY_UINT8, colourMapClone); } static PyObject *getDepth(PyObject *self, PyObject *args) { npy_intp dims[2] = {dH, dW}; memcpy(depthMapClone, depthFullMap, dshmsz); return PyArray_SimpleNewFromData(2, dims, NPY_INT16, depthMapClone); } // static PyObject *getGreyScale(PyObject *self, PyObject *args) // { // npy_intp dims[2] = {cH, cW}; // memcpy(greyColourMap, colourFullMap, cshmsz*3); // memset(greyResult, 0, cshmsz); // toGreyScale(0.2126, 0.7152, 0.0722); // memcpy(greyResultClone, greyResult, cshmsz); // return PyArray_SimpleNewFromData(2, dims, NPY_UINT8, greyResultClone); // } /* TODO: extract this bad boy */ static PyObject *getDepthColoured(PyObject *self, PyObject *args) { npy_intp dims[3] = {dH, dW, 3}; memcpy(depthCMap, depthFullMap, dshmsz); memset(depthColouredMap, 0, hshmsz*3); memcpy(depthColouredMapClone, depthColouredMap, hshmsz*3); return PyArray_SimpleNewFromData(3, dims, NPY_UINT8, depthColouredMapClone); } static PyObject *getAccel(PyObject *self, PyObject *args) { npy_intp dims[1] = {3}; memcpy(accelMapClone, accelFullMap, 3*sizeof(float)); return PyArray_SimpleNewFromData(1, dims, NPY_FLOAT32, accelMapClone); } static PyObject *getVertex(PyObject *self, PyObject *args) { npy_intp dims[3] = {dH, dW, 3}; memcpy(vertexMapClone, vertexFullMap, vshmsz*3); return PyArray_SimpleNewFromData(3, dims, NPY_INT16, vertexMapClone); } static PyObject *getVertexFP(PyObject *self, PyObject *args) { npy_intp dims[3] = {dH, dW, 3}; memcpy(vertexFMapClone, vertexFFullMap, ushmsz*3); return PyArray_SimpleNewFromData(3, dims, NPY_FLOAT32, vertexFMapClone); } static PyObject *getUV(PyObject *self, PyObject *args) { npy_intp dims[3] = {dH, dW, 2}; memcpy(uvMapClone, uvFullMap, ushmsz*2); return PyArray_SimpleNewFromData(3, dims, NPY_FLOAT32, uvMapClone); } static PyObject *getSync(PyObject *self, PyObject *args) { npy_intp dims[3] = {dH, dW, 3}; memcpy(uvMapClone, uvFullMap, ushmsz*2); memcpy(colourMapClone, colourFullMap, cshmsz*3); memcpy(depthMapClone, depthFullMap, dshmsz); buildSyncMap(); return PyArray_SimpleNewFromData(3, dims, NPY_UINT8, syncMapClone); } static PyObject *initDS(PyObject *self, PyObject *args) { initds(); return Py_None; } static PyObject *killDS(PyObject *self, PyObject *args) { killds(); return Py_None; } // /* TODO: Make this actually work, refer to checkHood.cxx */ // static PyObject *getBlob(PyObject *self, PyObject *args) // { // int i; // int j; // double thresh_high; // double thresh_low; // if (!PyArg_ParseTuple(args, "iidd", &i, &j, &thresh_high, &thresh_low)) // return NULL; // //npy_intp dims[2] = {dH, dW}; // //memcpy(blobMap, depthFullMap, dshmsz); // // SHUTDOWN findBlob(i, j, thresh_high, thresh_low); // //memcpy(blobResultClone, blobResult, dshmsz); // //return PyArray_SimpleNewFromData(2, dims, NPY_INT16, blobResultClone); // Py_RETURN_NONE; // } // static PyObject *convolveDepth(PyObject *self, PyObject *args) // { // char *kern; // int repeat; // double bias; // if (!PyArg_ParseTuple(args, "sid", &kern, &repeat, &bias)) // return NULL; // memcpy(dConvolveMap, depthFullMap, dshmsz); // for(int i = 0; i < repeat; i++) { // applyKernelDepth(kern, dW, dH, bias); // memcpy(dConvolveMap, dConvolveResult, dshmsz); // } // npy_intp dims[2] = {dH, dW}; // memcpy(dConvolveResultClone, dConvolveResult, dshmsz); // return PyArray_SimpleNewFromData(2, dims, NPY_INT16, dConvolveResultClone); // } // static PyObject *convolveColour(PyObject *self, PyObject *args) // { // char *kern; // int repeat; // double bias; // if (!PyArg_ParseTuple(args, "sid", &kern, &repeat, &bias)) // return NULL; // memcpy(greyColourMap, colourFullMap, cshmsz*3); // memset(greyResult, 0, cshmsz); // toGreyScale(0.2126, 0.7152, 0.0722); // memcpy(cConvolveMap, greyResult, cshmsz); // for(int i = 0; i < repeat; i++) { // applyKernelColour(kern, cW, cH, bias); // memcpy(cConvolveMap, cConvolveResult, cshmsz); // } // npy_intp dims[2] = {cH, cW}; // memcpy(cConvolveResultClone, cConvolveResult, cshmsz); // return PyArray_SimpleNewFromData(2, dims, NPY_UINT8, cConvolveResultClone); // } // /* TODO: Make this only vertex map */ // static PyObject *saveMap(PyObject *self, PyObject *args) // { // char *map; // char *file; // if (!PyArg_ParseTuple(args, "ss", &map, &file)) // return NULL; // /* TODO: choose if this part can become general or not */ // memcpy(vPrintMap, vertexFullMap, vshmsz*3); // memcpy(nPrintMap, normalResult, dshmsz*3); // saveMap(map, file); // Py_RETURN_NONE; // } // static PyObject *getNormal(PyObject *self, PyObject *args) // { // memcpy(normalMap, vertexFullMap, vshmsz*3); // double bias = 0.5; // char * kern = (char*)"placeholder"; // computeDifferential(kern, bias); // applies sobel kernel to each plane // crossMaps(); // cross product on three planes, store in normalMap result // npy_intp dims[3] = {dH, dW, 3}; // memcpy(normalResultClone, normalResult, dshmsz*3); // return PyArray_SimpleNewFromData(3, dims, NPY_INT16, normalResultClone); // } static PyMethodDef DepthSenseMethods[] = { // GET MAPS {"getDepthMap", getDepth, METH_VARARGS, "Get Depth Map"}, {"getDepthColouredMap", getDepthColoured, METH_VARARGS, "Get Depth Coloured Map"}, {"getColourMap", getColour, METH_VARARGS, "Get Colour Map"}, // {"getGreyScaleMap", getGreyScale, METH_VARARGS, "Get Grey Scale Colour Map"}, {"getVertices", getVertex, METH_VARARGS, "Get Vertex Map"}, {"getVerticesFP", getVertexFP, METH_VARARGS, "Get Floating Point Vertex Map"}, // {"getNormalMap", getNormal, METH_VARARGS, "Get Normal Map"}, {"getUVMap", getUV, METH_VARARGS, "Get UV Map"}, {"getSyncMap", getSync, METH_VARARGS, "Get Colour Overlay Map"}, {"getAcceleration", getAccel, METH_VARARGS, "Get Acceleration"}, // CREATE MODULE {"initPySenz3d", initDS, METH_VARARGS, "Init DepthSense"}, {"killDepthSense", killDS, METH_VARARGS, "Kill DepthSense"}, // PROCESS MAPS // {"getBlobAt", getBlob, METH_VARARGS, "Find blob at location in the depth map"}, // {"convolveDepthMap", convolveDepth, METH_VARARGS, "Apply specified kernel to the depth map"}, // {"convolveColourMap", convolveColour, METH_VARARGS, "Apply specified kernel to the image"}, // SAVE MAPS // {"saveMap", saveMap, METH_VARARGS, "Save the specified map"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC initpysenz3d(void) { (void) Py_InitModule("pysenz3d", DepthSenseMethods); // Clean up forked process, attach it to the python exit hook // (void) Py_AtExit(killds); // force the user to clean up module manually? import_array(); } int main(int argc, char* argv[]) { /* Pass argv[0] to the Python interpreter */ Py_SetProgramName((char *)"DepthSense"); /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initpysenz3d(); //initds(); //for testing return 0; } <commit_msg>remove commented-out code<commit_after>/* * DepthSense SDK for Python and SimpleCV * ----------------------------------------------------------------------------- * file: depthsense.cxx * author: Abdi Dahir * modified: May 9 2014 * vim: set fenc=utf-8:ts=4:sw=4:expandtab: * * Python hooks happen here. This is the main file. * ----------------------------------------------------------------------------- */ // Python Module includes #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <numpy/arrayobject.h> // MS completly untested #ifdef _MSC_VER #include <windows.h> #endif // C includes #include <stdio.h> #ifndef _MSC_VER #include <stdint.h> #include <unistd.h> #endif #include <sys/types.h> #include <stdlib.h> #include <string.h> // C++ includes #include <exception> #include <iostream> #include <fstream> //#include <thread> // Application includes #include "initdepthsense.h" // internal map copies uint8_t colourMapClone[640*480*3]; int16_t depthMapClone[320*240]; int16_t vertexMapClone[320*240*3]; float accelMapClone[3]; float uvMapClone[320*240*2]; float vertexFMapClone[320*240*3]; uint8_t syncMapClone[320*240*3]; int16_t nPrintMap[320*240*3]; int16_t vPrintMap[320*240*3]; uint8_t depthColouredMapClone[320*240*3]; int16_t dConvolveResultClone[320*240]; uint8_t cConvolveResultClone[640*480]; uint8_t greyResultClone[640*480]; int16_t normalResultClone[320*240*3]; using namespace std; void buildSyncMap() { int ci, cj; uint8_t colx; uint8_t coly; uint8_t colz; float uvx; float uvy; for(int i=0; i < dH; i++) { for(int j=0; j < dW; j++) { uvx = uvMapClone[i*dW*2 + j*2 + 0]; uvy = uvMapClone[i*dW*2 + j*2 + 1]; colx = 0; coly = 0; colz = 0; if((uvx > 0 && uvx < 1 && uvy > 0 && uvy < 1) && (depthMapClone[i*dW + j] < 32000)){ ci = (int) (uvy * ((float) cH)); cj = (int) (uvx * ((float) cW)); colx = colourMapClone[ci*cW*3 + cj*3 + 0]; coly = colourMapClone[ci*cW*3 + cj*3 + 1]; colz = colourMapClone[ci*cW*3 + cj*3 + 2]; } syncMapClone[i*dW*3 + j*3 + 0] = colx; syncMapClone[i*dW*3 + j*3 + 1] = coly; syncMapClone[i*dW*3 + j*3 + 2] = colz; } } } void buildDepthColoured() { for(int i=0; i < dH; i++) { for(int j=0; j < dW; j++) { //TODO: Make this not complete shit //colour = ((uint32_t)depthCMap[i*dW + j]) * 524; // convert approx 2^15 bits of data to 2^24 bits //colour = 16777216.0*(((double)depthCMap[i*dW + j])/31999.0); // 2^24 * zval/~2^15(zrange) //cout << depth << " " << depthCMap[i*dW + j] << endl; //depthColouredMap[i*dW*3 + j*3 + 0] = (uint8_t) ((colour << (32 - 8*1)) >> (32 - 8)); //depthColouredMap[i*dW*3 + j*3 + 1] = (uint8_t) ((colour << (32 - 8*2)) >> (32 - 8)); //depthColouredMap[i*dW*3 + j*3 + 2] = (uint8_t) ((colour << (32 - 8*3)) >> (32 - 8)); depthColouredMap[i*dW*3 + j*3 + 0] = (uint8_t) (((depthCMap[i*dW + j] << (16 - 5*1)) >> (16 - 5)) << 3); depthColouredMap[i*dW*3 + j*3 + 1] = (uint8_t) (((depthCMap[i*dW + j] << (16 - 5*2)) >> (16 - 5)) << 3); depthColouredMap[i*dW*3 + j*3 + 2] = (uint8_t) (((depthCMap[i*dW + j] << (16 - 5*3)) >> (16 - 5)) << 3); } } } // Python Callbacks static PyObject *getColour(PyObject *self, PyObject *args) { npy_intp dims[3] = {cH, cW, 3}; memcpy(colourMapClone, colourFullMap, cshmsz*3); return PyArray_SimpleNewFromData(3, dims, NPY_UINT8, colourMapClone); } static PyObject *getDepth(PyObject *self, PyObject *args) { npy_intp dims[2] = {dH, dW}; memcpy(depthMapClone, depthFullMap, dshmsz); return PyArray_SimpleNewFromData(2, dims, NPY_INT16, depthMapClone); } /* TODO: extract this bad boy */ // DOESNT WORK static PyObject *getDepthColoured(PyObject *self, PyObject *args) { npy_intp dims[3] = {dH, dW, 3}; memcpy(depthCMap, depthFullMap, dshmsz); memset(depthColouredMap, 0, hshmsz*3); memcpy(depthColouredMapClone, depthColouredMap, hshmsz*3); return PyArray_SimpleNewFromData(3, dims, NPY_UINT8, depthColouredMapClone); } static PyObject *getAccel(PyObject *self, PyObject *args) { npy_intp dims[1] = {3}; memcpy(accelMapClone, accelFullMap, 3*sizeof(float)); return PyArray_SimpleNewFromData(1, dims, NPY_FLOAT32, accelMapClone); } static PyObject *getVertex(PyObject *self, PyObject *args) { npy_intp dims[3] = {dH, dW, 3}; memcpy(vertexMapClone, vertexFullMap, vshmsz*3); return PyArray_SimpleNewFromData(3, dims, NPY_INT16, vertexMapClone); } static PyObject *getVertexFP(PyObject *self, PyObject *args) { npy_intp dims[3] = {dH, dW, 3}; memcpy(vertexFMapClone, vertexFFullMap, ushmsz*3); return PyArray_SimpleNewFromData(3, dims, NPY_FLOAT32, vertexFMapClone); } static PyObject *getUV(PyObject *self, PyObject *args) { npy_intp dims[3] = {dH, dW, 2}; memcpy(uvMapClone, uvFullMap, ushmsz*2); return PyArray_SimpleNewFromData(3, dims, NPY_FLOAT32, uvMapClone); } static PyObject *getSync(PyObject *self, PyObject *args) { npy_intp dims[3] = {dH, dW, 3}; memcpy(uvMapClone, uvFullMap, ushmsz*2); memcpy(colourMapClone, colourFullMap, cshmsz*3); memcpy(depthMapClone, depthFullMap, dshmsz); buildSyncMap(); return PyArray_SimpleNewFromData(3, dims, NPY_UINT8, syncMapClone); } static PyObject *initDS(PyObject *self, PyObject *args) { initds(); return Py_None; } static PyObject *killDS(PyObject *self, PyObject *args) { killds(); return Py_None; } static PyMethodDef DepthSenseMethods[] = { // GET MAPS {"getDepthMap", getDepth, METH_VARARGS, "Get Depth Map"}, {"getDepthColouredMap", getDepthColoured, METH_VARARGS, "Get Depth Coloured Map"}, {"getColourMap", getColour, METH_VARARGS, "Get Colour Map"}, // {"getGreyScaleMap", getGreyScale, METH_VARARGS, "Get Grey Scale Colour Map"}, {"getVertices", getVertex, METH_VARARGS, "Get Vertex Map"}, {"getVerticesFP", getVertexFP, METH_VARARGS, "Get Floating Point Vertex Map"}, // {"getNormalMap", getNormal, METH_VARARGS, "Get Normal Map"}, {"getUVMap", getUV, METH_VARARGS, "Get UV Map"}, {"getSyncMap", getSync, METH_VARARGS, "Get Colour Overlay Map"}, {"getAcceleration", getAccel, METH_VARARGS, "Get Acceleration"}, // CREATE MODULE {"initPySenz3d", initDS, METH_VARARGS, "Init DepthSense"}, {"killDepthSense", killDS, METH_VARARGS, "Kill DepthSense"}, // PROCESS MAPS // {"getBlobAt", getBlob, METH_VARARGS, "Find blob at location in the depth map"}, // {"convolveDepthMap", convolveDepth, METH_VARARGS, "Apply specified kernel to the depth map"}, // {"convolveColourMap", convolveColour, METH_VARARGS, "Apply specified kernel to the image"}, // SAVE MAPS // {"saveMap", saveMap, METH_VARARGS, "Save the specified map"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC initpysenz3d(void) { (void) Py_InitModule("pysenz3d", DepthSenseMethods); // Clean up forked process, attach it to the python exit hook // (void) Py_AtExit(killds); // force the user to clean up module manually? import_array(); } int main(int argc, char* argv[]) { /* Pass argv[0] to the Python interpreter */ Py_SetProgramName((char *)"DepthSense"); /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initpysenz3d(); //initds(); //for testing return 0; } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * 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 <assert.h> #include <stdlib.h> #include <limits.h> #include <iostream> #include "glproc.hpp" #include "glws.hpp" #include "glws_xlib.hpp" namespace glws { static const char *extensions = 0; static bool has_GLX_ARB_create_context = false; static bool has_GLX_ARB_create_context_profile = false; static bool has_GLX_EXT_create_context_es_profile = false; static bool has_GLX_EXT_create_context_es2_profile = false; class GlxVisual : public Visual { public: GLXFBConfig fbconfig; XVisualInfo *visinfo; GlxVisual(Profile prof) : Visual(prof), fbconfig(0), visinfo(0) {} ~GlxVisual() { XFree(visinfo); } }; class GlxDrawable : public Drawable { public: Window window; bool ever_current; GlxDrawable(const Visual *vis, int w, int h, bool pbuffer) : Drawable(vis, w, h, pbuffer), ever_current(false) { XVisualInfo *visinfo = static_cast<const GlxVisual *>(visual)->visinfo; const char *name = "glretrace"; window = createWindow(visinfo, name, width, height); glXWaitX(); } ~GlxDrawable() { XDestroyWindow(display, window); } void resize(int w, int h) { if (w == width && h == height) { return; } glXWaitGL(); // We need to ensure that pending events are processed here, and XSync // with discard = True guarantees that, but it appears the limited // event processing we do so far is sufficient //XSync(display, True); Drawable::resize(w, h); resizeWindow(window, w, h); glXWaitX(); } void show(void) { if (visible) { return; } glXWaitGL(); showWindow(window); glXWaitX(); Drawable::show(); } void copySubBuffer(int x, int y, int width, int height) { glXCopySubBufferMESA(display, window, x, y, width, height); processKeys(window); } void swapBuffers(void) { if (ever_current) { // The window has been bound to a context at least once glXSwapBuffers(display, window); } else { // Don't call glXSwapBuffers on this window to avoid an // (untrappable) X protocol error with NVIDIA's driver. std::cerr << "warning: attempt to issue SwapBuffers on unbound window " " - skipping.\n"; } processKeys(window); } }; class GlxContext : public Context { public: GLXContext context; GlxContext(const Visual *vis, GLXContext ctx) : Context(vis), context(ctx) {} ~GlxContext() { glXDestroyContext(display, context); } }; #ifndef GLXBadFBConfig #define GLXBadFBConfig 9 #endif static int errorBase = INT_MIN; static int eventBase = INT_MIN; static int (*oldErrorHandler)(Display *, XErrorEvent *) = NULL; static int errorHandler(Display *dpy, XErrorEvent *error) { if (error->error_code == errorBase + GLXBadFBConfig) { // Ignore, as we handle these. return 0; } return oldErrorHandler(dpy, error); } void init(void) { initX(); int major = 0, minor = 0; if (!glXQueryVersion(display, &major, &minor)) { std::cerr << "error: failed to obtain GLX version\n"; exit(1); } const int requiredMajor = 1, requiredMinor = 3; if (major < requiredMajor || (major == requiredMajor && minor < requiredMinor)) { std::cerr << "error: GLX version " << requiredMajor << "." << requiredMinor << " required, but got version " << major << "." << minor << "\n"; exit(1); } glXQueryExtension(display, &errorBase, &eventBase); oldErrorHandler = XSetErrorHandler(errorHandler); extensions = glXQueryExtensionsString(display, screen); #define CHECK_EXTENSION(name) \ has_##name = checkExtension(#name, extensions) CHECK_EXTENSION(GLX_ARB_create_context); CHECK_EXTENSION(GLX_ARB_create_context_profile); CHECK_EXTENSION(GLX_EXT_create_context_es_profile); CHECK_EXTENSION(GLX_EXT_create_context_es2_profile); #undef CHECK_EXTENSION } void cleanup(void) { XSetErrorHandler(oldErrorHandler); oldErrorHandler = NULL; cleanupX(); } Visual * createVisual(bool doubleBuffer, unsigned samples, Profile profile) { GlxVisual *visual = new GlxVisual(profile); Attributes<int> attribs; attribs.add(GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT); attribs.add(GLX_RENDER_TYPE, GLX_RGBA_BIT); attribs.add(GLX_RED_SIZE, 1); attribs.add(GLX_GREEN_SIZE, 1); attribs.add(GLX_BLUE_SIZE, 1); attribs.add(GLX_ALPHA_SIZE, 1); attribs.add(GLX_DOUBLEBUFFER, doubleBuffer ? GL_TRUE : GL_FALSE); attribs.add(GLX_DEPTH_SIZE, 1); attribs.add(GLX_STENCIL_SIZE, 1); if (samples > 1) { attribs.add(GLX_SAMPLE_BUFFERS, 1); attribs.add(GLX_SAMPLES_ARB, samples); } attribs.end(); int num_configs = 0; GLXFBConfig * fbconfigs; fbconfigs = glXChooseFBConfig(display, screen, attribs, &num_configs); if (!num_configs || !fbconfigs) { return NULL; } visual->fbconfig = fbconfigs[0]; assert(visual->fbconfig); visual->visinfo = glXGetVisualFromFBConfig(display, visual->fbconfig); assert(visual->visinfo); return visual; } Drawable * createDrawable(const Visual *visual, int width, int height, bool pbuffer) { return new GlxDrawable(visual, width, height, pbuffer); } Context * createContext(const Visual *_visual, Context *shareContext, bool debug) { const GlxVisual *visual = static_cast<const GlxVisual *>(_visual); Profile profile = visual->profile; GLXContext share_context = NULL; GLXContext context; if (shareContext) { share_context = static_cast<GlxContext*>(shareContext)->context; } if (has_GLX_ARB_create_context) { Attributes<int> attribs; attribs.add(GLX_RENDER_TYPE, GLX_RGBA_TYPE); int contextFlags = 0; if (profile.api == glprofile::API_GL) { attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, profile.major); attribs.add(GLX_CONTEXT_MINOR_VERSION_ARB, profile.minor); if (profile.versionGreaterOrEqual(3, 2)) { if (!has_GLX_ARB_create_context_profile) { std::cerr << "error: GLX_ARB_create_context_profile not supported\n"; return NULL; } int profileMask = profile.core ? GLX_CONTEXT_CORE_PROFILE_BIT_ARB : GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, profileMask); if (profile.forwardCompatible) { contextFlags |= GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; } } } else if (profile.api == glprofile::API_GLES) { if (has_GLX_EXT_create_context_es_profile) { attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES_PROFILE_BIT_EXT); attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, profile.major); attribs.add(GLX_CONTEXT_MINOR_VERSION_ARB, profile.minor); } else if (profile.major < 2) { std::cerr << "error: " << profile << " requested but GLX_EXT_create_context_es_profile not supported\n"; return NULL; } else if (has_GLX_EXT_create_context_es2_profile) { assert(profile.major >= 2); if (profile.major != 2 || profile.minor != 0) { // We might still get a ES 3.0 context later (in particular Mesa does this) std::cerr << "warning: " << profile << " requested but GLX_EXT_create_context_es_profile not supported\n"; } attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES2_PROFILE_BIT_EXT); attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, 2); attribs.add(GLX_CONTEXT_MINOR_VERSION_ARB, 0); } else { std::cerr << "warning: " << profile << " requested but GLX_EXT_create_context_es_profile or GLX_EXT_create_context_es2_profile not supported\n"; } } else { assert(0); } if (debug) { contextFlags |= GLX_CONTEXT_DEBUG_BIT_ARB; } if (contextFlags) { attribs.add(GLX_CONTEXT_FLAGS_ARB, contextFlags); } attribs.end(); context = glXCreateContextAttribsARB(display, visual->fbconfig, share_context, True, attribs); if (!context && debug) { // XXX: Mesa has problems with GLX_CONTEXT_DEBUG_BIT_ARB with // OpenGL ES contexts, so retry without it return createContext(_visual, shareContext, false); } } else { if (profile.api != glprofile::API_GL || profile.core) { return NULL; } context = glXCreateNewContext(display, visual->fbconfig, GLX_RGBA_TYPE, share_context, True); } if (!context) { return NULL; } return new GlxContext(visual, context); } bool makeCurrentInternal(Drawable *drawable, Context *context) { if (!drawable || !context) { return glXMakeCurrent(display, None, NULL); } else { GlxDrawable *glxDrawable = static_cast<GlxDrawable *>(drawable); GlxContext *glxContext = static_cast<GlxContext *>(context); glxDrawable->ever_current = true; return glXMakeCurrent(display, glxDrawable->window, glxContext->context); } } } /* namespace glws */ <commit_msg>glws: add GLX PBuffer support<commit_after>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * 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 <assert.h> #include <stdlib.h> #include <limits.h> #include <iostream> #include "glproc.hpp" #include "glws.hpp" #include "glws_xlib.hpp" namespace glws { static const char *extensions = 0; static bool has_GLX_ARB_create_context = false; static bool has_GLX_ARB_create_context_profile = false; static bool has_GLX_EXT_create_context_es_profile = false; static bool has_GLX_EXT_create_context_es2_profile = false; class GlxVisual : public Visual { public: GLXFBConfig fbconfig; XVisualInfo *visinfo; GlxVisual(Profile prof) : Visual(prof), fbconfig(0), visinfo(0) {} ~GlxVisual() { XFree(visinfo); } }; class GlxDrawable : public Drawable { public: Window window; bool ever_current; GlxDrawable(const Visual *vis, int w, int h, const glws::pbuffer_info *pbInfo) : Drawable(vis, w, h, pbInfo ? true : false), ever_current(false) { const GlxVisual *glxvisual = static_cast<const GlxVisual *>(visual); XVisualInfo *visinfo = glxvisual->visinfo; const char *name = "glretrace"; if (pbInfo) { window = createPbuffer(display, glxvisual, pbInfo, w, h); } else { window = createWindow(visinfo, name, width, height); } glXWaitX(); } ~GlxDrawable() { XDestroyWindow(display, window); } void resize(int w, int h) { if (w == width && h == height) { return; } glXWaitGL(); // We need to ensure that pending events are processed here, and XSync // with discard = True guarantees that, but it appears the limited // event processing we do so far is sufficient //XSync(display, True); Drawable::resize(w, h); resizeWindow(window, w, h); glXWaitX(); } void show(void) { if (visible) { return; } glXWaitGL(); showWindow(window); glXWaitX(); Drawable::show(); } void copySubBuffer(int x, int y, int width, int height) { glXCopySubBufferMESA(display, window, x, y, width, height); processKeys(window); } void swapBuffers(void) { assert(!pbuffer); if (ever_current) { // The window has been bound to a context at least once glXSwapBuffers(display, window); } else { // Don't call glXSwapBuffers on this window to avoid an // (untrappable) X protocol error with NVIDIA's driver. std::cerr << "warning: attempt to issue SwapBuffers on unbound window " " - skipping.\n"; } processKeys(window); } private: Window createPbuffer(Display *dpy, const GlxVisual *visinfo, const glws::pbuffer_info *pbInfo, int w, int h); }; class GlxContext : public Context { public: GLXContext context; GlxContext(const Visual *vis, GLXContext ctx) : Context(vis), context(ctx) {} ~GlxContext() { glXDestroyContext(display, context); } }; #ifndef GLXBadFBConfig #define GLXBadFBConfig 9 #endif static int errorBase = INT_MIN; static int eventBase = INT_MIN; static int (*oldErrorHandler)(Display *, XErrorEvent *) = NULL; static int errorHandler(Display *dpy, XErrorEvent *error) { if (error->error_code == errorBase + GLXBadFBConfig) { // Ignore, as we handle these. return 0; } return oldErrorHandler(dpy, error); } void init(void) { initX(); int major = 0, minor = 0; if (!glXQueryVersion(display, &major, &minor)) { std::cerr << "error: failed to obtain GLX version\n"; exit(1); } const int requiredMajor = 1, requiredMinor = 3; if (major < requiredMajor || (major == requiredMajor && minor < requiredMinor)) { std::cerr << "error: GLX version " << requiredMajor << "." << requiredMinor << " required, but got version " << major << "." << minor << "\n"; exit(1); } glXQueryExtension(display, &errorBase, &eventBase); oldErrorHandler = XSetErrorHandler(errorHandler); extensions = glXQueryExtensionsString(display, screen); #define CHECK_EXTENSION(name) \ has_##name = checkExtension(#name, extensions) CHECK_EXTENSION(GLX_ARB_create_context); CHECK_EXTENSION(GLX_ARB_create_context_profile); CHECK_EXTENSION(GLX_EXT_create_context_es_profile); CHECK_EXTENSION(GLX_EXT_create_context_es2_profile); #undef CHECK_EXTENSION } void cleanup(void) { XSetErrorHandler(oldErrorHandler); oldErrorHandler = NULL; cleanupX(); } Visual * createVisual(bool doubleBuffer, unsigned samples, Profile profile) { GlxVisual *visual = new GlxVisual(profile); Attributes<int> attribs; attribs.add(GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT); attribs.add(GLX_RENDER_TYPE, GLX_RGBA_BIT); attribs.add(GLX_RED_SIZE, 1); attribs.add(GLX_GREEN_SIZE, 1); attribs.add(GLX_BLUE_SIZE, 1); attribs.add(GLX_ALPHA_SIZE, 1); attribs.add(GLX_DOUBLEBUFFER, doubleBuffer ? GL_TRUE : GL_FALSE); attribs.add(GLX_DEPTH_SIZE, 1); attribs.add(GLX_STENCIL_SIZE, 1); if (samples > 1) { attribs.add(GLX_SAMPLE_BUFFERS, 1); attribs.add(GLX_SAMPLES_ARB, samples); } attribs.end(); int num_configs = 0; GLXFBConfig * fbconfigs; fbconfigs = glXChooseFBConfig(display, screen, attribs, &num_configs); if (!num_configs || !fbconfigs) { return NULL; } visual->fbconfig = fbconfigs[0]; assert(visual->fbconfig); visual->visinfo = glXGetVisualFromFBConfig(display, visual->fbconfig); assert(visual->visinfo); return visual; } Drawable * createDrawable(const Visual *visual, int width, int height, bool pbuffer) { return new GlxDrawable(visual, width, height, pbuffer); } Context * createContext(const Visual *_visual, Context *shareContext, bool debug) { const GlxVisual *visual = static_cast<const GlxVisual *>(_visual); Profile profile = visual->profile; GLXContext share_context = NULL; GLXContext context; if (shareContext) { share_context = static_cast<GlxContext*>(shareContext)->context; } if (has_GLX_ARB_create_context) { Attributes<int> attribs; attribs.add(GLX_RENDER_TYPE, GLX_RGBA_TYPE); int contextFlags = 0; if (profile.api == glprofile::API_GL) { attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, profile.major); attribs.add(GLX_CONTEXT_MINOR_VERSION_ARB, profile.minor); if (profile.versionGreaterOrEqual(3, 2)) { if (!has_GLX_ARB_create_context_profile) { std::cerr << "error: GLX_ARB_create_context_profile not supported\n"; return NULL; } int profileMask = profile.core ? GLX_CONTEXT_CORE_PROFILE_BIT_ARB : GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, profileMask); if (profile.forwardCompatible) { contextFlags |= GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; } } } else if (profile.api == glprofile::API_GLES) { if (has_GLX_EXT_create_context_es_profile) { attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES_PROFILE_BIT_EXT); attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, profile.major); attribs.add(GLX_CONTEXT_MINOR_VERSION_ARB, profile.minor); } else if (profile.major < 2) { std::cerr << "error: " << profile << " requested but GLX_EXT_create_context_es_profile not supported\n"; return NULL; } else if (has_GLX_EXT_create_context_es2_profile) { assert(profile.major >= 2); if (profile.major != 2 || profile.minor != 0) { // We might still get a ES 3.0 context later (in particular Mesa does this) std::cerr << "warning: " << profile << " requested but GLX_EXT_create_context_es_profile not supported\n"; } attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES2_PROFILE_BIT_EXT); attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, 2); attribs.add(GLX_CONTEXT_MINOR_VERSION_ARB, 0); } else { std::cerr << "warning: " << profile << " requested but GLX_EXT_create_context_es_profile or GLX_EXT_create_context_es2_profile not supported\n"; } } else { assert(0); } if (debug) { contextFlags |= GLX_CONTEXT_DEBUG_BIT_ARB; } if (contextFlags) { attribs.add(GLX_CONTEXT_FLAGS_ARB, contextFlags); } attribs.end(); context = glXCreateContextAttribsARB(display, visual->fbconfig, share_context, True, attribs); if (!context && debug) { // XXX: Mesa has problems with GLX_CONTEXT_DEBUG_BIT_ARB with // OpenGL ES contexts, so retry without it return createContext(_visual, shareContext, false); } } else { if (profile.api != glprofile::API_GL || profile.core) { return NULL; } context = glXCreateNewContext(display, visual->fbconfig, GLX_RGBA_TYPE, share_context, True); } if (!context) { return NULL; } return new GlxContext(visual, context); } bool makeCurrentInternal(Drawable *drawable, Context *context) { if (!drawable || !context) { return glXMakeCurrent(display, None, NULL); } else { GlxDrawable *glxDrawable = static_cast<GlxDrawable *>(drawable); GlxContext *glxContext = static_cast<GlxContext *>(context); glxDrawable->ever_current = true; return glXMakeCurrent(display, glxDrawable->window, glxContext->context); } } Window GlxDrawable::createPbuffer(Display *dpy, const GlxVisual *visinfo, const glws::pbuffer_info *pbInfo, int w, int h) { int samples = 0; // XXX ideally, we'd populate these attributes according to the Visual info Attributes<int> attribs; attribs.add(GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT); attribs.add(GLX_RENDER_TYPE, GLX_RGBA_BIT); attribs.add(GLX_RED_SIZE, 1); attribs.add(GLX_GREEN_SIZE, 1); attribs.add(GLX_BLUE_SIZE, 1); attribs.add(GLX_ALPHA_SIZE, 1); //attribs.add(GLX_DOUBLEBUFFER, doubleBuffer ? GL_TRUE : GL_FALSE); attribs.add(GLX_DEPTH_SIZE, 1); attribs.add(GLX_STENCIL_SIZE, 1); if (samples > 1) { attribs.add(GLX_SAMPLE_BUFFERS, 1); attribs.add(GLX_SAMPLES_ARB, samples); } attribs.end(); int num_configs = 0; GLXFBConfig *fbconfigs; fbconfigs = glXChooseFBConfig(dpy, screen, attribs, &num_configs); if (!num_configs || !fbconfigs) { std::cerr << "error: glXChooseFBConfig for pbuffer failed.\n"; exit(1); } Attributes<int> pbAttribs; pbAttribs.add(GLX_PBUFFER_WIDTH, w); pbAttribs.add(GLX_PBUFFER_HEIGHT, h); pbAttribs.add(GLX_PRESERVED_CONTENTS, True); pbAttribs.end(); GLXDrawable pbuffer = glXCreatePbuffer(dpy, fbconfigs[0], pbAttribs); if (!pbuffer) { std::cerr << "error: glXCreatePbuffer() failed\n"; exit(1); } return pbuffer; } } /* namespace glws */ <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Modified by Cloudius Systems. * Copyright 2015 Cloudius Systems. */ #include "streaming/stream_result_future.hh" #include "streaming/stream_manager.hh" #include "streaming/stream_exception.hh" #include "log.hh" namespace streaming { extern logging::logger sslog; future<stream_state> stream_result_future::init(UUID plan_id_, sstring description_, std::vector<stream_event_handler*> listeners_, shared_ptr<stream_coordinator> coordinator_) { auto future = create_and_register(plan_id_, description_, coordinator_); for (auto& listener : listeners_) { future->add_event_listener(listener); } sslog.info("[Stream #{}] Executing streaming plan for {}", plan_id_, description_); // Initialize and start all sessions for (auto& session : coordinator_->get_all_stream_sessions()) { session->init(future); } coordinator_->connect_all_stream_sessions(); return future->_done.get_future(); } void stream_result_future::init_receiving_side(int session_index, UUID plan_id, sstring description, inet_address from, bool keep_ss_table_level) { auto& sm = get_local_stream_manager(); auto f = sm.get_receiving_stream(plan_id); if (f == nullptr) { sslog.info("[Stream #{} ID#{}] Creating new streaming plan for {}", plan_id, session_index, description); // The main reason we create a StreamResultFuture on the receiving side is for JMX exposure. // TODO: stream_result_future needs a ref to stream_coordinator. bool is_receiving = true; sm.register_receiving(make_shared<stream_result_future>(plan_id, description, keep_ss_table_level, is_receiving)); } sslog.info("[Stream #{} ID#{}] Received streaming plan for {}", plan_id, session_index, description); } void stream_result_future::handle_session_prepared(shared_ptr<stream_session> session) { auto si = session->get_session_info(); sslog.info("[Stream #{} ID#{}] Prepare completed. Receiving {} files({} bytes), sending {} files({} bytes)", session->plan_id(), session->session_index(), si.get_total_files_to_receive(), si.get_total_size_to_receive(), si.get_total_files_to_send(), si.get_total_size_to_send()); auto event = session_prepared_event(plan_id, si); _coordinator->add_session_info(std::move(si)); fire_stream_event(std::move(event)); } void stream_result_future::handle_session_complete(shared_ptr<stream_session> session) { sslog.info("[Stream #{}] Session with {} is complete", session->plan_id(), session->peer); auto event = session_complete_event(session); fire_stream_event(std::move(event)); auto si = session->get_session_info(); _coordinator->add_session_info(std::move(si)); maybe_complete(); } template <typename Event> void stream_result_future::fire_stream_event(Event event) { // delegate to listener for (auto listener : _event_listeners) { listener->handle_stream_event(std::move(event)); } } void stream_result_future::maybe_complete() { if (!_coordinator->has_active_sessions()) { auto final_state = get_current_state(); if (final_state.has_failed_session()) { sslog.warn("[Stream #{}] Stream failed", plan_id); _done.set_exception(stream_exception(final_state, "Stream failed")); } else { sslog.info("[Stream #{}] All sessions completed", plan_id); _done.set_value(final_state); } } } stream_state stream_result_future::get_current_state() { return stream_state(plan_id, description, _coordinator->get_all_session_info()); } void stream_result_future::handle_progress(progress_info progress) { _coordinator->update_progress(progress); fire_stream_event(progress_event(plan_id, std::move(progress))); } shared_ptr<stream_result_future> stream_result_future::create_and_register(UUID plan_id_, sstring description_, shared_ptr<stream_coordinator> coordinator_) { auto future = make_shared<stream_result_future>(plan_id_, description_, coordinator_); auto& sm = get_local_stream_manager(); sm.register_receiving(future); return future; } } // namespace streaming <commit_msg>streaming: Fix stream_result_future::create_and_register<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Modified by Cloudius Systems. * Copyright 2015 Cloudius Systems. */ #include "streaming/stream_result_future.hh" #include "streaming/stream_manager.hh" #include "streaming/stream_exception.hh" #include "log.hh" namespace streaming { extern logging::logger sslog; future<stream_state> stream_result_future::init(UUID plan_id_, sstring description_, std::vector<stream_event_handler*> listeners_, shared_ptr<stream_coordinator> coordinator_) { auto future = create_and_register(plan_id_, description_, coordinator_); for (auto& listener : listeners_) { future->add_event_listener(listener); } sslog.info("[Stream #{}] Executing streaming plan for {}", plan_id_, description_); // Initialize and start all sessions for (auto& session : coordinator_->get_all_stream_sessions()) { session->init(future); } coordinator_->connect_all_stream_sessions(); return future->_done.get_future(); } void stream_result_future::init_receiving_side(int session_index, UUID plan_id, sstring description, inet_address from, bool keep_ss_table_level) { auto& sm = get_local_stream_manager(); auto f = sm.get_receiving_stream(plan_id); if (f == nullptr) { sslog.info("[Stream #{} ID#{}] Creating new streaming plan for {}", plan_id, session_index, description); // The main reason we create a StreamResultFuture on the receiving side is for JMX exposure. // TODO: stream_result_future needs a ref to stream_coordinator. bool is_receiving = true; sm.register_receiving(make_shared<stream_result_future>(plan_id, description, keep_ss_table_level, is_receiving)); } sslog.info("[Stream #{} ID#{}] Received streaming plan for {}", plan_id, session_index, description); } void stream_result_future::handle_session_prepared(shared_ptr<stream_session> session) { auto si = session->get_session_info(); sslog.info("[Stream #{} ID#{}] Prepare completed. Receiving {} files({} bytes), sending {} files({} bytes)", session->plan_id(), session->session_index(), si.get_total_files_to_receive(), si.get_total_size_to_receive(), si.get_total_files_to_send(), si.get_total_size_to_send()); auto event = session_prepared_event(plan_id, si); _coordinator->add_session_info(std::move(si)); fire_stream_event(std::move(event)); } void stream_result_future::handle_session_complete(shared_ptr<stream_session> session) { sslog.info("[Stream #{}] Session with {} is complete", session->plan_id(), session->peer); auto event = session_complete_event(session); fire_stream_event(std::move(event)); auto si = session->get_session_info(); _coordinator->add_session_info(std::move(si)); maybe_complete(); } template <typename Event> void stream_result_future::fire_stream_event(Event event) { // delegate to listener for (auto listener : _event_listeners) { listener->handle_stream_event(std::move(event)); } } void stream_result_future::maybe_complete() { if (!_coordinator->has_active_sessions()) { auto final_state = get_current_state(); if (final_state.has_failed_session()) { sslog.warn("[Stream #{}] Stream failed", plan_id); _done.set_exception(stream_exception(final_state, "Stream failed")); } else { sslog.info("[Stream #{}] All sessions completed", plan_id); _done.set_value(final_state); } } } stream_state stream_result_future::get_current_state() { return stream_state(plan_id, description, _coordinator->get_all_session_info()); } void stream_result_future::handle_progress(progress_info progress) { _coordinator->update_progress(progress); fire_stream_event(progress_event(plan_id, std::move(progress))); } shared_ptr<stream_result_future> stream_result_future::create_and_register(UUID plan_id_, sstring description_, shared_ptr<stream_coordinator> coordinator_) { auto future = make_shared<stream_result_future>(plan_id_, description_, coordinator_); auto& sm = get_local_stream_manager(); sm.register_sending(future); return future; } } // namespace streaming <|endoftext|>
<commit_before>#include <babylon/engines/abstract_scene.h> #include <babylon/audio/audio_engine.h> #include <babylon/audio/sound.h> #include <babylon/babylon_stl_util.h> #include <babylon/core/json_util.h> #include <babylon/engines/asset_container.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene_component_constants.h> #include <babylon/layer/effect_layer.h> #include <babylon/layer/glow_layer.h> #include <babylon/layer/highlight_layer.h> #include <babylon/lensflares/lens_flare_system.h> #include <babylon/lights/shadows/shadow_generator.h> #include <babylon/particles/gpu_particle_system.h> #include <babylon/particles/particle_system.h> namespace BABYLON { std::unordered_map<std::string, BabylonFileParser> AbstractScene::_BabylonFileParsers; std::unordered_map<std::string, IndividualBabylonFileParser> AbstractScene::_IndividualBabylonFileParsers; AbstractScene::AbstractScene() : environmentTexture{this, &AbstractScene::get_environmentTexture, &AbstractScene::set_environmentTexture} , _environmentTexture{nullptr} { _addIndividualParsers(); _addParsers(); } AbstractScene::~AbstractScene() { } void AbstractScene::_addIndividualParsers() { // Particle system parser AbstractScene::AddIndividualParser( SceneComponentConstants::NAME_PARTICLESYSTEM, [](const json& parsedParticleSystem, Scene* scene, const std::string& rootUrl) -> any { if (json_util::has_key(parsedParticleSystem, "activeParticleCount")) { auto ps = GPUParticleSystem::Parse(parsedParticleSystem, scene, rootUrl); return ps; } else { auto ps = ParticleSystem::Parse(parsedParticleSystem, scene, rootUrl); return ps; } }); } void AbstractScene::_addParsers() { // Effect layer parser AbstractScene::AddParser( SceneComponentConstants::NAME_EFFECTLAYER, [](const json& parsedData, Scene* scene, AssetContainer& container, const std::string& rootUrl) { if (json_util::has_key(parsedData, "effectLayers")) { for (const auto& effectLayer : json_util::get_array<json>(parsedData, "effectLayers")) { auto parsedEffectLayer = EffectLayer::Parse(effectLayer, scene, rootUrl); container.effectLayers.emplace_back(parsedEffectLayer); } } }); // Lens flare system parser AbstractScene::AddParser( SceneComponentConstants::NAME_LENSFLARESYSTEM, [](const json& parsedData, Scene* scene, AssetContainer& container, const std::string& rootUrl) { // Lens flares if (json_util::has_key(parsedData, "lensFlareSystems")) { for (const auto& parsedLensFlareSystem : json_util::get_array<json>(parsedData, "lensFlareSystems")) { auto lf = LensFlareSystem::Parse(parsedLensFlareSystem, scene, rootUrl); container.lensFlareSystems.emplace_back(lf); } } }); // Particle system parser AbstractScene::AddParser( SceneComponentConstants::NAME_PARTICLESYSTEM, [](const json& parsedData, Scene* scene, AssetContainer& container, const std::string& rootUrl) { auto individualParser = AbstractScene::GetIndividualParser( SceneComponentConstants::NAME_PARTICLESYSTEM); if (!individualParser) { return; } // Particles Systems if (json_util::has_key(parsedData, "particleSystems")) { for (const auto& parsedParticleSystem : json_util::get_array<json>(parsedData, "particleSystems")) { auto particleSystem = individualParser.value()(parsedParticleSystem, scene, rootUrl) ._<ParticleSystem*>(); container.particleSystems.emplace_back(particleSystem); } } }); // Shadows parser AbstractScene::AddParser( SceneComponentConstants::NAME_SHADOWGENERATOR, [](const json& parsedData, Scene* scene, AssetContainer& /*container*/, const std::string& /*rootUrl*/) { // Shadows if (json_util::has_key(parsedData, "shadowGenerators")) { for (const auto& parsedShadowGenerator : json_util::get_array<json>(parsedData, "shadowGenerators")) { ShadowGenerator::Parse(parsedShadowGenerator, scene); // SG would be available on their associated lights } } }); // Sound parsers AbstractScene::AddParser( SceneComponentConstants::NAME_AUDIO, [](const json& parsedData, Scene* scene, AssetContainer& container, const std::string& rootUrl) { std::unordered_map<std::string, SoundPtr> loadedSounds; SoundPtr loadedSound; if (json_util::has_key(parsedData, "sounds")) { for (const auto& parsedSound : json_util::get_array<json>(parsedData, "sounds")) { auto parsedSoundName = json_util::get_string(parsedSound, "name"); if (Engine::AudioEngine()->canUseWebAudio) { std::string parsedSoundUrl; if (!json_util::has_key(parsedSound, "url")) { parsedSoundUrl = parsedSoundName; } else { parsedSoundUrl = json_util::get_string(parsedSound, "url"); } if (!stl_util::contains(loadedSounds, parsedSoundUrl)) { loadedSound = Sound::Parse(parsedSound, scene, rootUrl); loadedSounds[parsedSoundUrl] = loadedSound; container.sounds.emplace_back(loadedSound); } else { container.sounds.emplace_back(Sound::Parse( parsedSound, scene, rootUrl, loadedSounds[parsedSoundUrl])); } } else { container.sounds.emplace_back( Sound::New(parsedSoundName, std::nullopt, scene)); } } } loadedSounds.clear(); }); } void AbstractScene::AddParser(const std::string& name, const BabylonFileParser& parser) { _BabylonFileParsers[name] = parser; } std::optional<BabylonFileParser> AbstractScene::GetParser(const std::string& name) { if (stl_util::contains(_BabylonFileParsers, name)) { return _BabylonFileParsers[name]; } return std::nullopt; } void AbstractScene::AddIndividualParser( const std::string& name, const IndividualBabylonFileParser& parser) { _IndividualBabylonFileParsers[name] = parser; } std::optional<IndividualBabylonFileParser> AbstractScene::GetIndividualParser(const std::string& name) { if (stl_util::contains(_IndividualBabylonFileParsers, name)) { return _IndividualBabylonFileParsers[name]; } return std::nullopt; } void AbstractScene::Parse(const json& /*jsonData*/, Scene* /*scene*/, const AssetContainerPtr& /*container*/, const std::string& /*rootUrl*/) { #if 0 for (const auto& _BabylonFileParserItem : _BabylonFileParsers) { _BabylonFileParserItem.second(jsonData, scene, container, rootUrl); } #endif } int AbstractScene::removeEffectLayer(const EffectLayerPtr& toRemove) { auto it = std::find(effectLayers.begin(), effectLayers.end(), toRemove); int index = static_cast<int>(it - effectLayers.begin()); if (it != effectLayers.end()) { effectLayers.erase(it); } return index; } void AbstractScene::addEffectLayer(const EffectLayerPtr& newEffectLayer) { effectLayers.emplace_back(newEffectLayer); } GlowLayerPtr AbstractScene::getGlowLayerByName(const std::string& name) { auto it = std::find_if(effectLayers.begin(), effectLayers.end(), [&name](const EffectLayerPtr& effectLayer) { return effectLayer->name == name && effectLayer->getEffectName() == GlowLayer::EffectName; }); return (it == effectLayers.end()) ? nullptr : std::static_pointer_cast<GlowLayer>(*it); } HighlightLayerPtr AbstractScene::getHighlightLayerByName(const std::string& name) { auto it = std::find_if(effectLayers.begin(), effectLayers.end(), [&name](const EffectLayerPtr& effectLayer) { return effectLayer->name == name && effectLayer->getEffectName() == HighlightLayer::EffectName; }); return (it == effectLayers.end()) ? nullptr : std::static_pointer_cast<HighlightLayer>(*it); } int AbstractScene::removeLensFlareSystem(const LensFlareSystemPtr& toRemove) { auto it = std::find(lensFlareSystems.begin(), lensFlareSystems.end(), toRemove); int index = static_cast<int>(it - lensFlareSystems.begin()); if (it != lensFlareSystems.end()) { lensFlareSystems.erase(it); } return index; } void AbstractScene::addLensFlareSystem( const LensFlareSystemPtr& newLensFlareSystem) { lensFlareSystems.emplace_back(newLensFlareSystem); } LensFlareSystemPtr AbstractScene::getLensFlareSystemByName(const std::string& name) { auto it = std::find_if(lensFlareSystems.begin(), lensFlareSystems.end(), [&name](const LensFlareSystemPtr& lensFlareSystem) { return lensFlareSystem->name == name; }); return (it == lensFlareSystems.end()) ? nullptr : (*it); } LensFlareSystemPtr AbstractScene::getLensFlareSystemByID(const std::string& id) { auto it = std::find_if(lensFlareSystems.begin(), lensFlareSystems.end(), [&id](const LensFlareSystemPtr& lensFlareSystem) { return lensFlareSystem->id == id; }); return (it == lensFlareSystems.end()) ? nullptr : (*it); } int AbstractScene::removeReflectionProbe(const ReflectionProbePtr& toRemove) { auto it = std::find(reflectionProbes.begin(), reflectionProbes.end(), toRemove); int index = static_cast<int>(it - reflectionProbes.begin()); if (it != reflectionProbes.end()) { reflectionProbes.erase(it); } return index; } void AbstractScene::addReflectionProbe( const ReflectionProbePtr& newReflectionProbe) { reflectionProbes.emplace_back(newReflectionProbe); } BaseTexturePtr& AbstractScene::get_environmentTexture() { return _environmentTexture; } void AbstractScene::set_environmentTexture(const BaseTexturePtr& value) { _environmentTexture = value; } } // end of namespace BABYLON <commit_msg>Returning -1 when reflectionProbes list is empty<commit_after>#include <babylon/engines/abstract_scene.h> #include <babylon/audio/audio_engine.h> #include <babylon/audio/sound.h> #include <babylon/babylon_stl_util.h> #include <babylon/core/json_util.h> #include <babylon/engines/asset_container.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene_component_constants.h> #include <babylon/layer/effect_layer.h> #include <babylon/layer/glow_layer.h> #include <babylon/layer/highlight_layer.h> #include <babylon/lensflares/lens_flare_system.h> #include <babylon/lights/shadows/shadow_generator.h> #include <babylon/particles/gpu_particle_system.h> #include <babylon/particles/particle_system.h> namespace BABYLON { std::unordered_map<std::string, BabylonFileParser> AbstractScene::_BabylonFileParsers; std::unordered_map<std::string, IndividualBabylonFileParser> AbstractScene::_IndividualBabylonFileParsers; AbstractScene::AbstractScene() : environmentTexture{this, &AbstractScene::get_environmentTexture, &AbstractScene::set_environmentTexture} , _environmentTexture{nullptr} { _addIndividualParsers(); _addParsers(); } AbstractScene::~AbstractScene() { } void AbstractScene::_addIndividualParsers() { // Particle system parser AbstractScene::AddIndividualParser( SceneComponentConstants::NAME_PARTICLESYSTEM, [](const json& parsedParticleSystem, Scene* scene, const std::string& rootUrl) -> any { if (json_util::has_key(parsedParticleSystem, "activeParticleCount")) { auto ps = GPUParticleSystem::Parse(parsedParticleSystem, scene, rootUrl); return ps; } else { auto ps = ParticleSystem::Parse(parsedParticleSystem, scene, rootUrl); return ps; } }); } void AbstractScene::_addParsers() { // Effect layer parser AbstractScene::AddParser( SceneComponentConstants::NAME_EFFECTLAYER, [](const json& parsedData, Scene* scene, AssetContainer& container, const std::string& rootUrl) { if (json_util::has_key(parsedData, "effectLayers")) { for (const auto& effectLayer : json_util::get_array<json>(parsedData, "effectLayers")) { auto parsedEffectLayer = EffectLayer::Parse(effectLayer, scene, rootUrl); container.effectLayers.emplace_back(parsedEffectLayer); } } }); // Lens flare system parser AbstractScene::AddParser( SceneComponentConstants::NAME_LENSFLARESYSTEM, [](const json& parsedData, Scene* scene, AssetContainer& container, const std::string& rootUrl) { // Lens flares if (json_util::has_key(parsedData, "lensFlareSystems")) { for (const auto& parsedLensFlareSystem : json_util::get_array<json>(parsedData, "lensFlareSystems")) { auto lf = LensFlareSystem::Parse(parsedLensFlareSystem, scene, rootUrl); container.lensFlareSystems.emplace_back(lf); } } }); // Particle system parser AbstractScene::AddParser( SceneComponentConstants::NAME_PARTICLESYSTEM, [](const json& parsedData, Scene* scene, AssetContainer& container, const std::string& rootUrl) { auto individualParser = AbstractScene::GetIndividualParser( SceneComponentConstants::NAME_PARTICLESYSTEM); if (!individualParser) { return; } // Particles Systems if (json_util::has_key(parsedData, "particleSystems")) { for (const auto& parsedParticleSystem : json_util::get_array<json>(parsedData, "particleSystems")) { auto particleSystem = individualParser.value()(parsedParticleSystem, scene, rootUrl) ._<ParticleSystem*>(); container.particleSystems.emplace_back(particleSystem); } } }); // Shadows parser AbstractScene::AddParser( SceneComponentConstants::NAME_SHADOWGENERATOR, [](const json& parsedData, Scene* scene, AssetContainer& /*container*/, const std::string& /*rootUrl*/) { // Shadows if (json_util::has_key(parsedData, "shadowGenerators")) { for (const auto& parsedShadowGenerator : json_util::get_array<json>(parsedData, "shadowGenerators")) { ShadowGenerator::Parse(parsedShadowGenerator, scene); // SG would be available on their associated lights } } }); // Sound parsers AbstractScene::AddParser( SceneComponentConstants::NAME_AUDIO, [](const json& parsedData, Scene* scene, AssetContainer& container, const std::string& rootUrl) { std::unordered_map<std::string, SoundPtr> loadedSounds; SoundPtr loadedSound; if (json_util::has_key(parsedData, "sounds")) { for (const auto& parsedSound : json_util::get_array<json>(parsedData, "sounds")) { auto parsedSoundName = json_util::get_string(parsedSound, "name"); if (Engine::AudioEngine()->canUseWebAudio) { std::string parsedSoundUrl; if (!json_util::has_key(parsedSound, "url")) { parsedSoundUrl = parsedSoundName; } else { parsedSoundUrl = json_util::get_string(parsedSound, "url"); } if (!stl_util::contains(loadedSounds, parsedSoundUrl)) { loadedSound = Sound::Parse(parsedSound, scene, rootUrl); loadedSounds[parsedSoundUrl] = loadedSound; container.sounds.emplace_back(loadedSound); } else { container.sounds.emplace_back(Sound::Parse( parsedSound, scene, rootUrl, loadedSounds[parsedSoundUrl])); } } else { container.sounds.emplace_back( Sound::New(parsedSoundName, std::nullopt, scene)); } } } loadedSounds.clear(); }); } void AbstractScene::AddParser(const std::string& name, const BabylonFileParser& parser) { _BabylonFileParsers[name] = parser; } std::optional<BabylonFileParser> AbstractScene::GetParser(const std::string& name) { if (stl_util::contains(_BabylonFileParsers, name)) { return _BabylonFileParsers[name]; } return std::nullopt; } void AbstractScene::AddIndividualParser( const std::string& name, const IndividualBabylonFileParser& parser) { _IndividualBabylonFileParsers[name] = parser; } std::optional<IndividualBabylonFileParser> AbstractScene::GetIndividualParser(const std::string& name) { if (stl_util::contains(_IndividualBabylonFileParsers, name)) { return _IndividualBabylonFileParsers[name]; } return std::nullopt; } void AbstractScene::Parse(const json& /*jsonData*/, Scene* /*scene*/, const AssetContainerPtr& /*container*/, const std::string& /*rootUrl*/) { #if 0 for (const auto& _BabylonFileParserItem : _BabylonFileParsers) { _BabylonFileParserItem.second(jsonData, scene, container, rootUrl); } #endif } int AbstractScene::removeEffectLayer(const EffectLayerPtr& toRemove) { auto it = std::find(effectLayers.begin(), effectLayers.end(), toRemove); int index = static_cast<int>(it - effectLayers.begin()); if (it != effectLayers.end()) { effectLayers.erase(it); } return index; } void AbstractScene::addEffectLayer(const EffectLayerPtr& newEffectLayer) { effectLayers.emplace_back(newEffectLayer); } GlowLayerPtr AbstractScene::getGlowLayerByName(const std::string& name) { auto it = std::find_if(effectLayers.begin(), effectLayers.end(), [&name](const EffectLayerPtr& effectLayer) { return effectLayer->name == name && effectLayer->getEffectName() == GlowLayer::EffectName; }); return (it == effectLayers.end()) ? nullptr : std::static_pointer_cast<GlowLayer>(*it); } HighlightLayerPtr AbstractScene::getHighlightLayerByName(const std::string& name) { auto it = std::find_if(effectLayers.begin(), effectLayers.end(), [&name](const EffectLayerPtr& effectLayer) { return effectLayer->name == name && effectLayer->getEffectName() == HighlightLayer::EffectName; }); return (it == effectLayers.end()) ? nullptr : std::static_pointer_cast<HighlightLayer>(*it); } int AbstractScene::removeLensFlareSystem(const LensFlareSystemPtr& toRemove) { auto it = std::find(lensFlareSystems.begin(), lensFlareSystems.end(), toRemove); int index = static_cast<int>(it - lensFlareSystems.begin()); if (it != lensFlareSystems.end()) { lensFlareSystems.erase(it); } return index; } void AbstractScene::addLensFlareSystem( const LensFlareSystemPtr& newLensFlareSystem) { lensFlareSystems.emplace_back(newLensFlareSystem); } LensFlareSystemPtr AbstractScene::getLensFlareSystemByName(const std::string& name) { auto it = std::find_if(lensFlareSystems.begin(), lensFlareSystems.end(), [&name](const LensFlareSystemPtr& lensFlareSystem) { return lensFlareSystem->name == name; }); return (it == lensFlareSystems.end()) ? nullptr : (*it); } LensFlareSystemPtr AbstractScene::getLensFlareSystemByID(const std::string& id) { auto it = std::find_if(lensFlareSystems.begin(), lensFlareSystems.end(), [&id](const LensFlareSystemPtr& lensFlareSystem) { return lensFlareSystem->id == id; }); return (it == lensFlareSystems.end()) ? nullptr : (*it); } int AbstractScene::removeReflectionProbe(const ReflectionProbePtr& toRemove) { if (reflectionProbes.empty()) { return -1; } auto it = std::find(reflectionProbes.begin(), reflectionProbes.end(), toRemove); auto index = static_cast<int>(it - reflectionProbes.begin()); if (it != reflectionProbes.end()) { reflectionProbes.erase(it); } return index; } void AbstractScene::addReflectionProbe( const ReflectionProbePtr& newReflectionProbe) { reflectionProbes.emplace_back(newReflectionProbe); } BaseTexturePtr& AbstractScene::get_environmentTexture() { return _environmentTexture; } void AbstractScene::set_environmentTexture(const BaseTexturePtr& value) { _environmentTexture = value; } } // end of namespace BABYLON <|endoftext|>
<commit_before>#include "rubymotion.h" #include <SimpleAudioEngine.h> /// @class Audio < Object VALUE rb_cAudio = Qnil; static VALUE mc_audio_instance = Qnil; /// @group Constructors /// @method .shared /// @return [Audio] the shared Audio instance. static VALUE audio_instance(VALUE rcv, SEL sel) { if (mc_audio_instance == Qnil) { VALUE obj = rb_class_wrap_new( (void *)CocosDenshion::SimpleAudioEngine::getInstance(), rb_cAudio); mc_audio_instance = rb_retain(obj); } return mc_audio_instance; } static std::string audio_path(VALUE path) { std::string str = RSTRING_PTR(path); #if CC_TARGET_OS_IPHONE str.append(".caf"); #else str.append(".wav"); #endif return str; } /// @group Audio Playback /// @method #background(file_name, loop=true) /// Plays a background audio file. /// @param file_name [String] Name of the audio file to play, without its file /// extension. The file should reside in the application's resource /// directory. /// @param loop [true, false] Whether the audio file should loop. /// @return [Audio] the receiver. static VALUE audio_background(VALUE rcv, SEL sel, int argc, VALUE *argv) { VALUE path = Qnil; VALUE loop = Qtrue; rb_scan_args(argc, argv, "11", &path, &loop); AUDIO(rcv)->playBackgroundMusic(audio_path(path).c_str(), RTEST(loop)); return rcv; } /// @method #effect(file_name) /// Plays an effect audio file. /// @param file_name [String] Name of the audio file to play, without its file /// extension. The file should reside in the application's resource /// directory /// @return [Audio] the receiver. static VALUE audio_effect(VALUE rcv, SEL sel, VALUE path) { AUDIO(rcv)->playEffect(audio_path(path).c_str()); return rcv; } extern "C" void Init_Audio(void) { rb_cAudio = rb_define_class_under(rb_mMC, "Audio", rb_cObject); rb_define_singleton_method(rb_cAudio, "shared", audio_instance, 0); rb_define_method(rb_cAudio, "background", audio_background, -1); rb_define_method(rb_cAudio, "effect", audio_effect, 1); } <commit_msg>don’t set audio file extension if there is already one, doc fixes<commit_after>#include "rubymotion.h" #include <SimpleAudioEngine.h> /// @class Audio < Object VALUE rb_cAudio = Qnil; static VALUE mc_audio_instance = Qnil; /// @group Constructors /// @method .shared /// @return [Audio] the shared Audio instance. static VALUE audio_instance(VALUE rcv, SEL sel) { if (mc_audio_instance == Qnil) { VALUE obj = rb_class_wrap_new( (void *)CocosDenshion::SimpleAudioEngine::getInstance(), rb_cAudio); mc_audio_instance = rb_retain(obj); } return mc_audio_instance; } static std::string audio_path(VALUE path) { std::string str = RSTRING_PTR(path); if (str.find('.') == std::string::npos) { #if CC_TARGET_OS_IPHONE str.append(".caf"); #else str.append(".wav"); #endif } return str; } /// @group Audio Playback /// @method #background(file_name, loop=true) /// Plays background music. /// @param file_name [String] Name of the audio file to play, without its file /// extension. The file should reside in the application's resource /// directory. /// @param loop [true, false] Whether the audio file should loop. /// @return [Audio] the receiver. static VALUE audio_background(VALUE rcv, SEL sel, int argc, VALUE *argv) { VALUE path = Qnil; VALUE loop = Qtrue; rb_scan_args(argc, argv, "11", &path, &loop); AUDIO(rcv)->playBackgroundMusic(audio_path(path).c_str(), RTEST(loop)); return rcv; } /// @method #effect(file_name) /// Plays a sound effect. /// @param file_name [String] Name of the audio file to play, without its file /// extension. The file should reside in the application's resource /// directory. /// @return [Audio] the receiver. static VALUE audio_effect(VALUE rcv, SEL sel, VALUE path) { AUDIO(rcv)->playEffect(audio_path(path).c_str()); return rcv; } extern "C" void Init_Audio(void) { rb_cAudio = rb_define_class_under(rb_mMC, "Audio", rb_cObject); rb_define_singleton_method(rb_cAudio, "shared", audio_instance, 0); rb_define_method(rb_cAudio, "background", audio_background, -1); rb_define_method(rb_cAudio, "effect", audio_effect, 1); } <|endoftext|>
<commit_before>#include "density.h" namespace sirius { /** type = 0: full-potential radial integrals \n * type = 1: pseudopotential valence density integrals \n * type = 2: pseudopotential code density integrals */ mdarray<double, 2> Density::generate_rho_radial_integrals(int type__) { Timer t("sirius::Density::generate_rho_radial_integrals"); auto rl = parameters_.reciprocal_lattice(); auto uc = parameters_.unit_cell(); mdarray<double, 2> rho_radial_integrals(uc->num_atom_types(), rl->num_gvec_shells_inner()); /* split G-shells between MPI ranks */ splindex<block> spl_gshells(rl->num_gvec_shells_inner(), parameters_.comm().size(), parameters_.comm().rank()); #pragma omp parallel { /* splines for all atom types */ std::vector< Spline<double> > sa(uc->num_atom_types()); for (int iat = 0; iat < uc->num_atom_types(); iat++) { /* full potential radial integrals requre a free atom grid */ if (type__ == 0) { sa[iat] = Spline<double>(uc->atom_type(iat)->free_atom_radial_grid()); } else { sa[iat] = Spline<double>(uc->atom_type(iat)->radial_grid()); } } /* spherical Bessel functions */ sbessel_pw<double> jl(uc, 0); #pragma omp for for (int igsloc = 0; igsloc < (int)spl_gshells.local_size(); igsloc++) { int igs = (int)spl_gshells[igsloc]; /* for pseudopotential valence or core charge density */ if (type__ == 1 || type__ == 2) jl.load(rl->gvec_shell_len(igs)); for (int iat = 0; iat < uc->num_atom_types(); iat++) { auto atom_type = uc->atom_type(iat); if (type__ == 0) { if (igs == 0) { for (int ir = 0; ir < sa[iat].num_points(); ir++) sa[iat][ir] = atom_type->free_atom_density(ir); rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(2); } else { double G = rl->gvec_shell_len(igs); for (int ir = 0; ir < sa[iat].num_points(); ir++) { sa[iat][ir] = atom_type->free_atom_density(ir) * sin(G * atom_type->free_atom_radial_grid(ir)) / G; } rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(1); } } if (type__ == 1) { for (int ir = 0; ir < sa[iat].num_points(); ir++) sa[iat][ir] = jl(ir, 0, iat) * atom_type->uspp().total_charge_density[ir]; rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(0) / fourpi; } if (type__ == 2) { for (int ir = 0; ir < sa[iat].num_points(); ir++) sa[iat][ir] = jl(ir, 0, iat) * atom_type->uspp().core_charge_density[ir]; rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(2); } } } } int ld = uc->num_atom_types(); parameters_.comm().allgather(rho_radial_integrals.at<CPU>(), static_cast<int>(ld * spl_gshells.global_offset()), static_cast<int>(ld * spl_gshells.local_size())); return rho_radial_integrals; } }; <commit_msg>initi density from gaussians<commit_after>#include "density.h" namespace sirius { /** type = 0: full-potential radial integrals \n * type = 1: pseudopotential valence density integrals \n * type = 2: pseudopotential code density integrals */ mdarray<double, 2> Density::generate_rho_radial_integrals(int type__) { Timer t("sirius::Density::generate_rho_radial_integrals"); auto rl = parameters_.reciprocal_lattice(); auto uc = parameters_.unit_cell(); mdarray<double, 2> rho_radial_integrals(uc->num_atom_types(), rl->num_gvec_shells_inner()); /* split G-shells between MPI ranks */ splindex<block> spl_gshells(rl->num_gvec_shells_inner(), parameters_.comm().size(), parameters_.comm().rank()); if (type__ == 5) { #ifdef _PRINT_OBJECT_CHECKSUM_ for (int iat = 0; iat < uc->num_atom_types(); iat++) { DUMP("iat: %i, checksum(radial_grid): %18.10f %18.10f", iat, uc->atom_type(iat)->radial_grid().x().checksum(), uc->atom_type(iat)->radial_grid().dx().checksum()); } #endif #ifdef _PRINT_OBJECT_HASH_ for (int iat = 0; iat < uc->num_atom_types(); iat++) { DUMP("iat: %i, hash(radial_grid): %16llX", iat, uc->atom_type(iat)->radial_grid().hash()); DUMP("iat: %i, hash(free_atom_radial_grid): %16llX", iat, uc->atom_type(iat)->free_atom_radial_grid().hash()); } #endif double b = 8; for (int igs = 0; igs < rl->num_gvec_shells_inner(); igs++) { double G = rl->gvec_shell_len(igs); for (int iat = 0; iat < uc->num_atom_types(); iat++) { int Z = uc->atom_type(iat)->zn(); double R = uc->atom_type(iat)->mt_radius(); if (igs != 0) { rho_radial_integrals(iat, igs) = (std::pow(b,3)*Z*((std::pow(G,5)*(G*(2*b + (std::pow(b,2) + std::pow(G,2))*R)*std::cos(G*R) + (std::pow(b,2) - std::pow(G,2) + b*(std::pow(b,2) + std::pow(G,2))*R)*std::sin(G*R)))/ std::pow(std::pow(b,2) + std::pow(G,2),2) + (G*(3 + b*R)*(G*R*(6 - std::pow(G,2)*std::pow(R,2))*std::cos(G*R) + 3*(-2 + std::pow(G,2)*std::pow(R,2))*std::sin(G*R)))/std::pow(R,2) + ((2 + b*R)*((24 - 12*std::pow(G,2)*std::pow(R,2) + std::pow(G,4)*std::pow(R,4))*std::cos(G*R) - 4*(6 + G*R*(-6 + std::pow(G,2)*std::pow(R,2))*std::sin(G*R))))/std::pow(R,3)))/ (8.*std::exp(b*R)*std::pow(G,6)*pi); } else { rho_radial_integrals(iat, igs) = ((60 + 60*b*R + 30*std::pow(b,2)*std::pow(R,2) + 8*std::pow(b,3)*std::pow(R,3) + std::pow(b,4)*std::pow(R,4))*Z)/(240.*std::exp(b*R)*pi); } } } #ifdef _PRINT_OBJECT_CHECKSUM_ DUMP("checksum(rho_radial_integrals): %18.10f", rho_radial_integrals.checksum()); #endif return rho_radial_integrals; } if (type__ == 4) { /* rho[r_] := Z*b^3/8/Pi*Exp[-b*r] * Integrate[Sin[G*r]*rho[r]*r*r/(G*r), {r, 0, \[Infinity]}, Assumptions -> {G >= 0, b > 0}] * Out[] = (b^4 Z)/(4 (b^2 + G^2)^2 \[Pi]) */ double b = 4; for (int igs = 0; igs < rl->num_gvec_shells_inner(); igs++) { double G = rl->gvec_shell_len(igs); for (int iat = 0; iat < uc->num_atom_types(); iat++) { rho_radial_integrals(iat, igs) = std::pow(b, 4) * uc->atom_type(iat)->zn() / (4 * std::pow(std::pow(b, 2) + std::pow(G, 2), 2) * pi); } } return rho_radial_integrals; } #pragma omp parallel { /* splines for all atom types */ std::vector< Spline<double> > sa(uc->num_atom_types()); for (int iat = 0; iat < uc->num_atom_types(); iat++) { /* full potential radial integrals requre a free atom grid */ if (type__ == 0) { sa[iat] = Spline<double>(uc->atom_type(iat)->free_atom_radial_grid()); } else { sa[iat] = Spline<double>(uc->atom_type(iat)->radial_grid()); } } /* spherical Bessel functions */ sbessel_pw<double> jl(uc, 0); #pragma omp for for (int igsloc = 0; igsloc < (int)spl_gshells.local_size(); igsloc++) { int igs = (int)spl_gshells[igsloc]; /* for pseudopotential valence or core charge density */ if (type__ == 1 || type__ == 2) jl.load(rl->gvec_shell_len(igs)); for (int iat = 0; iat < uc->num_atom_types(); iat++) { auto atom_type = uc->atom_type(iat); if (type__ == 0) { if (igs == 0) { for (int ir = 0; ir < sa[iat].num_points(); ir++) sa[iat][ir] = atom_type->free_atom_density(ir); rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(2); } else { double G = rl->gvec_shell_len(igs); for (int ir = 0; ir < sa[iat].num_points(); ir++) { sa[iat][ir] = atom_type->free_atom_density(ir) * sin(G * atom_type->free_atom_radial_grid(ir)) / G; } rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(1); } } if (type__ == 1) { for (int ir = 0; ir < sa[iat].num_points(); ir++) sa[iat][ir] = jl(ir, 0, iat) * atom_type->uspp().total_charge_density[ir]; rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(0) / fourpi; } if (type__ == 2) { for (int ir = 0; ir < sa[iat].num_points(); ir++) sa[iat][ir] = jl(ir, 0, iat) * atom_type->uspp().core_charge_density[ir]; rho_radial_integrals(iat, igs) = sa[iat].interpolate().integrate(2); } } } } int ld = uc->num_atom_types(); parameters_.comm().allgather(rho_radial_integrals.at<CPU>(), static_cast<int>(ld * spl_gshells.global_offset()), static_cast<int>(ld * spl_gshells.local_size())); return rho_radial_integrals; } }; <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TableWindowAccess.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 15:38:21 $ * * 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 DBACCESS_TABLEWINDOWACCESS_HXX #define DBACCESS_TABLEWINDOWACCESS_HXX #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLERELATIONSET_HPP_ #include <com/sun/star/accessibility/XAccessibleRelationSet.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ #include <toolkit/awt/vclxaccessiblecomponent.hxx> #endif namespace dbaui { typedef ::cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessibleRelationSet, ::com::sun::star::accessibility::XAccessible > OTableWindowAccess_BASE; class OTableWindow; /** the class OTableWindowAccess represents the accessible object for table windows like they are used in the QueryDesign and the RelationDesign */ class OTableWindowAccess : public VCLXAccessibleComponent , public OTableWindowAccess_BASE { OTableWindow* m_pTable; // the window which I should give accessibility to ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > getParentChild(sal_Int32 _nIndex); protected: /** this function is called upon disposing the component */ virtual void SAL_CALL disposing(); /** isEditable returns the current editable state @return true if it is editable otherwise false */ virtual sal_Bool isEditable() const; public: OTableWindowAccess( OTableWindow* _pTable); // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( ) throw () { // here inline is allowed because we do not use this class outside this dll VCLXAccessibleComponent::acquire( ); } virtual void SAL_CALL release( ) throw () { // here inline is allowed because we do not use this class outside this dll VCLXAccessibleComponent::release( ); } // XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(com::sun::star::uno::RuntimeException); // XServiceInfo - static methods static com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( com::sun::star::uno::RuntimeException ); static ::rtl::OUString getImplementationName_Static(void) throw( com::sun::star::uno::RuntimeException ); // XAccessible virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException); // XAccessibleContext virtual sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException,::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getAccessibleIndexInParent( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getAccessibleRole( ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getAccessibleName( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet( ) throw (::com::sun::star::uno::RuntimeException); // XAccessibleComponent virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); // XAccessibleExtendedComponent virtual ::rtl::OUString SAL_CALL getTitledBorderText( ) throw (::com::sun::star::uno::RuntimeException); // XAccessibleRelationSet virtual sal_Int32 SAL_CALL getRelationCount( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::accessibility::AccessibleRelation SAL_CALL getRelation( sal_Int32 nIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL containsRelation( sal_Int16 aRelationType ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::accessibility::AccessibleRelation SAL_CALL getRelationByType( sal_Int16 aRelationType ) throw (::com::sun::star::uno::RuntimeException); void notifyAccessibleEvent( const sal_Int16 _nEventId, const ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Any& _rNewValue ) { NotifyAccessibleEvent(_nEventId,_rOldValue,_rNewValue); } }; } #endif // DBACCESS_TABLEWINDOWACCESS_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.6.434); FILE MERGED 2008/03/31 13:27:44 rt 1.6.434.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TableWindowAccess.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef DBACCESS_TABLEWINDOWACCESS_HXX #define DBACCESS_TABLEWINDOWACCESS_HXX #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLERELATIONSET_HPP_ #include <com/sun/star/accessibility/XAccessibleRelationSet.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ #include <toolkit/awt/vclxaccessiblecomponent.hxx> #endif namespace dbaui { typedef ::cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessibleRelationSet, ::com::sun::star::accessibility::XAccessible > OTableWindowAccess_BASE; class OTableWindow; /** the class OTableWindowAccess represents the accessible object for table windows like they are used in the QueryDesign and the RelationDesign */ class OTableWindowAccess : public VCLXAccessibleComponent , public OTableWindowAccess_BASE { OTableWindow* m_pTable; // the window which I should give accessibility to ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > getParentChild(sal_Int32 _nIndex); protected: /** this function is called upon disposing the component */ virtual void SAL_CALL disposing(); /** isEditable returns the current editable state @return true if it is editable otherwise false */ virtual sal_Bool isEditable() const; public: OTableWindowAccess( OTableWindow* _pTable); // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( ) throw () { // here inline is allowed because we do not use this class outside this dll VCLXAccessibleComponent::acquire( ); } virtual void SAL_CALL release( ) throw () { // here inline is allowed because we do not use this class outside this dll VCLXAccessibleComponent::release( ); } // XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(com::sun::star::uno::RuntimeException); // XServiceInfo - static methods static com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( com::sun::star::uno::RuntimeException ); static ::rtl::OUString getImplementationName_Static(void) throw( com::sun::star::uno::RuntimeException ); // XAccessible virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException); // XAccessibleContext virtual sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException,::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getAccessibleIndexInParent( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getAccessibleRole( ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getAccessibleName( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet( ) throw (::com::sun::star::uno::RuntimeException); // XAccessibleComponent virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); // XAccessibleExtendedComponent virtual ::rtl::OUString SAL_CALL getTitledBorderText( ) throw (::com::sun::star::uno::RuntimeException); // XAccessibleRelationSet virtual sal_Int32 SAL_CALL getRelationCount( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::accessibility::AccessibleRelation SAL_CALL getRelation( sal_Int32 nIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL containsRelation( sal_Int16 aRelationType ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::accessibility::AccessibleRelation SAL_CALL getRelationByType( sal_Int16 aRelationType ) throw (::com::sun::star::uno::RuntimeException); void notifyAccessibleEvent( const sal_Int16 _nEventId, const ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Any& _rNewValue ) { NotifyAccessibleEvent(_nEventId,_rOldValue,_rNewValue); } }; } #endif // DBACCESS_TABLEWINDOWACCESS_HXX <|endoftext|>
<commit_before><commit_msg>Training key bindings for quick use with Mobile Mouse, fixed out of bounds of array bug.<commit_after><|endoftext|>
<commit_before>#include "LevyRand.h" LevyRand::LevyRand(double location, double scale) { setLocation(location); setScale(scale); } std::string LevyRand::name() { return "Levy(" + toStringWithPrecision(getLocation()) + ", " + toStringWithPrecision(getScale()) + ")"; } void LevyRand::setLocation(double location) { mu = location; } void LevyRand::setScale(double scale) { c = scale; if (c <= 0) c = 1.0; sqrtc_2pi = std::sqrt(c); X.setSigma(1.0 / sqrtc_2pi); /// X ~ N(0, c ^ -0.5) sqrtc_2pi *= M_1_SQRT2PI; } double LevyRand::f(double x) const { if (x <= mu) return 0; double xInv = 1.0 / (x - mu); double y = -0.5 * c * xInv; y = std::exp(y); y *= xInv; y *= std::sqrt(xInv); return sqrtc_2pi * y; } double LevyRand::F(double x) const { if (x <= mu) return 0; double y = x - mu; y += y; y = c / y; y = std::sqrt(y); return std::erfc(y); } double LevyRand::variate() const { double rv = X.variate(); rv *= rv; rv = 1.0 / rv; return mu + rv; } double LevyRand::Mean() const { return INFINITY; } double LevyRand::Variance() const { return INFINITY; } std::complex<double> LevyRand::CF(double t) const { std::complex<double> y(0.0, -2 * c * t); y = -std::sqrt(y); y += std::complex<double>(0.0, mu * t); return std::exp(y); } double LevyRand::Quantile(double p) const { if (p == 0.0) return mu; double x = 1.0 / X.Quantile(0.5 * p); return mu + x * x; } double LevyRand::Mode() const { return c / 3.0 + mu; } double LevyRand::Skewness() const { return NAN; } double LevyRand::ExcessKurtosis() const { return NAN; } <commit_msg>Update LevyRand.cpp<commit_after>#include "LevyRand.h" LevyRand::LevyRand(double location, double scale) { setLocation(location); setScale(scale); } std::string LevyRand::name() { return "Levy(" + toStringWithPrecision(getLocation()) + ", " + toStringWithPrecision(getScale()) + ")"; } void LevyRand::setLocation(double location) { mu = location; } void LevyRand::setScale(double scale) { c = scale; if (c <= 0) c = 1.0; sqrtc_2pi = std::sqrt(c); X.setSigma(1.0 / sqrtc_2pi); /// X ~ N(0, c ^ -0.5) sqrtc_2pi *= M_1_SQRT2PI; } double LevyRand::f(double x) const { if (x <= mu) return 0; double xInv = 1.0 / (x - mu); double y = -0.5 * c * xInv; y = std::exp(y); y *= xInv; y *= std::sqrt(xInv); return sqrtc_2pi * y; } double LevyRand::F(double x) const { if (x <= mu) return 0; double y = x - mu; y += y; y = c / y; y = std::sqrt(y); return std::erfc(y); } double LevyRand::variate() const { double rv = X.variate(); rv *= rv; rv = 1.0 / rv; return mu + rv; } double LevyRand::Mean() const { return INFINITY; } double LevyRand::Variance() const { return INFINITY; } std::complex<double> LevyRand::CF(double t) const { std::complex<double> y(0.0, -2 * c * t); y = -std::sqrt(y); y += std::complex<double>(0.0, mu * t); return std::exp(y); } double LevyRand::Quantile(double p) const { if (p == 0.0) return mu; double x = 1.0 / X.Quantile(0.5 * p); return mu + x * x; } double LevyRand::Mode() const { return c / 3.0 + mu; } double LevyRand::Skewness() const { return NAN; } double LevyRand::ExcessKurtosis() const { return NAN; } bool LevyRand::checkValidity(const QVector<double> &sample) { for (double var : sample) { if (var <= mu) return false; } return true; } bool LevyRand::fitScale_MLE(const QVector<double> &sample) { int n = sample.size(); if (n <= 0 || !checkValidity(sample)) return false; long double invSum = 0.0; for (double var : sample) invSum += 1.0 / (var - mu); setScale(n / invSum); return true; } <|endoftext|>
<commit_before><commit_msg>tdf#84881: Move some variables one block level out<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <vcl/temporaryfonts.hxx> #include <osl/file.hxx> #include <rtl/bootstrap.hxx> #include <vcl/svapp.hxx> #include <vcl/outdev.hxx> void TemporaryFonts::clear() { OUString path = "${$BRAND_BASE_DIR/program/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}"; rtl::Bootstrap::expandMacros( path ); path += "/user/temp/fonts/"; osl::Directory dir( path ); dir.reset(); for(;;) { osl::DirectoryItem item; if( dir.getNextItem( item ) != osl::Directory::E_None ) break; osl::FileStatus status( osl_FileStatus_Mask_FileURL ); if( item.getFileStatus( status ) == osl::File::E_None ) osl::File::remove( status.getFileURL()); } } OUString TemporaryFonts::fileUrlForFont( const OUString& fontName, const char* fontStyle ) { OUString path = "${$BRAND_BASE_DIR/program/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}"; rtl::Bootstrap::expandMacros( path ); path += "/user/temp/fonts/"; osl::Directory::createPath( path ); OUString filename = fontName; filename += OStringToOUString( fontStyle, RTL_TEXTENCODING_ASCII_US ); filename += ".ttf"; // TODO is it always ttf? return path + filename; } void TemporaryFonts::activateFont( const OUString& fontName, const OUString& fileUrl ) { OutputDevice *pDevice = Application::GetDefaultDevice(); pDevice->AddTempDevFont( fileUrl, fontName ); pDevice->ImplUpdateAllFontData( true ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>do not use invalid Directory instance (OSL_ASSERT about a NULL pointer)<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <vcl/temporaryfonts.hxx> #include <osl/file.hxx> #include <rtl/bootstrap.hxx> #include <vcl/svapp.hxx> #include <vcl/outdev.hxx> void TemporaryFonts::clear() { OUString path = "${$BRAND_BASE_DIR/program/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}"; rtl::Bootstrap::expandMacros( path ); path += "/user/temp/fonts/"; osl::Directory dir( path ); if( dir.reset() == osl::Directory::E_None ) { for(;;) { osl::DirectoryItem item; if( dir.getNextItem( item ) != osl::Directory::E_None ) break; osl::FileStatus status( osl_FileStatus_Mask_FileURL ); if( item.getFileStatus( status ) == osl::File::E_None ) osl::File::remove( status.getFileURL()); } } } OUString TemporaryFonts::fileUrlForFont( const OUString& fontName, const char* fontStyle ) { OUString path = "${$BRAND_BASE_DIR/program/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}"; rtl::Bootstrap::expandMacros( path ); path += "/user/temp/fonts/"; osl::Directory::createPath( path ); OUString filename = fontName; filename += OStringToOUString( fontStyle, RTL_TEXTENCODING_ASCII_US ); filename += ".ttf"; // TODO is it always ttf? return path + filename; } void TemporaryFonts::activateFont( const OUString& fontName, const OUString& fileUrl ) { OutputDevice *pDevice = Application::GetDefaultDevice(); pDevice->AddTempDevFont( fileUrl, fontName ); pDevice->ImplUpdateAllFontData( true ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * SchemeShell.c * * Simple scheme shell * Copyright (c) 2008 Linas Vepstas <linas@linas.org> */ #ifdef HAVE_GUILE #include "SchemeShell.h" #include <libguile.h> #include <libguile/backtrace.h> #include <libguile/lang.h> #include "platform.h" #include "SchemeSmob.h" using namespace opencog; bool SchemeShell::is_inited = false; SchemeShell::SchemeShell(void) { if (!is_inited) { is_inited = true; scm_init_guile(); scm_init_debug(); scm_init_backtrace(); } funcs = new SchemeSmob(); pending_input = false; show_output = true; input_line = ""; normal_prompt = "guile> "; pending_prompt = "... "; } void SchemeShell::hush_output(bool hush) { show_output = !hush; } /* ============================================================== */ std::string SchemeShell::prt(SCM node) { if (scm_is_pair(node)) { std::string str = "("; SCM node_list = node; const char * sp = ""; do { str += sp; sp = " "; node = SCM_CAR (node_list); str += prt (node); node_list = SCM_CDR (node_list); } while (scm_is_pair(node_list)); // Print the rest -- the CDR part if (!scm_is_null(node_list)) { str += " . "; str += prt (node_list); } str += ")"; return str; } else if (scm_is_true(scm_symbol_p(node))) { node = scm_symbol_to_string(node); char * str = scm_to_locale_string(node); // std::string rv = "'"; // print the symbol escape std::string rv = ""; // err .. don't print it rv += str; free(str); return rv; } else if (scm_is_true(scm_string_p(node))) { char * str = scm_to_locale_string(node); std::string rv = "\""; rv += str; rv += "\""; free(str); return rv; } else if (SCM_SMOB_PREDICATE(SchemeSmob::cog_handle_tag, node)) { return SchemeSmob::handle_to_string(node); } else if (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, node)) { return SchemeSmob::misc_to_string(node); } else if (scm_is_number(node)) { #define NUMBUFSZ 60 char buff[NUMBUFSZ]; if (scm_is_signed_integer(node, INT_MIN, INT_MAX)) { snprintf (buff, NUMBUFSZ, "%ld", (long) scm_to_long(node)); } else if (scm_is_unsigned_integer(node, 0, UINT_MAX)) { snprintf (buff, NUMBUFSZ, "%lu", (unsigned long) scm_to_ulong(node)); } else if (scm_is_real(node)) { snprintf (buff, NUMBUFSZ, "%g", scm_to_double(node)); } else if (scm_is_complex(node)) { snprintf (buff, NUMBUFSZ, "%g +i %g", scm_c_real_part(node), scm_c_imag_part(node)); } else if (scm_is_rational(node)) { std::string rv; rv = prt(scm_numerator(node)); rv += "/"; rv += prt(scm_denominator(node)); return rv; } return buff; } else if (scm_is_true(scm_char_p(node))) { std::string rv; rv = (char) scm_to_char(node); return rv; } else if (scm_is_true(scm_boolean_p(node))) { if (scm_to_bool(node)) return "#t"; return "#f"; } else if (SCM_NULL_OR_NIL_P(node)) { // scm_is_null(x) is true when x is SCM_EOL // SCM_NILP(x) is true when x is SCM_ELISP_NIL return "()"; } else if (scm_is_eq(node, SCM_UNDEFINED)) { return "undefined"; } else if (scm_is_eq(node, SCM_EOF_VAL)) { return "eof"; } else if (scm_is_eq(node, SCM_UNSPECIFIED)) { return ""; } #if 0 else if (scm_is_true(scm_procedure_p(node))) { return "procedure"; } else if (scm_subr_p(node)) { return "subr"; } else if (scm_is_true(scm_operator_p(node))) { return "operator"; } else if (scm_is_true(scm_entity_p(node))) { return "entity"; } else if (scm_is_true(scm_variable_p(node))) { return "variable"; } #endif else { fprintf (stderr, "Error: unhandled type for guile printing: %p\n", node); return "#opencog-guile-error: unknown type"; } return ""; } /* ============================================================== */ SCM SchemeShell::catch_handler_wrapper (void *data, SCM tag, SCM throw_args) { SchemeShell *ss = (SchemeShell *)data; return ss->catch_handler(tag, throw_args); } SCM SchemeShell::catch_handler (SCM tag, SCM throw_args) { // Check for read error. If a read error, then wait for user to correct it. SCM re = scm_symbol_to_string(tag); char * restr = scm_to_locale_string(re); pending_input = false; if (0 == strcmp(restr, "read-error")) { pending_input = true; free(restr); // quit accumulating text on escape (^[), cancel (^X) or ^C char c = input_line[input_line.length()-1]; if ((0x6 == c) || (0x16 == c) || (0x18 == c) || (0x1b == c)) { pending_input = false; input_line = ""; } return SCM_EOL; } free(restr); // If its not a read error, then its a regular error; report it. caught_error = true; /* get string port into which we write the error message and stack. */ error_string_port = scm_open_output_string(); SCM port = error_string_port; if (scm_is_true(scm_list_p(throw_args)) && (scm_ilength(throw_args) >= 4)) { SCM stack = scm_make_stack (SCM_BOOL_T, SCM_EOL); SCM subr = SCM_CAR (throw_args); SCM message = SCM_CADR (throw_args); SCM parts = SCM_CADDR (throw_args); SCM rest = SCM_CADDDR (throw_args); if (scm_is_true (stack)) { SCM highlights; if (scm_is_eq (tag, scm_arg_type_key) || scm_is_eq (tag, scm_out_of_range_key)) highlights = rest; else highlights = SCM_EOL; scm_puts ("Backtrace:\n", port); scm_display_backtrace_with_highlights (stack, port, SCM_BOOL_F, SCM_BOOL_F, highlights); scm_newline (port); } scm_i_display_error (stack, port, subr, message, parts, rest); } else { printf("ERROR: thow args are unexpectedly short!\n"); } #if 0 /* find the stack, and conditionally display it */ SCM the_stack = scm_fluid_ref(SCM_CDR(scm_the_last_stack_fluid_var)); if (the_stack != SCM_BOOL_F) { scm_display_backtrace(the_stack, port, SCM_UNDEFINED, SCM_UNDEFINED); } #endif return SCM_BOOL_F; } /* ============================================================== */ /** * Evaluate the expression */ std::string SchemeShell::eval(const std::string &expr) { input_line += expr; caught_error = false; pending_input = false; SCM rc = scm_internal_catch (SCM_BOOL_T, (scm_t_catch_body) scm_c_eval_string, (void *) input_line.c_str(), SchemeShell::catch_handler_wrapper, this); if (pending_input) { if (show_output) return pending_prompt; else return ""; } pending_input = false; input_line = ""; if (caught_error) { std::string rv; rc = scm_get_output_string(error_string_port); char * str = scm_to_locale_string(rc); rv = str; free(str); scm_close_port(error_string_port); rv += "\n"; rv += normal_prompt; return rv; } else { if (show_output) { std::string rv; rv = prt(rc); rv += "\n"; rv += normal_prompt; return rv; } else return ""; } return "#<Error: Unreachable statement reached>"; } #endif /* ===================== END OF FILE ============================ */ <commit_msg>add some minor debug printing.<commit_after>/* * SchemeShell.c * * Simple scheme shell * Copyright (c) 2008 Linas Vepstas <linas@linas.org> */ #ifdef HAVE_GUILE #include "SchemeShell.h" #include <libguile.h> #include <libguile/backtrace.h> #include <libguile/lang.h> #include "platform.h" #include "SchemeSmob.h" using namespace opencog; bool SchemeShell::is_inited = false; SchemeShell::SchemeShell(void) { if (!is_inited) { is_inited = true; scm_init_guile(); scm_init_debug(); scm_init_backtrace(); } funcs = new SchemeSmob(); pending_input = false; show_output = true; input_line = ""; normal_prompt = "guile> "; pending_prompt = "... "; } void SchemeShell::hush_output(bool hush) { show_output = !hush; } /* ============================================================== */ std::string SchemeShell::prt(SCM node) { if (scm_is_pair(node)) { std::string str = "("; SCM node_list = node; const char * sp = ""; do { str += sp; sp = " "; node = SCM_CAR (node_list); str += prt (node); node_list = SCM_CDR (node_list); } while (scm_is_pair(node_list)); // Print the rest -- the CDR part if (!scm_is_null(node_list)) { str += " . "; str += prt (node_list); } str += ")"; return str; } else if (scm_is_true(scm_symbol_p(node))) { node = scm_symbol_to_string(node); char * str = scm_to_locale_string(node); // std::string rv = "'"; // print the symbol escape std::string rv = ""; // err .. don't print it rv += str; free(str); return rv; } else if (scm_is_true(scm_string_p(node))) { char * str = scm_to_locale_string(node); std::string rv = "\""; rv += str; rv += "\""; free(str); return rv; } else if (SCM_SMOB_PREDICATE(SchemeSmob::cog_handle_tag, node)) { return SchemeSmob::handle_to_string(node); } else if (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, node)) { return SchemeSmob::misc_to_string(node); } else if (scm_is_number(node)) { #define NUMBUFSZ 60 char buff[NUMBUFSZ]; if (scm_is_signed_integer(node, INT_MIN, INT_MAX)) { snprintf (buff, NUMBUFSZ, "%ld", (long) scm_to_long(node)); } else if (scm_is_unsigned_integer(node, 0, UINT_MAX)) { snprintf (buff, NUMBUFSZ, "%lu", (unsigned long) scm_to_ulong(node)); } else if (scm_is_real(node)) { snprintf (buff, NUMBUFSZ, "%g", scm_to_double(node)); } else if (scm_is_complex(node)) { snprintf (buff, NUMBUFSZ, "%g +i %g", scm_c_real_part(node), scm_c_imag_part(node)); } else if (scm_is_rational(node)) { std::string rv; rv = prt(scm_numerator(node)); rv += "/"; rv += prt(scm_denominator(node)); return rv; } return buff; } else if (scm_is_true(scm_char_p(node))) { std::string rv; rv = (char) scm_to_char(node); return rv; } else if (scm_is_true(scm_boolean_p(node))) { if (scm_to_bool(node)) return "#t"; return "#f"; } else if (SCM_NULL_OR_NIL_P(node)) { // scm_is_null(x) is true when x is SCM_EOL // SCM_NILP(x) is true when x is SCM_ELISP_NIL return "()"; } else if (scm_is_eq(node, SCM_UNDEFINED)) { return "undefined"; } else if (scm_is_eq(node, SCM_EOF_VAL)) { return "eof"; } else if (scm_is_eq(node, SCM_UNSPECIFIED)) { return ""; } else if (scm_is_true(scm_dynamic_object_p(node))) { return "#<dynamic object (XXX add name here)>"; } #if 0 else if (scm_is_true(scm_procedure_p(node))) { return "procedure"; } else if (scm_subr_p(node)) { return "subr"; } else if (scm_is_true(scm_operator_p(node))) { return "operator"; } else if (scm_is_true(scm_entity_p(node))) { return "entity"; } else if (scm_is_true(scm_variable_p(node))) { return "variable"; } #endif else { fprintf (stderr, "Error: unhandled type for guile printing: %p\n", node); return "#opencog-guile-error: unknown type"; } return ""; } /* ============================================================== */ SCM SchemeShell::catch_handler_wrapper (void *data, SCM tag, SCM throw_args) { SchemeShell *ss = (SchemeShell *)data; return ss->catch_handler(tag, throw_args); } SCM SchemeShell::catch_handler (SCM tag, SCM throw_args) { // Check for read error. If a read error, then wait for user to correct it. SCM re = scm_symbol_to_string(tag); char * restr = scm_to_locale_string(re); pending_input = false; if (0 == strcmp(restr, "read-error")) { pending_input = true; free(restr); // quit accumulating text on escape (^[), cancel (^X) or ^C char c = input_line[input_line.length()-1]; if ((0x6 == c) || (0x16 == c) || (0x18 == c) || (0x1b == c)) { pending_input = false; input_line = ""; } return SCM_EOL; } free(restr); // If its not a read error, then its a regular error; report it. caught_error = true; /* get string port into which we write the error message and stack. */ error_string_port = scm_open_output_string(); SCM port = error_string_port; if (scm_is_true(scm_list_p(throw_args)) && (scm_ilength(throw_args) >= 4)) { SCM stack = scm_make_stack (SCM_BOOL_T, SCM_EOL); SCM subr = SCM_CAR (throw_args); SCM message = SCM_CADR (throw_args); SCM parts = SCM_CADDR (throw_args); SCM rest = SCM_CADDDR (throw_args); if (scm_is_true (stack)) { SCM highlights; if (scm_is_eq (tag, scm_arg_type_key) || scm_is_eq (tag, scm_out_of_range_key)) highlights = rest; else highlights = SCM_EOL; scm_puts ("Backtrace:\n", port); scm_display_backtrace_with_highlights (stack, port, SCM_BOOL_F, SCM_BOOL_F, highlights); scm_newline (port); } scm_i_display_error (stack, port, subr, message, parts, rest); } else { printf("ERROR: thow args are unexpectedly short!\n"); } #if 0 /* find the stack, and conditionally display it */ SCM the_stack = scm_fluid_ref(SCM_CDR(scm_the_last_stack_fluid_var)); if (the_stack != SCM_BOOL_F) { scm_display_backtrace(the_stack, port, SCM_UNDEFINED, SCM_UNDEFINED); } #endif return SCM_BOOL_F; } /* ============================================================== */ /** * Evaluate the expression */ std::string SchemeShell::eval(const std::string &expr) { input_line += expr; caught_error = false; pending_input = false; SCM rc = scm_internal_catch (SCM_BOOL_T, (scm_t_catch_body) scm_c_eval_string, (void *) input_line.c_str(), SchemeShell::catch_handler_wrapper, this); if (pending_input) { if (show_output) return pending_prompt; else return ""; } pending_input = false; input_line = ""; if (caught_error) { std::string rv; rc = scm_get_output_string(error_string_port); char * str = scm_to_locale_string(rc); rv = str; free(str); scm_close_port(error_string_port); rv += "\n"; rv += normal_prompt; return rv; } else { if (show_output) { std::string rv; rv = prt(rc); rv += "\n"; rv += normal_prompt; return rv; } else return ""; } return "#<Error: Unreachable statement reached>"; } #endif /* ===================== END OF FILE ============================ */ <|endoftext|>
<commit_before>#include <cstdlib> #include <unistd.h> #include <sys/wait.h> #include <sys/stat.h> #include <syslog.h> #include <stdio.h> #include <string.h> #include <libgen.h> #include <limits.h> #include <string> #include <iostream> #include <fstream> int install(const char* serviceFile, const std::string& options); int uninstall(); void rundaemon(char* path, char** argv); void* logthread(void *); // wrap "must succeed" system calls into os class to avoid error handling spaghetti class os { public: static void pipe(int fildes[2], const char* desc); static int fork(const char* desc); static void close(int fd, const char* desc); static void dup2(int oldfd, int newfd, const char* desc); static void execvp(const char *file, char *const argv[], const char* desc); static void pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg, const char* desc); static void waitpid(pid_t pid, int *status, int options, const char* desc); static FILE* fdopen(int fd, const char *mode, const char* desc); static void setsid(const char* desc); static void chdir(const char* path, const char* desc); private: static void logfatal(const char* err, const char* desc); }; int logpipe[2]; int inpipe[2]; const char* logprefix = "pubsubsql"; const char* pubsubsqld = "/etc/init.d/pubsubsqld"; int main(int argc, char** argv) { // validate command line input std::string usage = "Usage: pubsubsqlsvc {install|uinstall}\""; if (argc < 2) { std::cerr << "NO COMMAND" << std::endl << usage << std::endl; return EXIT_FAILURE; } // execute command std::string command(argv[1]); if (command == "install") { std::string options; for (int i = 2; i < argc; i++) { char* arg = argv[i]; options.append(" "); options.append(arg); } return install(argv[0], options); } else if (command == "uninstall") { return uninstall(); } else if (command == "svc") { if (argc < 3) { std::cerr << "MISSING PUBSUBSQL EXECUTABLE PATH" << std::endl; return EXIT_FAILURE; } rundaemon(argv[2], argv + 2); } // invalid command std::cerr << "INVALID COMMAND: " << command << std::endl << usage << std::endl; return EXIT_FAILURE; } int install(const char* servicePath, const std::string& options) { std::cerr << "Installing pubsubsqld service..." << std::endl; // set paths char tempPath[PATH_MAX]; std::string pubsubsqlsvc = realpath(servicePath, tempPath); std::string temp = pubsubsqlsvc.c_str(); std::string pubsubsql(dirname(const_cast<char*>(temp.c_str()))); pubsubsql.append("/"); pubsubsql.append("pubsubsql"); // create script file std::string scriptd( "#!/bin/bash" "\n#" "\n# service daemon path" "\nSERVICE_PATH="); scriptd.append(pubsubsqlsvc); scriptd.append( "\n# pubsubsql path" "\nPUBSUBSQL_PATH="); scriptd.append(pubsubsql); scriptd.append( "\n#" "\n#" "\nstart() {" "\n $SERVICE_PATH svc $PUBSUBSQL_PATH "); scriptd.append(options); scriptd.append("\n}"); scriptd.append( "\n#" "\n#" "\nstop() {" "\n $PUBSUBSQL_PATH stop "); scriptd.append(options); scriptd.append("\n}"); scriptd.append( "\n#" "\n#" "\ncase \"$1\" in " "\n start) " "\n start " "\n ;;" "\n stop) " "\n stop " "\n ;;" "\n *)" "\n echo \"Usage: pubsubsqld {start|stop}\"" "\n exit 1 " "\n ;;" "\nesac" "\nexit $?"); // check if service exists if (0 == access(pubsubsqld, F_OK)) { std::cerr << "FAILED TO INSTALL PUBSUBSQLD SERVICE" << std::endl << "The service is already installed. " << std::endl << "Run [pubsubsqlsvc uninstall]" << " to uninstall the service before installing it." << std::endl; return EXIT_FAILURE; } // install the service (write script) std::ofstream fout(pubsubsqld, std::ios::out); if (!fout.is_open()) { std::cerr << "FAILED TO INSTALL PUBSUBSQLD SERVICE" << std::endl << "Can not open file: " << pubsubsqld << " for output operations." << std::endl << "MAKE SURE YOU ARE RUNNING WITH VALID ACCESS RIGHTS TO PERFORM THIS OPERATION" << std::endl; return EXIT_FAILURE; } fout << scriptd << std::endl; if (fout.bad()) { std::cerr << "FAILED TO INSTALL PUBSUBSQLD SERVICE" << std::endl << "Write operation for file:" << pubsubsqld << " failed."; return EXIT_FAILURE; } // success fout.close(); // add execute permission mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; chmod(pubsubsqld, mode); std::cerr << "Done." << std::endl; return EXIT_SUCCESS; } int uninstall() { std::cerr << "Uninstalling pubsubsqld service..." << std::endl; // check if installed if (0 != access(pubsubsqld, F_OK)) { std::cerr << "FAILED TO UNINSTALL PUBSUBSQLD SERVICE" << std::endl << "The service is not installed?" << std::endl; return EXIT_FAILURE; } // uninstall service (delete script) if (remove(pubsubsqld) != 0) { std::cerr << "FAILED TO UNINSTALL PUBSUBSQLD SERVICE" << std::endl << "MAKE SURE YOU ARE RUNNING WITH VALID ACCESS RIGHTS TO PERFORM THIS OPERATION" << std::endl; return EXIT_FAILURE; } // success std::cerr << "Done." << std::endl; return EXIT_SUCCESS; } void rundaemon(char* path, char** argv) { // first become a daemon if (os::fork("become background process") > 0) _exit(EXIT_SUCCESS); os::setsid("become a leader of new session"); if (os::fork("ensure we are not session leader") > 0) _exit(EXIT_SUCCESS); //os::chdir("/", "change to root directory"); os::close(STDIN_FILENO, "closing stdin"); os::close(STDOUT_FILENO, "closing stdout"); os::close(STDERR_FILENO, "closing stderr"); // try to close all open file descriptors int maxfd = sysconf(_SC_OPEN_MAX); if (-1 == maxfd) maxfd = 8192; // limit is indeterminate, so take a guess for (int fd = 0; fd < maxfd; fd++) close(fd); // we are daemon, start pubsubsql child process os::pipe(logpipe, "create pipe to redirect stderr to syslog"); os::pipe(inpipe, "create pipe to redirect to stdin"); int status = 0; pid_t childPid = os::fork("forking child process"); switch (childPid) { case 0: // child process context os::close(logpipe[0], "close read end of the logpipe"); os::close(inpipe[1], "close write end of inpipe"); // associate pipe with stdin if (inpipe[0] != STDIN_FILENO) { os::dup2(inpipe[0], STDIN_FILENO, "duplicate read pipe->STDIN_FILENO"); os::close(inpipe[0], "close duplicated read pipe->STDIN_FILENO"); } // associate pipe with stderr if (logpipe[1] != STDERR_FILENO) { os::dup2(logpipe[1], STDERR_FILENO, "duplicate write pipe->STDERR_FILENO"); os::close(logpipe[1], "close duplicated write pipe->STDERR_FILENO"); } os::execvp(path, argv, "starting pubsubsql"); break; default: // parent process context os::close(logpipe[1], "close write end of the logpipe"); os::close(inpipe[0], "close read end of inpipe"); // start thread to redirect err from pubsubsql to syslog pthread_t thread; os::pthread_create(&thread, NULL, logthread, NULL, "start logger thread"); os::waitpid(childPid, &status, 0, "waiting for child pubsubsql"); pthread_join(thread, NULL); _exit(status); } _exit(EXIT_SUCCESS); } void* logthread(void *) { FILE* f = os::fdopen(logpipe[0], "r", "set stream in logthread"); openlog(logprefix, LOG_PERROR, LOG_USER); const int BUFFER_SIZE = 4096; char buffer[1 + BUFFER_SIZE] = {0}; for (;;) { const char* line = fgets(buffer, BUFFER_SIZE, f); if (NULL == line) { // if we fail to read it indicates that child process is done break; } // redirect log message to syslog if (strncmp(line, "info", 4) == 0) { syslog(LOG_INFO, "%s", line); } else if (strncmp(line, "error", 5) == 0) { syslog(LOG_ERR, "%s", line); } else if (strncmp(line, "debug", 5) == 0) { syslog(LOG_DEBUG, "%s", line); } else { syslog(LOG_WARNING, "%s", line); } } closelog(); return NULL; } // os void os::pipe(int fildes[2], const char* desc) { if (-1 == ::pipe(fildes)) logfatal("pipe() failed", desc); } int os::fork(const char* desc) { int ret = ::fork(); if (-1 == ret) logfatal("fork() failed", desc); return ret; } void os::close(int fd, const char* desc) { if (-1 == ::close(fd)) logfatal("close() failed", desc); } void os::dup2(int oldfd, int newfd, const char* desc) { if (-1 == ::dup2(oldfd, newfd)) logfatal("dup2() failed", desc); } void os::execvp(const char *file, char *const argv[], const char* desc) { ::execvp(file, argv); logfatal("execvp() failed", desc); } void os::pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg, const char* desc) { if (0 != ::pthread_create(thread, attr, start_routine, arg)) logfatal("pthread_create() failed", desc); } void os::waitpid(pid_t pid, int *status, int options, const char* desc) { if (-1 == ::waitpid(pid, status, options)) logfatal("waitpid() failed", desc); } FILE* os::fdopen(int fd, const char *mode, const char* desc) { FILE* ret = ::fdopen(fd, mode); if (NULL == ret) logfatal("fdopen() failed", desc); return ret; } void os::setsid(const char* desc) { if (-1 == ::setsid()) logfatal("setsid() failed", desc); } void os::chdir(const char* path, const char* desc) { if (-1 == ::chdir(path)) logfatal("chdir() failed", desc); } // since we are not running in a terminal session, log to syslog and exit the process void os::logfatal(const char* err, const char* desc) { openlog(logprefix, LOG_PID | LOG_PERROR, LOG_USER); syslog(LOG_EMERG, "%s %s", err, desc); closelog(); _exit(EXIT_FAILURE); } <commit_msg>linux service add license<commit_after>/* Copyright (C) 2013 CompleteDB LLC. * * 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 PubSubSQL. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <unistd.h> #include <sys/wait.h> #include <sys/stat.h> #include <syslog.h> #include <stdio.h> #include <string.h> #include <libgen.h> #include <limits.h> #include <string> #include <iostream> #include <fstream> int install(const char* serviceFile, const std::string& options); int uninstall(); void rundaemon(char* path, char** argv); void* logthread(void *); // wrap "must succeed" system calls into os class to avoid error handling spaghetti class os { public: static void pipe(int fildes[2], const char* desc); static int fork(const char* desc); static void close(int fd, const char* desc); static void dup2(int oldfd, int newfd, const char* desc); static void execvp(const char *file, char *const argv[], const char* desc); static void pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg, const char* desc); static void waitpid(pid_t pid, int *status, int options, const char* desc); static FILE* fdopen(int fd, const char *mode, const char* desc); static void setsid(const char* desc); static void chdir(const char* path, const char* desc); private: static void logfatal(const char* err, const char* desc); }; int logpipe[2]; int inpipe[2]; const char* logprefix = "pubsubsql"; const char* pubsubsqld = "/etc/init.d/pubsubsqld"; int main(int argc, char** argv) { // validate command line input std::string usage = "Usage: pubsubsqlsvc {install|uinstall}\""; if (argc < 2) { std::cerr << "NO COMMAND" << std::endl << usage << std::endl; return EXIT_FAILURE; } // execute command std::string command(argv[1]); if (command == "install") { std::string options; for (int i = 2; i < argc; i++) { char* arg = argv[i]; options.append(" "); options.append(arg); } return install(argv[0], options); } else if (command == "uninstall") { return uninstall(); } else if (command == "svc") { if (argc < 3) { std::cerr << "MISSING PUBSUBSQL EXECUTABLE PATH" << std::endl; return EXIT_FAILURE; } rundaemon(argv[2], argv + 2); } // invalid command std::cerr << "INVALID COMMAND: " << command << std::endl << usage << std::endl; return EXIT_FAILURE; } int install(const char* servicePath, const std::string& options) { std::cerr << "Installing pubsubsqld service..." << std::endl; // set paths char tempPath[PATH_MAX]; std::string pubsubsqlsvc = realpath(servicePath, tempPath); std::string temp = pubsubsqlsvc.c_str(); std::string pubsubsql(dirname(const_cast<char*>(temp.c_str()))); pubsubsql.append("/"); pubsubsql.append("pubsubsql"); // create script file std::string scriptd( "#!/bin/bash" "\n#" "\n# service daemon path" "\nSERVICE_PATH="); scriptd.append(pubsubsqlsvc); scriptd.append( "\n# pubsubsql path" "\nPUBSUBSQL_PATH="); scriptd.append(pubsubsql); scriptd.append( "\n#" "\n#" "\nstart() {" "\n $SERVICE_PATH svc $PUBSUBSQL_PATH "); scriptd.append(options); scriptd.append("\n}"); scriptd.append( "\n#" "\n#" "\nstop() {" "\n $PUBSUBSQL_PATH stop "); scriptd.append(options); scriptd.append("\n}"); scriptd.append( "\n#" "\n#" "\ncase \"$1\" in " "\n start) " "\n start " "\n ;;" "\n stop) " "\n stop " "\n ;;" "\n *)" "\n echo \"Usage: pubsubsqld {start|stop}\"" "\n exit 1 " "\n ;;" "\nesac" "\nexit $?"); // check if service exists if (0 == access(pubsubsqld, F_OK)) { std::cerr << "FAILED TO INSTALL PUBSUBSQLD SERVICE" << std::endl << "The service is already installed. " << std::endl << "Run [pubsubsqlsvc uninstall]" << " to uninstall the service before installing it." << std::endl; return EXIT_FAILURE; } // install the service (write script) std::ofstream fout(pubsubsqld, std::ios::out); if (!fout.is_open()) { std::cerr << "FAILED TO INSTALL PUBSUBSQLD SERVICE" << std::endl << "Can not open file: " << pubsubsqld << " for output operations." << std::endl << "MAKE SURE YOU ARE RUNNING WITH VALID ACCESS RIGHTS TO PERFORM THIS OPERATION" << std::endl; return EXIT_FAILURE; } fout << scriptd << std::endl; if (fout.bad()) { std::cerr << "FAILED TO INSTALL PUBSUBSQLD SERVICE" << std::endl << "Write operation for file:" << pubsubsqld << " failed."; return EXIT_FAILURE; } // success fout.close(); // add execute permission mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; chmod(pubsubsqld, mode); std::cerr << "Done." << std::endl; return EXIT_SUCCESS; } int uninstall() { std::cerr << "Uninstalling pubsubsqld service..." << std::endl; // check if installed if (0 != access(pubsubsqld, F_OK)) { std::cerr << "FAILED TO UNINSTALL PUBSUBSQLD SERVICE" << std::endl << "The service is not installed?" << std::endl; return EXIT_FAILURE; } // uninstall service (delete script) if (remove(pubsubsqld) != 0) { std::cerr << "FAILED TO UNINSTALL PUBSUBSQLD SERVICE" << std::endl << "MAKE SURE YOU ARE RUNNING WITH VALID ACCESS RIGHTS TO PERFORM THIS OPERATION" << std::endl; return EXIT_FAILURE; } // success std::cerr << "Done." << std::endl; return EXIT_SUCCESS; } void rundaemon(char* path, char** argv) { // first become a daemon if (os::fork("become background process") > 0) _exit(EXIT_SUCCESS); os::setsid("become a leader of new session"); if (os::fork("ensure we are not session leader") > 0) _exit(EXIT_SUCCESS); //os::chdir("/", "change to root directory"); os::close(STDIN_FILENO, "closing stdin"); os::close(STDOUT_FILENO, "closing stdout"); os::close(STDERR_FILENO, "closing stderr"); // try to close all open file descriptors int maxfd = sysconf(_SC_OPEN_MAX); if (-1 == maxfd) maxfd = 8192; // limit is indeterminate, so take a guess for (int fd = 0; fd < maxfd; fd++) close(fd); // we are daemon, start pubsubsql child process os::pipe(logpipe, "create pipe to redirect stderr to syslog"); os::pipe(inpipe, "create pipe to redirect to stdin"); int status = 0; pid_t childPid = os::fork("forking child process"); switch (childPid) { case 0: // child process context os::close(logpipe[0], "close read end of the logpipe"); os::close(inpipe[1], "close write end of inpipe"); // associate pipe with stdin if (inpipe[0] != STDIN_FILENO) { os::dup2(inpipe[0], STDIN_FILENO, "duplicate read pipe->STDIN_FILENO"); os::close(inpipe[0], "close duplicated read pipe->STDIN_FILENO"); } // associate pipe with stderr if (logpipe[1] != STDERR_FILENO) { os::dup2(logpipe[1], STDERR_FILENO, "duplicate write pipe->STDERR_FILENO"); os::close(logpipe[1], "close duplicated write pipe->STDERR_FILENO"); } os::execvp(path, argv, "starting pubsubsql"); break; default: // parent process context os::close(logpipe[1], "close write end of the logpipe"); os::close(inpipe[0], "close read end of inpipe"); // start thread to redirect err from pubsubsql to syslog pthread_t thread; os::pthread_create(&thread, NULL, logthread, NULL, "start logger thread"); os::waitpid(childPid, &status, 0, "waiting for child pubsubsql"); pthread_join(thread, NULL); _exit(status); } _exit(EXIT_SUCCESS); } void* logthread(void *) { FILE* f = os::fdopen(logpipe[0], "r", "set stream in logthread"); openlog(logprefix, LOG_PERROR, LOG_USER); const int BUFFER_SIZE = 4096; char buffer[1 + BUFFER_SIZE] = {0}; for (;;) { const char* line = fgets(buffer, BUFFER_SIZE, f); if (NULL == line) { // if we fail to read it indicates that child process is done break; } // redirect log message to syslog if (strncmp(line, "info", 4) == 0) { syslog(LOG_INFO, "%s", line); } else if (strncmp(line, "error", 5) == 0) { syslog(LOG_ERR, "%s", line); } else if (strncmp(line, "debug", 5) == 0) { syslog(LOG_DEBUG, "%s", line); } else { syslog(LOG_WARNING, "%s", line); } } closelog(); return NULL; } // os void os::pipe(int fildes[2], const char* desc) { if (-1 == ::pipe(fildes)) logfatal("pipe() failed", desc); } int os::fork(const char* desc) { int ret = ::fork(); if (-1 == ret) logfatal("fork() failed", desc); return ret; } void os::close(int fd, const char* desc) { if (-1 == ::close(fd)) logfatal("close() failed", desc); } void os::dup2(int oldfd, int newfd, const char* desc) { if (-1 == ::dup2(oldfd, newfd)) logfatal("dup2() failed", desc); } void os::execvp(const char *file, char *const argv[], const char* desc) { ::execvp(file, argv); logfatal("execvp() failed", desc); } void os::pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg, const char* desc) { if (0 != ::pthread_create(thread, attr, start_routine, arg)) logfatal("pthread_create() failed", desc); } void os::waitpid(pid_t pid, int *status, int options, const char* desc) { if (-1 == ::waitpid(pid, status, options)) logfatal("waitpid() failed", desc); } FILE* os::fdopen(int fd, const char *mode, const char* desc) { FILE* ret = ::fdopen(fd, mode); if (NULL == ret) logfatal("fdopen() failed", desc); return ret; } void os::setsid(const char* desc) { if (-1 == ::setsid()) logfatal("setsid() failed", desc); } void os::chdir(const char* path, const char* desc) { if (-1 == ::chdir(path)) logfatal("chdir() failed", desc); } // since we are not running in a terminal session, log to syslog and exit the process void os::logfatal(const char* err, const char* desc) { openlog(logprefix, LOG_PID | LOG_PERROR, LOG_USER); syslog(LOG_EMERG, "%s %s", err, desc); closelog(); _exit(EXIT_FAILURE); } <|endoftext|>
<commit_before>// // ImageQueue.cpp // FluxOF // // Created by Jonas Jongejan on 14/06/14. // // #include "ImageQueue.h" void ImageQueue::setupUI(){ incommingSizeLabel = gui->addLabel("");; oldSizeLabel = gui->addLabel("");; lastImageUI = gui->addImage("Last image", nil, 100, 100, true); currentImageUI = gui->addImage("Next image", nil, 100, 100, true); gui->autoSizeToFitWidgets(); } void ImageQueue::update(){ incommingSizeLabel->setLabel(ofToString(incommingItemsQueue.size())+" incomming items"); oldSizeLabel->setLabel(ofToString(oldItemsQueue.size())+" old items"); // Check if there are items that need to get loaded // for(int i=0;i<incommingItemsQueue.size();i++){ if(!incommingItemsQueue[i].image.isAllocated()){ incommingItemsQueue[i].image.loadImage(incommingItemsQueue[i].path); } } for(int i=0;i<oldItemsQueue.size();i++){ if(!oldItemsQueue[i].image.isAllocated()){ oldItemsQueue[i].image.loadImage(oldItemsQueue[i].path); } } // Determine if we should start a new transition // if(renderEngine->transitionDone() || currentItem.path.length() == 0){ // Determine if the transition should be delayed // if(transitionDelay == -1){ if(incommingItemsQueue.size() > 0){ transitionDelay = 0; } else { transitionDelay = ofRandom(5); } } transitionDelay -= 1.0/ofGetFrameRate(); //If the delay counter has reached zero, then do the transition if(transitionDelay <= 0){ transitionToNextItem(); } } } // // Determines what next image to show, and starts the transition and does some cleanup // void ImageQueue::transitionToNextItem(){ //Determine if there are new images to show, or we should pick an old one // if(incommingItemsQueue.size() > 0){ //Transition to the first item in the incommint items incommingItemsQueue[0].takePhoto = true; transitionTo(incommingItemsQueue[0]); oldItemsQueue.push_back(incommingItemsQueue[0]); incommingItemsQueue.pop_front(); } else if(oldItemsQueue.size() > 0){ //Transition to the first item in the old items, and move it to the back oldItemsQueue[0].takePhoto = false; transitionTo(oldItemsQueue[0]); oldItemsQueue.push_back(oldItemsQueue[0]); oldItemsQueue.pop_front(); } cleanupQueue(); storeQueueToFile(); } // // Starts a transition to a given queue item // void ImageQueue::transitionTo(QueueItem item){ lastItem = currentItem; currentItem = item; // Tell the render engine to start the transition // renderEngine->startTransitionTo(currentItem); renderEngine->getTimeline()->setDurationInSeconds(10); // Update the UI to show the images we transition between // if(lastItem.image.bAllocated()) lastImageUI->setImage(&lastItem.image); currentImageUI->setImage(&currentItem.image); } // // This function will go through the old items queue and remove duplicates // void ImageQueue::cleanupQueue(){ for(int i=0;i<oldItemsQueue.size();i++){ for(int u=i+1;u<oldItemsQueue.size();u++){ if(oldItemsQueue[i].itemId == oldItemsQueue[u].itemId){ oldItemsQueue.erase(oldItemsQueue.begin()+i); } } } for(int i=0;i<oldItemsQueue.size();i++){ if(oldItemsQueue.size() > 3 && (ofGetUnixTime()-oldItemsQueue[i].timestamp) > 60*60){ cout<<"Delete element because its old ("<<oldItemsQueue[i].timestamp<<") now its "<<ofGetUnixTime()<<" "<<(ofGetUnixTime()-oldItemsQueue[i].timestamp)<<endl; oldItemsQueue.erase(oldItemsQueue.begin()+i); i--; } } } // // Stores the old items queue to a file in case the application needs to restart // void ImageQueue::storeQueueToFile(){ storedQueue.clear(); for(int i=0;i<oldItemsQueue.size();i++){ storedQueue.addTag("item"); storedQueue.setValue("item:username", oldItemsQueue[i].username, i); storedQueue.setValue("item:itemId", oldItemsQueue[i].itemId, i); storedQueue.setValue("item:path", oldItemsQueue[i].path, i); storedQueue.setValue("item:timestamp", oldItemsQueue[i].timestamp, i); } storedQueue.save("imageQueue.xml"); } // // Loads the file from the previous function // void ImageQueue::loadQueueFromFile(){ ofxXmlSettings load; load.load("imageQueue.xml"); for(int i=0;i<load.getNumTags("item");i++){ load.pushTag("item",i); QueueItem newItem; newItem.path = load.getValue("path", ""); newItem.username = load.getValue("username", ""); newItem.itemId = load.getValue("itemId", 0); newItem.takePhoto = false; newItem.timestamp = load.getValue("timestamp", (int)ofGetUnixTime()); oldItemsQueue.push_back(newItem); load.popTag(); } } void ImageQueue::loadQueueFromDir(){ //Mockup data string path = "images"; ofDirectory backgroundsDir(path); if(backgroundsDir.exists()){ backgroundsDir.listDir(); int total = backgroundsDir.getFiles().size(); for (int i = 0; i < total; i++) { QueueItem newItem; newItem.path = "images/"+backgroundsDir.getName(i); newItem.image.loadImage(newItem.path); newItem.username = "@Username"+ofToString(i+1); incommingItemsQueue.push_back(newItem); } } transitionDelay = -1; } // // // void ImageQueue::guiEvent(ofxUIEventArgs &e){ } <commit_msg>image queue update<commit_after>// // ImageQueue.cpp // FluxOF // // Created by Jonas Jongejan on 14/06/14. // // #include "ImageQueue.h" void ImageQueue::setupUI(){ incommingSizeLabel = gui->addLabel("");; oldSizeLabel = gui->addLabel("");; lastImageUI = gui->addImage("Last image", nil, 100, 100, true); currentImageUI = gui->addImage("Next image", nil, 100, 100, true); gui->autoSizeToFitWidgets(); } void ImageQueue::update(){ incommingSizeLabel->setLabel(ofToString(incommingItemsQueue.size())+" incomming items"); oldSizeLabel->setLabel(ofToString(oldItemsQueue.size())+" old items"); // Check if there are items that need to get loaded // for(int i=0;i<incommingItemsQueue.size();i++){ if(!incommingItemsQueue[i].image.isAllocated()){ incommingItemsQueue[i].image.loadImage(incommingItemsQueue[i].path); } } for(int i=0;i<oldItemsQueue.size();i++){ if(!oldItemsQueue[i].image.isAllocated()){ oldItemsQueue[i].image.loadImage(oldItemsQueue[i].path); } } // Determine if we should start a new transition // if(renderEngine->transitionDone() || currentItem.path.length() == 0){ // Determine if the transition should be delayed // if(transitionDelay == -1){ if(incommingItemsQueue.size() > 0){ transitionDelay = 0; } else { transitionDelay = ofRandom(5); } } transitionDelay -= 1.0/ofGetFrameRate(); //If the delay counter has reached zero, then do the transition if(transitionDelay <= 0){ transitionToNextItem(); } } } // // Determines what next image to show, and starts the transition and does some cleanup // void ImageQueue::transitionToNextItem(){ //Determine if there are new images to show, or we should pick an old one // if(incommingItemsQueue.size() > 0){ //Transition to the first item in the incommint items incommingItemsQueue[0].takePhoto = true; transitionTo(incommingItemsQueue[0]); oldItemsQueue.push_back(incommingItemsQueue[0]); incommingItemsQueue.pop_front(); } else if(oldItemsQueue.size() > 0){ //Transition to the first item in the old items, and move it to the back oldItemsQueue[0].takePhoto = false; transitionTo(oldItemsQueue[0]); oldItemsQueue.push_back(oldItemsQueue[0]); oldItemsQueue.pop_front(); } cleanupQueue(); storeQueueToFile(); } // // Starts a transition to a given queue item // void ImageQueue::transitionTo(QueueItem item){ lastItem = currentItem; currentItem = item; // Tell the render engine to start the transition // renderEngine->startTransitionTo(currentItem); renderEngine->getTimeline()->setDurationInSeconds(10); // Update the UI to show the images we transition between // if(lastItem.image.bAllocated()) lastImageUI->setImage(&lastItem.image); currentImageUI->setImage(&currentItem.image); } // // This function will go through the old items queue and remove duplicates // void ImageQueue::cleanupQueue(){ for(int i=0;i<oldItemsQueue.size();i++){ for(int u=i+1;u<oldItemsQueue.size();u++){ if(oldItemsQueue[i].itemId == oldItemsQueue[u].itemId){ oldItemsQueue.erase(oldItemsQueue.begin()+i); } } } for(int i=0;i<oldItemsQueue.size();i++){ if(oldItemsQueue.size() > 10 && (ofGetUnixTime()-oldItemsQueue[i].timestamp) > 60*60){ cout<<"Delete element because its old ("<<oldItemsQueue[i].timestamp<<") now its "<<ofGetUnixTime()<<" "<<(ofGetUnixTime()-oldItemsQueue[i].timestamp)<<endl; oldItemsQueue.erase(oldItemsQueue.begin()+i); i--; } } } // // Stores the old items queue to a file in case the application needs to restart // void ImageQueue::storeQueueToFile(){ storedQueue.clear(); for(int i=0;i<oldItemsQueue.size();i++){ storedQueue.addTag("item"); storedQueue.setValue("item:username", oldItemsQueue[i].username, i); storedQueue.setValue("item:itemId", oldItemsQueue[i].itemId, i); storedQueue.setValue("item:path", oldItemsQueue[i].path, i); storedQueue.setValue("item:timestamp", oldItemsQueue[i].timestamp, i); } storedQueue.save("imageQueue.xml"); } // // Loads the file from the previous function // void ImageQueue::loadQueueFromFile(){ ofxXmlSettings load; load.load("imageQueue.xml"); for(int i=0;i<load.getNumTags("item");i++){ load.pushTag("item",i); QueueItem newItem; newItem.path = load.getValue("path", ""); newItem.username = load.getValue("username", ""); newItem.itemId = load.getValue("itemId", 0); newItem.takePhoto = false; newItem.timestamp = load.getValue("timestamp", (int)ofGetUnixTime()); oldItemsQueue.push_back(newItem); load.popTag(); } } void ImageQueue::loadQueueFromDir(){ //Mockup data string path = "images"; ofDirectory backgroundsDir(path); if(backgroundsDir.exists()){ backgroundsDir.listDir(); int total = backgroundsDir.getFiles().size(); for (int i = 0; i < total; i++) { QueueItem newItem; newItem.path = "images/"+backgroundsDir.getName(i); newItem.image.loadImage(newItem.path); newItem.username = "@Username"+ofToString(i+1); incommingItemsQueue.push_back(newItem); } } transitionDelay = -1; } // // // void ImageQueue::guiEvent(ofxUIEventArgs &e){ } <|endoftext|>
<commit_before>#include <string> #include <utility> #include <ros/ros.h> #include <controller_manager/controller_manager.h> #include <hardware_interface/joint_command_interface.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> class Arcsys2HW : public hardware_interface::RobotHW { public: Arcsys2HW(); void read(); void write(); ros::Time getTime() const; ros::Duration getPeriod() const; private: static constexpr std::size_t JOINT_COUNT {6}; hardware_interface::JointStateInterface joint_state_interface; hardware_interface::PositionJointInterface joint_pos_interface; double cmd[JOINT_COUNT]; double pos[JOINT_COUNT]; double vel[JOINT_COUNT]; double eff[JOINT_COUNT]; }; int main(int argc, char *argv[]) { ros::init(argc, argv, "arcsys2_control_node"); Arcsys2HW robot {}; controller_manager::ControllerManager cm {&robot}; ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner {1}; spinner.start(); while(ros::ok()) { robot.read(); cm.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } spinner.stop(); return 0; } inline Arcsys2HW::Arcsys2HW() : joint_state_interface {}, joint_pos_interface {}, cmd {}, pos {}, vel {}, eff {} { // [input] connect and register the joint state interface joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"rail_to_shaft_joint", &pos[0], &vel[0], &eff[0]}); joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"shaft_to_arm0_joint", &pos[1], &vel[1], &eff[1]}); joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"arm0_to_arm1_joint", &pos[2], &vel[2], &eff[2]}); joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"arm1_to_arm2_joint", &pos[3], &vel[3], &eff[3]}); joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"arm2_to_effector_base_joint", &pos[4], &vel[4], &eff[4]}); joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"effector_base_to_effector_end_joint", &pos[5], &vel[5], &eff[5]}); registerInterface(&joint_state_interface); // [output] connect and register the joint position interface joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("rail_to_shaft_joint"), &cmd[0]}); joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("shaft_to_arm0_joint"), &cmd[1]}); joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("arm0_to_arm1_joint"), &cmd[2]}); joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("arm1_to_arm2_joint"), &cmd[3]}); joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("arm2_to_effector_base_joint"), &cmd[4]}); joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("effector_base_to_effector_end_joint"), &cmd[5]}); registerInterface(&joint_pos_interface); } inline void Arcsys2HW::read() { for (std::size_t i {0}; i < 6; i++) ROS_INFO_STREAM("cmd[" << i << "]: " << cmd[i]); } inline void Arcsys2HW::write() { for (std::size_t i {-1}; i < 6; i++) pos[i] = cmd[i]; } } inline ros::Time Arcsys2HW::getTime() const { return ros::Time::now(); } inline ros::Duration Arcsys2HW::getPeriod() const { return ros::Duration(0.01); } <commit_msg>Fix breaking code<commit_after>#include <string> #include <utility> #include <ros/ros.h> #include <controller_manager/controller_manager.h> #include <hardware_interface/joint_command_interface.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> class Arcsys2HW : public hardware_interface::RobotHW { public: Arcsys2HW(); void read(); void write(); ros::Time getTime() const; ros::Duration getPeriod() const; private: static constexpr std::size_t JOINT_COUNT {6}; hardware_interface::JointStateInterface joint_state_interface; hardware_interface::PositionJointInterface joint_pos_interface; double cmd[JOINT_COUNT]; double pos[JOINT_COUNT]; double vel[JOINT_COUNT]; double eff[JOINT_COUNT]; }; int main(int argc, char *argv[]) { ros::init(argc, argv, "arcsys2_control_node"); Arcsys2HW robot {}; controller_manager::ControllerManager cm {&robot}; ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner {1}; spinner.start(); while(ros::ok()) { robot.read(); cm.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } spinner.stop(); return 0; } inline Arcsys2HW::Arcsys2HW() : joint_state_interface {}, joint_pos_interface {}, cmd {}, pos {}, vel {}, eff {} { // [input] connect and register the joint state interface joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"rail_to_shaft_joint", &pos[0], &vel[0], &eff[0]}); joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"shaft_to_arm0_joint", &pos[1], &vel[1], &eff[1]}); joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"arm0_to_arm1_joint", &pos[2], &vel[2], &eff[2]}); joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"arm1_to_arm2_joint", &pos[3], &vel[3], &eff[3]}); joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"arm2_to_effector_base_joint", &pos[4], &vel[4], &eff[4]}); joint_state_interface.registerHandle(hardware_interface::JointStateHandle {"effector_base_to_effector_end_joint", &pos[5], &vel[5], &eff[5]}); registerInterface(&joint_state_interface); // [output] connect and register the joint position interface joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("rail_to_shaft_joint"), &cmd[0]}); joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("shaft_to_arm0_joint"), &cmd[1]}); joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("arm0_to_arm1_joint"), &cmd[2]}); joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("arm1_to_arm2_joint"), &cmd[3]}); joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("arm2_to_effector_base_joint"), &cmd[4]}); joint_pos_interface.registerHandle(hardware_interface::JointHandle {joint_state_interface.getHandle("effector_base_to_effector_end_joint"), &cmd[5]}); registerInterface(&joint_pos_interface); } inline void Arcsys2HW::read() { for (std::size_t i {0}; i < 6; i++) ROS_INFO_STREAM("cmd[" << i << "]: " << cmd[i]); } inline void Arcsys2HW::write() { for (std::size_t i {0}; i < 6; i++) pos[i] = cmd[i]; } inline ros::Time Arcsys2HW::getTime() const { return ros::Time::now(); } inline ros::Duration Arcsys2HW::getPeriod() const { return ros::Duration(0.01); } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * * expr_transformer.cpp * file description * * Copyright(c) 2015, CMU * *------------------------------------------------------------------------- */ #include <unordered_map> #include "nodes/pprint.h" #include "utils/rel.h" #include "utils/lsyscache.h" #include "parser/parsetree.h" #include "backend/bridge/dml/tuple/tuple_transformer.h" #include "backend/bridge/dml/expr/pg_func_map.h" #include "backend/bridge/dml/expr/expr_transformer.h" #include "backend/bridge/dml/executor/plan_executor.h" #include "backend/common/logger.h" #include "backend/common/value.h" #include "backend/common/value_factory.h" #include "backend/expression/expression_util.h" namespace peloton { namespace bridge { expression::AbstractExpression* ReMapPgFunc(Oid pg_func_id, expression::AbstractExpression* lc, expression::AbstractExpression* rc); extern std::unordered_map<Oid, peloton::ExpressionType> pg_func_map; void ExprTransformer::PrintPostgressExprTree(const ExprState* expr_state, std::string prefix) { auto tag = nodeTag(expr_state->expr); /* TODO Not complete. * Not all ExprState has a child / children list, * so it would take some multiplexing to print it recursively here. */ LOG_INFO("%u ", tag); } /** * @brief Transform a ExprState tree (Postgres) to a AbstractExpression tree (Peloton) recursively. */ expression::AbstractExpression* ExprTransformer::TransformExpr( const ExprState* expr_state) { if(!expr_state) return nullptr; /* Special case: * Input is a list of expressions. * Transform it to a conjunction tree. */ if(expr_state->type == T_List) { return TransformList(expr_state); } expression::AbstractExpression* peloton_expr = nullptr; switch (nodeTag(expr_state->expr)) { case T_Const: peloton_expr = TransformConst(expr_state); break; case T_OpExpr: peloton_expr = TransformOp(expr_state); break; case T_Var: peloton_expr = TransformVar(expr_state); break; case T_BoolExpr: peloton_expr = TransformBool(expr_state); break; case T_Param: peloton_expr = TransformParam(expr_state); break; case T_RelabelType: peloton_expr = TransformRelabelType(expr_state); break; case T_FuncExpr: peloton_expr = TransformFunc(expr_state); break; default: LOG_ERROR("Unsupported Postgres Expr type: %u (see 'nodes.h')\n", nodeTag(expr_state->expr)); } return peloton_expr; } bool ExprTransformer::CleanExprTree(expression::AbstractExpression* root) { // AbstractExpression's destructor already handles deleting children delete root; return true; } expression::AbstractExpression* ExprTransformer::TransformConst( const ExprState* es) { auto const_expr = reinterpret_cast<const Const*>(es->expr); Value value; if (const_expr->constisnull) { // Constant is null value = ValueFactory::GetNullValue(); } else if(const_expr->constbyval){ // non null value = TupleTransformer::GetValue(const_expr->constvalue, const_expr->consttype); } else if(const_expr->constlen == -1) { LOG_INFO("Probably handing a string constant \n"); value = TupleTransformer::GetValue(const_expr->constvalue, const_expr->consttype); } else { LOG_ERROR("Unknown Const profile: constlen = %d , constbyval = %d, constvalue = %lu \n", const_expr->constlen, const_expr->constbyval, (long unsigned)const_expr->constvalue); } LOG_INFO("Const : "); std::cout << value << std::endl; // A Const Expr has no children. return expression::ConstantValueFactory(value); } expression::AbstractExpression* ExprTransformer::TransformOp( const ExprState* es) { LOG_INFO("Transform Op \n"); auto op_expr = reinterpret_cast<const OpExpr*>(es->expr); auto func_state = reinterpret_cast<const FuncExprState*>(es); assert(op_expr->opfuncid != 0); // Hopefully it has been filled in by PG planner assert(list_length(func_state->args) <= 2); // Hopefully it has at most two parameters expression::AbstractExpression* lc = nullptr; expression::AbstractExpression* rc = nullptr; // Add function arguments as children int i = 0; ListCell *arg; foreach(arg, func_state->args) { ExprState *argstate = (ExprState *) lfirst(arg); if(i == 0) lc = TransformExpr(argstate); else if(i == 1) rc = TransformExpr(argstate); else break; // skip >2 arguments i++; } return ReMapPgFunc(op_expr->opfuncid, lc, rc); } expression::AbstractExpression* ExprTransformer::TransformVar( const ExprState* es) { // Var expr only needs default ES auto var_expr = reinterpret_cast<const Var*>(es->expr); assert(var_expr->varattno != InvalidAttrNumber); oid_t tuple_idx = (var_expr->varno == INNER_VAR ? 1 : 0); // Seems reasonable, c.f. ExecEvalScalarVarFast() oid_t value_idx = static_cast<oid_t>(var_expr->varattno - 1); // Damnit attno is 1-index LOG_INFO("tuple_idx = %u , value_idx = %u \n", tuple_idx, value_idx); // TupleValue expr has no children. return expression::TupleValueFactory(tuple_idx, value_idx); } expression::AbstractExpression* ExprTransformer::TransformBool( const ExprState* es) { auto bool_expr = reinterpret_cast<const BoolExpr*>(es->expr); auto bool_state = reinterpret_cast<const BoolExprState*>(es); auto bool_op = bool_expr->boolop; /* * AND and OR can take >=2 arguments, * while NOT should take only one. */ assert(bool_state->args); assert(bool_op != NOT_EXPR || list_length(bool_state->args) == 1); assert(bool_op == NOT_EXPR || list_length(bool_state->args) >= 2); auto args = bool_state->args; switch(bool_op){ case AND_EXPR: LOG_INFO("Bool AND list \n"); return TransformList(reinterpret_cast<const ExprState*>(args), EXPRESSION_TYPE_CONJUNCTION_AND); case OR_EXPR: LOG_INFO("Bool OR list \n"); return TransformList(reinterpret_cast<const ExprState*>(args), EXPRESSION_TYPE_CONJUNCTION_OR); case NOT_EXPR: { LOG_INFO("Bool NOT \n"); auto child_es = reinterpret_cast<const ExprState*>(lfirst(list_head(args))); auto child = TransformExpr(child_es); return expression::OperatorFactory(EXPRESSION_TYPE_OPERATOR_NOT, child, nullptr); } default: LOG_ERROR("Unrecognized BoolExpr : %u", bool_op); } return nullptr; } expression::AbstractExpression* ExprTransformer::TransformParam(const ExprState *es) { auto param_expr = reinterpret_cast<const Param*>(es->expr); switch (param_expr->paramkind) { case PARAM_EXTERN: LOG_INFO("Handle EXTREN PARAM"); return expression::ParameterValueFactory(param_expr->paramid - 1); // 1 indexed break; default: LOG_ERROR("Unrecognized param kind %d", param_expr->paramkind); break; } return nullptr; } expression::AbstractExpression* ExprTransformer::TransformRelabelType(const ExprState *es) { auto state = reinterpret_cast<const GenericExprState*>(es); auto expr = reinterpret_cast<const RelabelType *>(es->expr); auto child_state = state->arg; auto child_expr = expr->arg; assert(expr->xpr.type == T_RelabelType); LOG_INFO("child is of type %d, %d", child_expr->type, child_state->type); LOG_INFO("%d, %d", expr->resulttype, expr->relabelformat); expression::AbstractExpression *child = ExprTransformer::TransformExpr(child_state); //TODO: not implemented yet return child; } expression::AbstractExpression* ExprTransformer::TransformFunc(const ExprState *es) { auto state = reinterpret_cast<const FuncExprState*>(es); auto expr = reinterpret_cast<const FuncExpr*>(es->expr); auto expr_args = reinterpret_cast<const ExprState*>(state->args); assert(expr->xpr.type == T_FuncExpr); LOG_INFO("Return type: %d, isReturn %d, Coercion: %d", expr->funcresulttype, expr->funcretset, expr->funcformat); expression::AbstractExpression *args = ExprTransformer::TransformExpr(expr_args); LOG_INFO("args : %s", args->DebugInfo(" ").c_str()); //TODO: not implemented yet return nullptr; } expression::AbstractExpression* ExprTransformer::TransformList(const ExprState* es, ExpressionType et) { assert(et == EXPRESSION_TYPE_CONJUNCTION_AND || et == EXPRESSION_TYPE_CONJUNCTION_OR); const List* list = reinterpret_cast<const List*>(es); ListCell *l; int length = list_length(list); assert(length > 0); LOG_INFO("Expression List of length %d", length); std::list<expression::AbstractExpression*> exprs; // a list of AND'ed expressions foreach(l, list) { const ExprState *expr_state = reinterpret_cast<const ExprState*>(lfirst(l)); exprs.push_back(ExprTransformer::TransformExpr(expr_state)); } return expression::ConjunctionFactory(et, exprs); } /** * @brief Helper function: re-map Postgres's builtin function Oid * to proper expression type in Peloton * * @param pg_func_id PG Function Id used to lookup function in \b fmrg_builtin[] * (see Postgres source file 'fmgrtab.cpp') * @param lc Left child. * @param rc Right child. * @return Corresponding expression tree in peloton. */ expression::AbstractExpression* ReMapPgFunc(Oid func_id, expression::AbstractExpression* lc, expression::AbstractExpression* rc) { auto itr = pg_func_map.find(func_id); if(itr == pg_func_map.end()){ LOG_ERROR("Unsupported PG Function ID : %u (check fmgrtab.cpp)\n", func_id); return nullptr; } auto pl_expr_type = itr->second; switch(pl_expr_type){ case EXPRESSION_TYPE_COMPARE_EQ: case EXPRESSION_TYPE_COMPARE_NE: case EXPRESSION_TYPE_COMPARE_GT: case EXPRESSION_TYPE_COMPARE_LT: case EXPRESSION_TYPE_COMPARE_GTE: case EXPRESSION_TYPE_COMPARE_LTE: return expression::ComparisonFactory(pl_expr_type, lc, rc); case EXPRESSION_TYPE_OPERATOR_PLUS: case EXPRESSION_TYPE_OPERATOR_MINUS: case EXPRESSION_TYPE_OPERATOR_MULTIPLY: case EXPRESSION_TYPE_OPERATOR_DIVIDE: return expression::OperatorFactory(pl_expr_type, lc, rc); default: LOG_ERROR("This Peloton ExpressionType is in our map but not transformed here : %u", pl_expr_type); } return nullptr; } } // namespace bridge } // namespace peloton <commit_msg>add support for RelabelType expr<commit_after>/*------------------------------------------------------------------------- * * expr_transformer.cpp * file description * * Copyright(c) 2015, CMU * *------------------------------------------------------------------------- */ #include <unordered_map> #include "nodes/pprint.h" #include "utils/rel.h" #include "utils/lsyscache.h" #include "parser/parsetree.h" #include "backend/bridge/dml/tuple/tuple_transformer.h" #include "backend/bridge/dml/expr/pg_func_map.h" #include "backend/bridge/dml/expr/expr_transformer.h" #include "backend/bridge/dml/executor/plan_executor.h" #include "backend/common/logger.h" #include "backend/common/value.h" #include "backend/common/value_factory.h" #include "backend/expression/expression_util.h" namespace peloton { namespace bridge { expression::AbstractExpression* ReMapPgFunc(Oid pg_func_id, expression::AbstractExpression* lc, expression::AbstractExpression* rc); extern std::unordered_map<Oid, peloton::ExpressionType> pg_func_map; void ExprTransformer::PrintPostgressExprTree(const ExprState* expr_state, std::string prefix) { auto tag = nodeTag(expr_state->expr); /* TODO Not complete. * Not all ExprState has a child / children list, * so it would take some multiplexing to print it recursively here. */ LOG_INFO("%u ", tag); } /** * @brief Transform a ExprState tree (Postgres) to a AbstractExpression tree (Peloton) recursively. */ expression::AbstractExpression* ExprTransformer::TransformExpr( const ExprState* expr_state) { if(!expr_state) return nullptr; /* Special case: * Input is a list of expressions. * Transform it to a conjunction tree. */ if(expr_state->type == T_List) { return TransformList(expr_state); } expression::AbstractExpression* peloton_expr = nullptr; switch (nodeTag(expr_state->expr)) { case T_Const: peloton_expr = TransformConst(expr_state); break; case T_OpExpr: peloton_expr = TransformOp(expr_state); break; case T_Var: peloton_expr = TransformVar(expr_state); break; case T_BoolExpr: peloton_expr = TransformBool(expr_state); break; case T_Param: peloton_expr = TransformParam(expr_state); break; case T_RelabelType: peloton_expr = TransformRelabelType(expr_state); break; case T_FuncExpr: peloton_expr = TransformFunc(expr_state); break; default: LOG_ERROR("Unsupported Postgres Expr type: %u (see 'nodes.h')\n", nodeTag(expr_state->expr)); } return peloton_expr; } bool ExprTransformer::CleanExprTree(expression::AbstractExpression* root) { // AbstractExpression's destructor already handles deleting children delete root; return true; } expression::AbstractExpression* ExprTransformer::TransformConst( const ExprState* es) { auto const_expr = reinterpret_cast<const Const*>(es->expr); Value value; if (const_expr->constisnull) { // Constant is null value = ValueFactory::GetNullValue(); } else if(const_expr->constbyval){ // non null value = TupleTransformer::GetValue(const_expr->constvalue, const_expr->consttype); } else if(const_expr->constlen == -1) { LOG_INFO("Probably handing a string constant \n"); value = TupleTransformer::GetValue(const_expr->constvalue, const_expr->consttype); } else { LOG_ERROR("Unknown Const profile: constlen = %d , constbyval = %d, constvalue = %lu \n", const_expr->constlen, const_expr->constbyval, (long unsigned)const_expr->constvalue); } LOG_INFO("Const : "); std::cout << value << std::endl; // A Const Expr has no children. return expression::ConstantValueFactory(value); } expression::AbstractExpression* ExprTransformer::TransformOp( const ExprState* es) { LOG_INFO("Transform Op \n"); auto op_expr = reinterpret_cast<const OpExpr*>(es->expr); auto func_state = reinterpret_cast<const FuncExprState*>(es); assert(op_expr->opfuncid != 0); // Hopefully it has been filled in by PG planner assert(list_length(func_state->args) <= 2); // Hopefully it has at most two parameters expression::AbstractExpression* lc = nullptr; expression::AbstractExpression* rc = nullptr; // Add function arguments as children int i = 0; ListCell *arg; foreach(arg, func_state->args) { ExprState *argstate = (ExprState *) lfirst(arg); if(i == 0) lc = TransformExpr(argstate); else if(i == 1) rc = TransformExpr(argstate); else break; // skip >2 arguments i++; } return ReMapPgFunc(op_expr->opfuncid, lc, rc); } expression::AbstractExpression* ExprTransformer::TransformVar( const ExprState* es) { // Var expr only needs default ES auto var_expr = reinterpret_cast<const Var*>(es->expr); assert(var_expr->varattno != InvalidAttrNumber); oid_t tuple_idx = (var_expr->varno == INNER_VAR ? 1 : 0); // Seems reasonable, c.f. ExecEvalScalarVarFast() oid_t value_idx = static_cast<oid_t>(var_expr->varattno - 1); // Damnit attno is 1-index LOG_INFO("tuple_idx = %u , value_idx = %u \n", tuple_idx, value_idx); // TupleValue expr has no children. return expression::TupleValueFactory(tuple_idx, value_idx); } expression::AbstractExpression* ExprTransformer::TransformBool( const ExprState* es) { auto bool_expr = reinterpret_cast<const BoolExpr*>(es->expr); auto bool_state = reinterpret_cast<const BoolExprState*>(es); auto bool_op = bool_expr->boolop; /* * AND and OR can take >=2 arguments, * while NOT should take only one. */ assert(bool_state->args); assert(bool_op != NOT_EXPR || list_length(bool_state->args) == 1); assert(bool_op == NOT_EXPR || list_length(bool_state->args) >= 2); auto args = bool_state->args; switch(bool_op){ case AND_EXPR: LOG_INFO("Bool AND list \n"); return TransformList(reinterpret_cast<const ExprState*>(args), EXPRESSION_TYPE_CONJUNCTION_AND); case OR_EXPR: LOG_INFO("Bool OR list \n"); return TransformList(reinterpret_cast<const ExprState*>(args), EXPRESSION_TYPE_CONJUNCTION_OR); case NOT_EXPR: { LOG_INFO("Bool NOT \n"); auto child_es = reinterpret_cast<const ExprState*>(lfirst(list_head(args))); auto child = TransformExpr(child_es); return expression::OperatorFactory(EXPRESSION_TYPE_OPERATOR_NOT, child, nullptr); } default: LOG_ERROR("Unrecognized BoolExpr : %u", bool_op); } return nullptr; } expression::AbstractExpression* ExprTransformer::TransformParam(const ExprState *es) { auto param_expr = reinterpret_cast<const Param*>(es->expr); switch (param_expr->paramkind) { case PARAM_EXTERN: LOG_INFO("Handle EXTREN PARAM"); return expression::ParameterValueFactory(param_expr->paramid - 1); // 1 indexed break; default: LOG_ERROR("Unrecognized param kind %d", param_expr->paramkind); break; } return nullptr; } expression::AbstractExpression* ExprTransformer::TransformRelabelType(const ExprState *es) { auto state = reinterpret_cast<const GenericExprState*>(es); auto expr = reinterpret_cast<const RelabelType *>(es->expr); auto child_state = state->arg; assert(expr->relabelformat == COERCE_IMPLICIT_CAST); LOG_INFO("Handle relabel as %d", expr->resulttype); expression::AbstractExpression *child = ExprTransformer::TransformExpr(child_state); PostgresValueType type = static_cast<PostgresValueType>(expr->resulttype); return expression::CastFactory(type, child); } expression::AbstractExpression* ExprTransformer::TransformFunc(const ExprState *es) { auto state = reinterpret_cast<const FuncExprState*>(es); auto expr = reinterpret_cast<const FuncExpr*>(es->expr); auto expr_args = reinterpret_cast<const ExprState*>(state->args); assert(expr->xpr.type == T_FuncExpr); LOG_INFO("Return type: %d, isReturn %d, Coercion: %d", expr->funcresulttype, expr->funcretset, expr->funcformat); expression::AbstractExpression *args = ExprTransformer::TransformExpr(expr_args); LOG_INFO("args : %s", args->DebugInfo(" ").c_str()); //TODO: not implemented yet return nullptr; } expression::AbstractExpression* ExprTransformer::TransformList(const ExprState* es, ExpressionType et) { assert(et == EXPRESSION_TYPE_CONJUNCTION_AND || et == EXPRESSION_TYPE_CONJUNCTION_OR); const List* list = reinterpret_cast<const List*>(es); ListCell *l; int length = list_length(list); assert(length > 0); LOG_INFO("Expression List of length %d", length); std::list<expression::AbstractExpression*> exprs; // a list of AND'ed expressions foreach(l, list) { const ExprState *expr_state = reinterpret_cast<const ExprState*>(lfirst(l)); exprs.push_back(ExprTransformer::TransformExpr(expr_state)); } return expression::ConjunctionFactory(et, exprs); } /** * @brief Helper function: re-map Postgres's builtin function Oid * to proper expression type in Peloton * * @param pg_func_id PG Function Id used to lookup function in \b fmrg_builtin[] * (see Postgres source file 'fmgrtab.cpp') * @param lc Left child. * @param rc Right child. * @return Corresponding expression tree in peloton. */ expression::AbstractExpression* ReMapPgFunc(Oid func_id, expression::AbstractExpression* lc, expression::AbstractExpression* rc) { auto itr = pg_func_map.find(func_id); if(itr == pg_func_map.end()){ LOG_ERROR("Unsupported PG Function ID : %u (check fmgrtab.cpp)\n", func_id); return nullptr; } auto pl_expr_type = itr->second; switch(pl_expr_type){ case EXPRESSION_TYPE_COMPARE_EQ: case EXPRESSION_TYPE_COMPARE_NE: case EXPRESSION_TYPE_COMPARE_GT: case EXPRESSION_TYPE_COMPARE_LT: case EXPRESSION_TYPE_COMPARE_GTE: case EXPRESSION_TYPE_COMPARE_LTE: return expression::ComparisonFactory(pl_expr_type, lc, rc); case EXPRESSION_TYPE_OPERATOR_PLUS: case EXPRESSION_TYPE_OPERATOR_MINUS: case EXPRESSION_TYPE_OPERATOR_MULTIPLY: case EXPRESSION_TYPE_OPERATOR_DIVIDE: return expression::OperatorFactory(pl_expr_type, lc, rc); default: LOG_ERROR("This Peloton ExpressionType is in our map but not transformed here : %u", pl_expr_type); } return nullptr; } } // namespace bridge } // namespace peloton <|endoftext|>
<commit_before>#include <ruby.h> #include <stdio.h> #include <iostream> #include <sstream> #include "classad/classad_distribution.h" #include "classad/fnCall.h" using namespace std; #ifdef WANT_CLASSAD_NAMESPACE using namespace classad; #endif void print_value(FILE *fp, Value val, const char *name) { /* AFAICT the only way to get at the string in a 'Value' object is to use * the C++ stream operator <<, so we set up a stringstream and write * stuff we want into that.. */ std::stringstream sstr; sstr << name << " is " << val; fprintf(fp, "%s\n", sstr.str().c_str()); } /* * Perform our quota check against the deltacloud aggregator database. * This function expects: * * - Instance executable name as handed to condor so that we can map to the * instance found in the database. * - The username * - The provider url so we can map back to the provider. * - The realm key so we know what realm this is in. * * ... at least for now. Need to better analyze what is required to do all * the quota matching but that's the idea. */ bool deltacloud_quota_check(const char *name, const ArgumentList &arglist, EvalState &state, Value &result) { Value instance_key; Value account_id; FILE *fp; char msg[1024]; VALUE res; bool val = false; char *ruby_string; std::stringstream method_args; result.SetBooleanValue(false); fp = fopen(LOGFILE, "a"); if (arglist.size() != 2) { result.SetErrorValue(); fprintf(fp, "Expected 2 arguments, saw %d\n", arglist.size()); goto do_ret; } if (!arglist[0]->Evaluate(state, instance_key)) { result.SetErrorValue(); fprintf(fp, "Could not evaluate argument 0 to instance key\n"); goto do_ret; } if (!arglist[1]->Evaluate(state, account_id)) { result.SetErrorValue(); fprintf(fp, "Could not evaluate argument 1 to account_id\n"); goto do_ret; } if (instance_key.GetType() != Value::STRING_VALUE) { result.SetErrorValue(); fprintf(fp, "Instance type was not a string\n"); goto do_ret; } //print_value(fp, instance_key, "instance_key"); if (account_id.GetType() != Value::STRING_VALUE) { result.SetErrorValue(); fprintf(fp, "Account ID type was not a string\n"); goto do_ret; } //print_value(fp, account_id, "account_id"); ruby_init(); ruby_init_loadpath(); method_args << "'" << DELTACLOUD_INSTALL_DIR << "/config/database.yml', '" << instance_key << "', " << account_id; asprintf(&ruby_string, "$: << '%s/classad_plugin'\n" "$: << '%s/app/models'\n" "logf = File.new('%s', 'a')\n" "logf.puts \"Loading ruby support file from %s/classad_plugin\"\n" "begin\n" " require 'classad_plugin.rb'\n" " ret = classad_plugin(logf, %s)\n" "rescue Exception => ex\n" " logf.puts \"Error running classad plugin: #{ex.message}\"\n" " logf.puts ex.backtrace\n" " ret = false\n" "end\n" "logf.close\n" "ret", DELTACLOUD_INSTALL_DIR, DELTACLOUD_INSTALL_DIR, LOGFILE, DELTACLOUD_INSTALL_DIR, method_args.str().c_str()); fprintf(fp, "ruby string is %s\n", ruby_string); fflush(fp); res = rb_eval_string(ruby_string); free(ruby_string); /* FIXME: I'd like to call ruby_finalize here, but it spews weird errors: * * Error running classad plugin: wrong argument type Mutex (expected Data) */ //ruby_finalize(); fprintf(fp, "Returned result from ruby code was %s\n", (res == Qtrue) ? "true" : "false"); if (res == Qtrue) { result.SetBooleanValue(true); val = true; } do_ret: fclose(fp); return val; } /* * Struct containing the names of the functions provided here and a pointer * to the function that implements them. Third arg is an int flags that appears * to be unused. * * This is found in fnCall.h */ static ClassAdFunctionMapping classad_functions[] = { { "deltacloud_quota_check", (void *) deltacloud_quota_check, 0 }, { "", NULL, 0 } }; /* * This is the 'Init' function that is called after the library is dlopen()'d. * This just returns the struct defined above. * */ extern "C" { ClassAdFunctionMapping * Init(void) { return classad_functions; } } <commit_msg>Fix up a couple of compiler warnings in the classad parser.<commit_after>#include <ruby.h> #include <stdio.h> #include <iostream> #include <sstream> #include "classad/classad_distribution.h" #include "classad/fnCall.h" using namespace std; #ifdef WANT_CLASSAD_NAMESPACE using namespace classad; #endif void print_value(FILE *fp, Value val, const char *name) { /* AFAICT the only way to get at the string in a 'Value' object is to use * the C++ stream operator <<, so we set up a stringstream and write * stuff we want into that.. */ std::stringstream sstr; sstr << name << " is " << val; fprintf(fp, "%s\n", sstr.str().c_str()); } /* * Perform our quota check against the deltacloud aggregator database. * This function expects: * * - Instance executable name as handed to condor so that we can map to the * instance found in the database. * - The username * - The provider url so we can map back to the provider. * - The realm key so we know what realm this is in. * * ... at least for now. Need to better analyze what is required to do all * the quota matching but that's the idea. */ bool deltacloud_quota_check(const char *name, const ArgumentList &arglist, EvalState &state, Value &result) { Value instance_key; Value account_id; FILE *fp; VALUE res; bool val = false; char *ruby_string; std::stringstream method_args; int rc; result.SetBooleanValue(false); fp = fopen(LOGFILE, "a"); if (arglist.size() != 2) { result.SetErrorValue(); fprintf(fp, "Expected 2 arguments, saw %d\n", arglist.size()); goto do_ret; } if (!arglist[0]->Evaluate(state, instance_key)) { result.SetErrorValue(); fprintf(fp, "Could not evaluate argument 0 to instance key\n"); goto do_ret; } if (!arglist[1]->Evaluate(state, account_id)) { result.SetErrorValue(); fprintf(fp, "Could not evaluate argument 1 to account_id\n"); goto do_ret; } if (instance_key.GetType() != Value::STRING_VALUE) { result.SetErrorValue(); fprintf(fp, "Instance type was not a string\n"); goto do_ret; } //print_value(fp, instance_key, "instance_key"); if (account_id.GetType() != Value::STRING_VALUE) { result.SetErrorValue(); fprintf(fp, "Account ID type was not a string\n"); goto do_ret; } //print_value(fp, account_id, "account_id"); ruby_init(); ruby_init_loadpath(); method_args << "'" << DELTACLOUD_INSTALL_DIR << "/config/database.yml', '" << instance_key << "', " << account_id; rc = asprintf(&ruby_string, "$: << '%s/classad_plugin'\n" "$: << '%s/app/models'\n" "logf = File.new('%s', 'a')\n" "logf.puts \"Loading ruby support file from %s/classad_plugin\"\n" "begin\n" " require 'classad_plugin.rb'\n" " ret = classad_plugin(logf, %s)\n" "rescue Exception => ex\n" " logf.puts \"Error running classad plugin: #{ex.message}\"\n" " logf.puts ex.backtrace\n" " ret = false\n" "end\n" "logf.close\n" "ret", DELTACLOUD_INSTALL_DIR, DELTACLOUD_INSTALL_DIR, LOGFILE, DELTACLOUD_INSTALL_DIR, method_args.str().c_str()); if (rc < 0) { fprintf(fp, "Failed to allocate memory for asprintf\n"); goto do_ret; } fprintf(fp, "ruby string is %s\n", ruby_string); fflush(fp); res = rb_eval_string(ruby_string); free(ruby_string); /* FIXME: I'd like to call ruby_finalize here, but it spews weird errors: * * Error running classad plugin: wrong argument type Mutex (expected Data) */ //ruby_finalize(); fprintf(fp, "Returned result from ruby code was %s\n", (res == Qtrue) ? "true" : "false"); if (res == Qtrue) { result.SetBooleanValue(true); val = true; } do_ret: fclose(fp); return val; } /* * Struct containing the names of the functions provided here and a pointer * to the function that implements them. Third arg is an int flags that appears * to be unused. * * This is found in fnCall.h */ static ClassAdFunctionMapping classad_functions[] = { { "deltacloud_quota_check", (void *) deltacloud_quota_check, 0 }, { "", NULL, 0 } }; /* * This is the 'Init' function that is called after the library is dlopen()'d. * This just returns the struct defined above. * */ extern "C" { ClassAdFunctionMapping * Init(void) { return classad_functions; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: chrlohdl.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:37:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_PROPERTYHANDLER_CHARLOCALETYPES_HXX #include <chrlohdl.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _XMLOFF_XMLEMENT_HXX #include <xmloff/xmlelement.hxx> #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::xmloff::token; // this is a copy of defines in svx/inc/escpitem.hxx #define DFLT_ESC_PROP 58 #define DFLT_ESC_AUTO_SUPER 101 #define DFLT_ESC_AUTO_SUB -101 /////////////////////////////////////////////////////////////////////////////// // // class XMLEscapementPropHdl // XMLCharLanguageHdl::~XMLCharLanguageHdl() { // nothing to do } bool XMLCharLanguageHdl::equals( const ::com::sun::star::uno::Any& r1, const ::com::sun::star::uno::Any& r2 ) const { sal_Bool bRet = sal_False; lang::Locale aLocale1, aLocale2; if( ( r1 >>= aLocale1 ) && ( r2 >>= aLocale2 ) ) bRet = ( aLocale1.Language == aLocale2.Language ); return bRet; } sal_Bool XMLCharLanguageHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const { lang::Locale aLocale; rValue >>= aLocale; if( !IsXMLToken(rStrImpValue, XML_NONE) ) aLocale.Language = rStrImpValue; rValue <<= aLocale; return sal_True; } sal_Bool XMLCharLanguageHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const { lang::Locale aLocale; if(!(rValue >>= aLocale)) return sal_False; rStrExpValue = aLocale.Language; if( !rStrExpValue.getLength() ) rStrExpValue = GetXMLToken( XML_NONE ); return sal_True; } /////////////////////////////////////////////////////////////////////////////// // // class XMLEscapementHeightPropHdl // XMLCharCountryHdl::~XMLCharCountryHdl() { // nothing to do } bool XMLCharCountryHdl::equals( const ::com::sun::star::uno::Any& r1, const ::com::sun::star::uno::Any& r2 ) const { sal_Bool bRet = sal_False; lang::Locale aLocale1, aLocale2; if( ( r1 >>= aLocale1 ) && ( r2 >>= aLocale2 ) ) bRet = ( aLocale1.Country == aLocale2.Country ); return bRet; } sal_Bool XMLCharCountryHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const { lang::Locale aLocale; rValue >>= aLocale; if( !IsXMLToken( rStrImpValue, XML_NONE ) ) aLocale.Country = rStrImpValue; rValue <<= aLocale; return sal_True; } sal_Bool XMLCharCountryHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const { lang::Locale aLocale; if(!(rValue >>= aLocale)) return sal_False; rStrExpValue = aLocale.Country; if( !rStrExpValue.getLength() ) rStrExpValue = GetXMLToken( XML_NONE ); return sal_True; } <commit_msg>INTEGRATION: CWS impresstables2 (1.7.70); FILE MERGED 2007/08/01 14:30:32 cl 1.7.70.2: RESYNC: (1.7-1.8); FILE MERGED 2007/07/27 09:09:54 cl 1.7.70.1: fixed build issues due to pch and namespace ::rtl<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: chrlohdl.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2008-03-12 10:50:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_PROPERTYHANDLER_CHARLOCALETYPES_HXX #include <chrlohdl.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _XMLOFF_XMLEMENT_HXX #include <xmloff/xmlelement.hxx> #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star; using namespace ::xmloff::token; // this is a copy of defines in svx/inc/escpitem.hxx #define DFLT_ESC_PROP 58 #define DFLT_ESC_AUTO_SUPER 101 #define DFLT_ESC_AUTO_SUB -101 /////////////////////////////////////////////////////////////////////////////// // // class XMLEscapementPropHdl // XMLCharLanguageHdl::~XMLCharLanguageHdl() { // nothing to do } bool XMLCharLanguageHdl::equals( const ::com::sun::star::uno::Any& r1, const ::com::sun::star::uno::Any& r2 ) const { sal_Bool bRet = sal_False; lang::Locale aLocale1, aLocale2; if( ( r1 >>= aLocale1 ) && ( r2 >>= aLocale2 ) ) bRet = ( aLocale1.Language == aLocale2.Language ); return bRet; } sal_Bool XMLCharLanguageHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const { lang::Locale aLocale; rValue >>= aLocale; if( !IsXMLToken(rStrImpValue, XML_NONE) ) aLocale.Language = rStrImpValue; rValue <<= aLocale; return sal_True; } sal_Bool XMLCharLanguageHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const { lang::Locale aLocale; if(!(rValue >>= aLocale)) return sal_False; rStrExpValue = aLocale.Language; if( !rStrExpValue.getLength() ) rStrExpValue = GetXMLToken( XML_NONE ); return sal_True; } /////////////////////////////////////////////////////////////////////////////// // // class XMLEscapementHeightPropHdl // XMLCharCountryHdl::~XMLCharCountryHdl() { // nothing to do } bool XMLCharCountryHdl::equals( const ::com::sun::star::uno::Any& r1, const ::com::sun::star::uno::Any& r2 ) const { sal_Bool bRet = sal_False; lang::Locale aLocale1, aLocale2; if( ( r1 >>= aLocale1 ) && ( r2 >>= aLocale2 ) ) bRet = ( aLocale1.Country == aLocale2.Country ); return bRet; } sal_Bool XMLCharCountryHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const { lang::Locale aLocale; rValue >>= aLocale; if( !IsXMLToken( rStrImpValue, XML_NONE ) ) aLocale.Country = rStrImpValue; rValue <<= aLocale; return sal_True; } sal_Bool XMLCharCountryHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const { lang::Locale aLocale; if(!(rValue >>= aLocale)) return sal_False; rStrExpValue = aLocale.Country; if( !rStrExpValue.getLength() ) rStrExpValue = GetXMLToken( XML_NONE ); return sal_True; } <|endoftext|>
<commit_before>/* ** ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2013 Aldebaran Robotics */ #include "pysession.hpp" #include <qimessaging/session.hpp> #include <boost/python.hpp> #include <boost/python/stl_iterator.hpp> #include <qitype/dynamicobjectbuilder.hpp> #include "pyfuture.hpp" #include "gil.hpp" #include "pysignal.hpp" qiLogCategory("qi.py"); namespace qi { namespace py { qi::AnyReference triggerBouncer(qi::SignalBase *sig, const std::vector<qi::AnyReference>& args) { sig->trigger(args); return qi::AnyReference(); } class PySession { public: PySession() : _ses(new qi::Session) , nSigConnected(0) , nSigDisconnected(0) , connected(makePySignal()) , disconnected(makePySignal()) { // Get SignalBase from our PySignals qi::SignalBase *conn = getSignal(connected); qi::SignalBase *disconn = getSignal(disconnected); // Connect our PySignals with qi::Session signals, have to use a dynamic generic function to trigger nSigConnected = _ses->connected.connect(qi::AnyFunction::fromDynamicFunction(boost::bind(&triggerBouncer, conn, _1))); nSigDisconnected = _ses->disconnected.connect(qi::AnyFunction::fromDynamicFunction(boost::bind(&triggerBouncer, disconn, _1))); } ~PySession() { _ses->connected.disconnect(nSigConnected); _ses->disconnected.disconnect(nSigDisconnected); } //return a future, or None (and throw in case of error) boost::python::object connect(const std::string &url, bool _async=false) { GILScopedUnlock _unlock; return toPyFutureAsync(_ses->connect(url), _async); } //return a future, or None (and throw in case of error) boost::python::object close(bool _async=false) { GILScopedUnlock _unlock; return toPyFutureAsync(_ses->close(), _async); } boost::python::object service(const std::string &name, bool _async=false) { GILScopedUnlock _unlock; return toPyFutureAsync(_ses->service(name), _async); } boost::python::object services(bool _async=false) { GILScopedUnlock _unlock; return toPyFutureAsync(_ses->services(), _async); } boost::python::object registerService(const std::string &name, boost::python::object obj, bool _async=false) { GILScopedUnlock _unlock; return toPyFutureAsync(_ses->registerService(name, qi::AnyReference(obj).toObject()), _async); } boost::python::object unregisterService(const unsigned int &id, bool _async=false) { GILScopedUnlock _unlock; return toPyFutureAsync(_ses->unregisterService(id), _async); } private: boost::shared_ptr<qi::Session> _ses; int nSigConnected; int nSigDisconnected; public: boost::python::object connected; boost::python::object disconnected; }; void export_pysession() { boost::python::class_<PySession>("Session") .def("connect", &PySession::connect, (boost::python::arg("url"), boost::python::arg("_async") = false)) .def("close", &PySession::close, (boost::python::arg("_async") = false)) .def("service", &PySession::service, (boost::python::arg("service"), boost::python::arg("_async") = false)) .def("services", &PySession::services, (boost::python::arg("_async") = false)) .def("registerService", &PySession::registerService, (boost::python::arg("name"), boost::python::arg("object"), boost::python::arg("_async") = false)) .def("unregisterService", &PySession::unregisterService, (boost::python::arg("id"), boost::python::arg("_async") = false)) .def_readonly("connected", &PySession::connected) .def_readonly("disconnected", &PySession::disconnected) ; } } } <commit_msg>python: session: unlock only the needed part<commit_after>/* ** ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2013 Aldebaran Robotics */ #include "pysession.hpp" #include <qimessaging/session.hpp> #include <boost/python.hpp> #include <boost/python/stl_iterator.hpp> #include <qitype/dynamicobjectbuilder.hpp> #include "pyfuture.hpp" #include "gil.hpp" #include "pysignal.hpp" qiLogCategory("qi.py"); namespace qi { namespace py { qi::AnyReference triggerBouncer(qi::SignalBase *sig, const std::vector<qi::AnyReference>& args) { sig->trigger(args); return qi::AnyReference(); } class PySession { public: PySession() : _ses(new qi::Session) , nSigConnected(0) , nSigDisconnected(0) , connected(makePySignal()) , disconnected(makePySignal()) { // Get SignalBase from our PySignals qi::SignalBase *conn = getSignal(connected); qi::SignalBase *disconn = getSignal(disconnected); // Connect our PySignals with qi::Session signals, have to use a dynamic generic function to trigger nSigConnected = _ses->connected.connect(qi::AnyFunction::fromDynamicFunction(boost::bind(&triggerBouncer, conn, _1))); nSigDisconnected = _ses->disconnected.connect(qi::AnyFunction::fromDynamicFunction(boost::bind(&triggerBouncer, disconn, _1))); } ~PySession() { _ses->connected.disconnect(nSigConnected); _ses->disconnected.disconnect(nSigDisconnected); } //return a future, or None (and throw in case of error) boost::python::object connect(const std::string &url, bool _async=false) { qi::Future<void> fut; { GILScopedUnlock _unlock; fut = _ses->connect(url); } return toPyFutureAsync(fut, _async); } //return a future, or None (and throw in case of error) boost::python::object close(bool _async=false) { qi::Future<void> fut; { GILScopedUnlock _unlock; fut = _ses->close(); } return toPyFutureAsync(fut, _async); } boost::python::object service(const std::string &name, bool _async=false) { qi::Future<qi::AnyObject> fut; { GILScopedUnlock _unlock; fut = _ses->service(name); } return toPyFutureAsync(fut, _async); } boost::python::object services(bool _async=false) { qi::Future< std::vector<ServiceInfo> > fut; { GILScopedUnlock _unlock; fut = _ses->services(); } return toPyFutureAsync(fut, _async); } boost::python::object registerService(const std::string &name, boost::python::object obj, bool _async=false) { qi::AnyObject anyobj = qi::AnyReference(obj).toObject(); qi::Future<unsigned int> fut; { GILScopedUnlock _unlock; fut = _ses->registerService(name, anyobj); } return toPyFutureAsync(fut, _async); } boost::python::object unregisterService(const unsigned int &id, bool _async=false) { qi::Future<void> fut; { GILScopedUnlock _unlock; fut = _ses->unregisterService(id); } return toPyFutureAsync(fut, _async); } private: boost::shared_ptr<qi::Session> _ses; int nSigConnected; int nSigDisconnected; public: boost::python::object connected; boost::python::object disconnected; }; void export_pysession() { boost::python::class_<PySession>("Session") .def("connect", &PySession::connect, (boost::python::arg("url"), boost::python::arg("_async") = false)) .def("close", &PySession::close, (boost::python::arg("_async") = false)) .def("service", &PySession::service, (boost::python::arg("service"), boost::python::arg("_async") = false)) .def("services", &PySession::services, (boost::python::arg("_async") = false)) .def("registerService", &PySession::registerService, (boost::python::arg("name"), boost::python::arg("object"), boost::python::arg("_async") = false)) .def("unregisterService", &PySession::unregisterService, (boost::python::arg("id"), boost::python::arg("_async") = false)) .def_readonly("connected", &PySession::connected) .def_readonly("disconnected", &PySession::disconnected) ; } } } <|endoftext|>
<commit_before>#include <gmock/gmock.h> #include <gtest/gtest.h> #include <sauce/sauce.h> #include "allocate_with.h" using ::testing::Sequence; using ::testing::Return; namespace sauce { namespace test { class Chasis { public: Chasis() {} virtual ~Chasis() {} }; class CoupChasis: public Chasis { public: static int constructed; static int destroyed; CoupChasis() { constructed += 1; } ~CoupChasis() { destroyed += 1; } }; int CoupChasis::constructed = 0; int CoupChasis::destroyed = 0; class Engine { public: Engine() {} virtual ~Engine() {} }; class HybridEngine: public Engine { public: static int constructed; static int destroyed; HybridEngine() { constructed += 1; } ~HybridEngine() { destroyed += 1; } }; int HybridEngine::constructed = 0; int HybridEngine::destroyed = 0; class Vehicle { public: Vehicle() {} virtual ~Vehicle() {} virtual SAUCE_SHARED_PTR<Chasis> getChasis() const = 0; virtual SAUCE_SHARED_PTR<Engine> getEngine() const = 0; }; class Herbie: public Vehicle { public: static int constructed; static int destroyed; SAUCE_SHARED_PTR<Chasis> chasis; SAUCE_SHARED_PTR<Engine> engine; Herbie(SAUCE_SHARED_PTR<Chasis> chasis, SAUCE_SHARED_PTR<Engine> engine): chasis(chasis), engine(engine) { constructed += 1; } ~Herbie() { destroyed += 1; } SAUCE_SHARED_PTR<Chasis> getChasis() const { return chasis; } SAUCE_SHARED_PTR<Engine> getEngine() const { return engine; } }; int Herbie::constructed = 0; int Herbie::destroyed = 0; /** * Our mock for the new and delete operations, for use with AllocateWith. * * The AllocateWith contract assumes allocate will be disambiguated with a * leading tag parameter. So, be sure to accept such parameters. */ class MockAllocation { public: MOCK_METHOD2(allocate, CoupChasis * (A<CoupChasis>, size_t)); MOCK_METHOD2(allocate, HybridEngine * (A<HybridEngine>, size_t)); MOCK_METHOD2(allocate, Herbie * (A<Herbie>, size_t)); MOCK_METHOD2(deallocate, void(CoupChasis *, size_t)); MOCK_METHOD2(deallocate, void(HybridEngine *, size_t)); MOCK_METHOD2(deallocate, void(Herbie *, size_t)); }; using ::sauce::Bind; class HerbieModule: public Bind<Chasis, CoupChasis(), AllocateWith<MockAllocation>::Allocator<CoupChasis> >, public Bind<Engine, HybridEngine(), AllocateWith<MockAllocation>::Allocator<HybridEngine> >, public Bind<Vehicle, Herbie(Chasis, Engine), AllocateWith<MockAllocation>::Allocator<Herbie> > { public: using Bind<Chasis, CoupChasis(), AllocateWith<MockAllocation>::Allocator<CoupChasis> >::bindings; using Bind<Engine, HybridEngine(), AllocateWith<MockAllocation>::Allocator<HybridEngine> >::bindings; using Bind<Vehicle, Herbie(Chasis, Engine), AllocateWith<MockAllocation>::Allocator<Herbie> >::bindings; }; template<> MockAllocation * AllocateWith<MockAllocation>::Base::backing = NULL; class AllocationTest: public ::testing::Test { public: ::sauce::Injector<HerbieModule> injector; MockAllocation allocator; // These point to ALLOCATED but UNINITIALIZED memory CoupChasis * chasis; HybridEngine * engine; Herbie * vehicle; AllocationTest(): injector(), allocator(), chasis(NULL), engine(NULL), vehicle(NULL) { } virtual void SetUp() { // Clear the static counters CoupChasis::constructed = 0; CoupChasis::destroyed = 0; HybridEngine::constructed = 0; HybridEngine::destroyed = 0; Herbie::constructed = 0; Herbie::destroyed = 0; // Point our configured allocator at the mock AllocateWith<MockAllocation>::Base::setBacking(allocator); // And now use a real one to get some raw memory chasis = std::allocator<CoupChasis>().allocate(1); engine = std::allocator<HybridEngine>().allocate(1); vehicle = std::allocator<Herbie>().allocate(1); } virtual void TearDown() { std::allocator<CoupChasis>().deallocate(chasis, 1); std::allocator<HybridEngine>().deallocate(engine, 1); std::allocator<Herbie>().deallocate(vehicle, 1); } }; TEST_F(AllocationTest, shouldProvideAndDisposeADependency) { EXPECT_CALL(allocator, allocate(A<CoupChasis>(), 1)).WillOnce(Return(chasis)); EXPECT_CALL(allocator, deallocate(chasis, 1)); { SAUCE_SHARED_PTR<Chasis> actual = injector.get<Chasis>(); ASSERT_EQ(1, CoupChasis::constructed); ASSERT_EQ(chasis, actual.get()); } ASSERT_EQ(1, CoupChasis::destroyed); } TEST_F(AllocationTest, shouldProvideAndDisposeOfDependenciesTransitively) { // We don't care about the relative ordering between chasis and engine: // only about how they stand relative to the vehicle. Sequence chasisSeq, engineSeq; // Allocate the chasis and engine before the vehicle EXPECT_CALL(allocator, allocate(A<CoupChasis>(), 1)). InSequence(chasisSeq).WillOnce(Return(chasis)); EXPECT_CALL(allocator, allocate(A<HybridEngine>(), 1)). InSequence(engineSeq).WillOnce(Return(engine)); EXPECT_CALL(allocator, allocate(A<Herbie>(), 1)). InSequence(chasisSeq, engineSeq).WillOnce(Return(vehicle)); // Deallocate the chasis and engine *before* the vehicle // Should destroying the vehicle after its dependencies be an issue? This // is simply the order that falls out of smart pointer deletion.. EXPECT_CALL(allocator, deallocate(engine, 1)).InSequence(engineSeq); EXPECT_CALL(allocator, deallocate(chasis, 1)).InSequence(chasisSeq); EXPECT_CALL(allocator, deallocate(vehicle, 1)).InSequence(chasisSeq, engineSeq); { SAUCE_SHARED_PTR<Vehicle> actual = injector.get<Vehicle>(); ASSERT_EQ(1, CoupChasis::constructed); ASSERT_EQ(1, HybridEngine::constructed); ASSERT_EQ(1, Herbie::constructed); ASSERT_EQ(chasis, actual->getChasis().get()); ASSERT_EQ(engine, actual->getEngine().get()); ASSERT_EQ(vehicle, actual.get()); } ASSERT_EQ(1, CoupChasis::destroyed); ASSERT_EQ(1, HybridEngine::destroyed); ASSERT_EQ(1, Herbie::destroyed); } } }<commit_msg>tweak<commit_after>#include <gmock/gmock.h> #include <gtest/gtest.h> #include <sauce/sauce.h> #include "allocate_with.h" using ::testing::Sequence; using ::testing::Return; namespace sauce { namespace test { class Chasis { public: Chasis() {} virtual ~Chasis() {} }; class CoupChasis: public Chasis { public: static int constructed; static int destroyed; CoupChasis() { constructed += 1; } ~CoupChasis() { destroyed += 1; } }; int CoupChasis::constructed = 0; int CoupChasis::destroyed = 0; class Engine { public: Engine() {} virtual ~Engine() {} }; class HybridEngine: public Engine { public: static int constructed; static int destroyed; HybridEngine() { constructed += 1; } ~HybridEngine() { destroyed += 1; } }; int HybridEngine::constructed = 0; int HybridEngine::destroyed = 0; class Vehicle { public: Vehicle() {} virtual ~Vehicle() {} virtual SAUCE_SHARED_PTR<Chasis> getChasis() const = 0; virtual SAUCE_SHARED_PTR<Engine> getEngine() const = 0; }; class Herbie: public Vehicle { public: static int constructed; static int destroyed; SAUCE_SHARED_PTR<Chasis> chasis; SAUCE_SHARED_PTR<Engine> engine; Herbie(SAUCE_SHARED_PTR<Chasis> chasis, SAUCE_SHARED_PTR<Engine> engine): chasis(chasis), engine(engine) { constructed += 1; } ~Herbie() { destroyed += 1; } SAUCE_SHARED_PTR<Chasis> getChasis() const { return chasis; } SAUCE_SHARED_PTR<Engine> getEngine() const { return engine; } }; int Herbie::constructed = 0; int Herbie::destroyed = 0; /** * Our mock for the new and delete operations, for use with AllocateWith. * * The AllocateWith contract assumes allocate will be disambiguated with a * leading tag parameter. So, be sure to accept such parameters. */ class MockAllocation { public: MOCK_METHOD2(allocate, CoupChasis * (A<CoupChasis>, size_t)); MOCK_METHOD2(allocate, HybridEngine * (A<HybridEngine>, size_t)); MOCK_METHOD2(allocate, Herbie * (A<Herbie>, size_t)); MOCK_METHOD2(deallocate, void(CoupChasis *, size_t)); MOCK_METHOD2(deallocate, void(HybridEngine *, size_t)); MOCK_METHOD2(deallocate, void(Herbie *, size_t)); }; using ::sauce::Bind; class HerbieModule: public Bind<Chasis, CoupChasis(), AllocateWith<MockAllocation>::Allocator<CoupChasis> >, public Bind<Engine, HybridEngine(), AllocateWith<MockAllocation>::Allocator<HybridEngine> >, public Bind<Vehicle, Herbie(Chasis, Engine), AllocateWith<MockAllocation>::Allocator<Herbie> > { public: using Bind<Chasis, CoupChasis(), AllocateWith<MockAllocation>::Allocator<CoupChasis> >::bindings; using Bind<Engine, HybridEngine(), AllocateWith<MockAllocation>::Allocator<HybridEngine> >::bindings; using Bind<Vehicle, Herbie(Chasis, Engine), AllocateWith<MockAllocation>::Allocator<Herbie> >::bindings; }; template<> MockAllocation * AllocateWith<MockAllocation>::Base::backing = NULL; class AllocationTest: public ::testing::Test { public: ::sauce::Injector<HerbieModule> injector; MockAllocation allocator; // These point to ALLOCATED but UNINITIALIZED memory CoupChasis * chasis; HybridEngine * engine; Herbie * vehicle; AllocationTest(): injector(), allocator(), chasis(NULL), engine(NULL), vehicle(NULL) {} virtual void SetUp() { // Clear the static counters CoupChasis::constructed = 0; CoupChasis::destroyed = 0; HybridEngine::constructed = 0; HybridEngine::destroyed = 0; Herbie::constructed = 0; Herbie::destroyed = 0; // Point our configured allocator at the mock AllocateWith<MockAllocation>::Base::setBacking(allocator); // And now use a real one to get some raw memory chasis = std::allocator<CoupChasis>().allocate(1); engine = std::allocator<HybridEngine>().allocate(1); vehicle = std::allocator<Herbie>().allocate(1); } virtual void TearDown() { std::allocator<CoupChasis>().deallocate(chasis, 1); std::allocator<HybridEngine>().deallocate(engine, 1); std::allocator<Herbie>().deallocate(vehicle, 1); } }; TEST_F(AllocationTest, shouldProvideAndDisposeADependency) { EXPECT_CALL(allocator, allocate(A<CoupChasis>(), 1)).WillOnce(Return(chasis)); EXPECT_CALL(allocator, deallocate(chasis, 1)); { SAUCE_SHARED_PTR<Chasis> actual = injector.get<Chasis>(); ASSERT_EQ(1, CoupChasis::constructed); ASSERT_EQ(chasis, actual.get()); } ASSERT_EQ(1, CoupChasis::destroyed); } TEST_F(AllocationTest, shouldProvideAndDisposeOfDependenciesTransitively) { // We don't care about the relative ordering between chasis and engine: // only about how they stand relative to the vehicle. Sequence chasisSeq, engineSeq; // Allocate the chasis and engine before the vehicle EXPECT_CALL(allocator, allocate(A<CoupChasis>(), 1)). InSequence(chasisSeq).WillOnce(Return(chasis)); EXPECT_CALL(allocator, allocate(A<HybridEngine>(), 1)). InSequence(engineSeq).WillOnce(Return(engine)); EXPECT_CALL(allocator, allocate(A<Herbie>(), 1)). InSequence(chasisSeq, engineSeq).WillOnce(Return(vehicle)); // Deallocate the chasis and engine *before* the vehicle // Should destroying the vehicle after its dependencies be an issue? This // is simply the order that falls out of smart pointer deletion.. EXPECT_CALL(allocator, deallocate(engine, 1)).InSequence(engineSeq); EXPECT_CALL(allocator, deallocate(chasis, 1)).InSequence(chasisSeq); EXPECT_CALL(allocator, deallocate(vehicle, 1)).InSequence(chasisSeq, engineSeq); { SAUCE_SHARED_PTR<Vehicle> actual = injector.get<Vehicle>(); ASSERT_EQ(1, CoupChasis::constructed); ASSERT_EQ(1, HybridEngine::constructed); ASSERT_EQ(1, Herbie::constructed); ASSERT_EQ(chasis, actual->getChasis().get()); ASSERT_EQ(engine, actual->getEngine().get()); ASSERT_EQ(vehicle, actual.get()); } ASSERT_EQ(1, CoupChasis::destroyed); ASSERT_EQ(1, HybridEngine::destroyed); ASSERT_EQ(1, Herbie::destroyed); } } }<|endoftext|>
<commit_before>#include <cybozu/test.hpp> #include <cybozu/zlib.hpp> #include <cybozu/file.hpp> #include <cybozu/stream.hpp> #include <cybozu/serializer.hpp> #include <sstream> #include <fstream> #include <string> #include <vector> #include <map> CYBOZU_TEST_AUTO(test1_deflate) { typedef cybozu::ZlibCompressorT<std::stringstream> Compressor; typedef cybozu::ZlibDecompressorT<std::stringstream> Decompressor; const std::string in = "this is a pen"; std::stringstream os; { Compressor comp(os); comp.write(in.c_str(), in.size()); comp.flush(); } const std::string enc = os.str(); const char encTbl[] = "\x78\x9c\x2b\xc9\xc8\x2c\x56\x00\xa2\x44\x85\x82\xd4\x3c\x00\x21\x0c\x04\x99"; const std::string encOk(encTbl, encTbl + sizeof(encTbl) - 1); CYBOZU_TEST_EQUAL(enc, encOk); std::stringstream is; is << encOk; { Decompressor dec(is); char buf[2048]; std::string out; for (;;) { size_t size = dec.readSome(buf, sizeof(buf)); if (size == 0) break; out.append(buf, buf + size); } CYBOZU_TEST_EQUAL(in, out); } } CYBOZU_TEST_AUTO(test2_deflate) { typedef cybozu::ZlibCompressorT<std::stringstream, 1> Compressor; typedef cybozu::ZlibDecompressorT<std::stringstream, 1> Decompressor; const std::string in = "this is a pen"; std::stringstream os; { Compressor comp(os); for (size_t i = 0; i < in.size(); i++) { comp.write(&in[i], 1); } comp.flush(); } const std::string enc = os.str(); const char encTbl[] = "\x78\x9c\x2b\xc9\xc8\x2c\x56\x00\xa2\x44\x85\x82\xd4\x3c\x00\x21\x0c\x04\x99"; const std::string encOk(encTbl, encTbl + sizeof(encTbl) - 1); CYBOZU_TEST_EQUAL(enc, encOk); std::stringstream is; is << encOk; { Decompressor dec(is); char buf[2048]; std::string out; for (;;) { size_t size = dec.readSome(buf, sizeof(buf)); if (size == 0) break; out.append(buf, buf + size); } CYBOZU_TEST_EQUAL(in, out); } } CYBOZU_TEST_AUTO(enc_and_dec) { std::string body = "From: cybozu\r\n" "To: cybozu\r\n" "\r\n" "hello with zlib compressed\r\n" ".\r\n"; std::stringstream ss; cybozu::ZlibCompressorT<std::stringstream> comp(ss); comp.write(&body[0], body.size()); comp.flush(); std::string enc = ss.str(); cybozu::StringInputStream ims(enc); cybozu::ZlibDecompressorT<cybozu::StringInputStream> dec(ims); char buf[4096]; size_t size = dec.readSome(buf, sizeof(buf)); std::string decStr(buf, buf + size); CYBOZU_TEST_EQUAL(body, decStr); } CYBOZU_TEST_AUTO(output_gzip1) { std::string str = "Only a test, test, test, test, test, test, test, test!\n"; std::stringstream ss; cybozu::ZlibCompressorT<std::stringstream> comp(ss, true); comp.write(&str[0], str.size()); comp.flush(); std::string enc = ss.str(); { cybozu::ZlibDecompressorT<std::stringstream> dec(ss, true); char buf[4096]; size_t size = dec.readSome(buf, sizeof(buf)); std::string decStr(buf, buf + size); CYBOZU_TEST_EQUAL(decStr, str); } { cybozu::StringInputStream is(enc); cybozu::ZlibDecompressorT<cybozu::StringInputStream> dec(is, true); char buf[4096]; size_t size = dec.readSome(buf, sizeof(buf)); std::string decStr(buf, buf + size); CYBOZU_TEST_EQUAL(decStr, str); } } #ifdef _MSC_VER #pragma warning(disable : 4309) #endif CYBOZU_TEST_AUTO(output_gzip2) { const uint8_t textBufTbl[] = { 0x23, 0x69, 0x6E, 0x63, 0x6C, 0x75, 0x64, 0x65, 0x20, 0x3C, 0x73, 0x74, 0x64, 0x69, 0x6F, 0x2E, 0x68, 0x3E, 0x0A, 0x0A, 0x69, 0x6E, 0x74, 0x20, 0x6D, 0x61, 0x69, 0x6E, 0x28, 0x29, 0x0A, 0x7B, 0x0A, 0x09, 0x70, 0x75, 0x74, 0x73, 0x28, 0x22, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x22, 0x29, 0x3B, 0x0A, 0x09, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x20, 0x30, 0x3B, 0x0A, 0x7D, 0x0A, 0x0A, }; const uint8_t encBufTbl[] = { 0x1F, 0x8B, 0x08, 0x08, 0xA4, 0x7E, 0x20, 0x4B, 0x00, 0x03, 0x74, 0x2E, 0x63, 0x70, 0x70, 0x00, 0x53, 0xCE, 0xCC, 0x4B, 0xCE, 0x29, 0x4D, 0x49, 0x55, 0xB0, 0x29, 0x2E, 0x49, 0xC9, 0xCC, 0xD7, 0xCB, 0xB0, 0xE3, 0xE2, 0xCA, 0xCC, 0x2B, 0x51, 0xC8, 0x4D, 0xCC, 0xCC, 0xD3, 0xD0, 0xE4, 0xAA, 0xE6, 0xE2, 0x2C, 0x28, 0x2D, 0x29, 0xD6, 0x50, 0xCA, 0x48, 0xCD, 0xC9, 0xC9, 0x57, 0xD2, 0xB4, 0xE6, 0xE2, 0x2C, 0x4A, 0x2D, 0x29, 0x2D, 0xCA, 0x53, 0x30, 0xB0, 0xE6, 0xAA, 0xE5, 0xE2, 0x02, 0x00, 0x48, 0xAB, 0x48, 0x61, 0x3F, 0x00, 0x00, 0x00, }; const char *const textBuf = cybozu::cast<const char*>(textBufTbl); const char *const encBuf = cybozu::cast<const char*>(encBufTbl); const std::string text(textBuf, textBuf + sizeof(textBufTbl)); { std::stringstream ss; ss.write(encBuf, sizeof(encBufTbl)); cybozu::ZlibDecompressorT<std::stringstream> dec(ss, true); char buf[4096]; size_t size = dec.readSome(buf, sizeof(buf)); std::string decStr(buf, buf + size); CYBOZU_TEST_EQUAL(decStr, text); } } CYBOZU_TEST_AUTO(serializer) { typedef std::map<int, double> Map; Map m, mm; for (int i = 0; i < 100; i++) { m[i * i] = (i + i * i) / 3.42; } std::stringstream ss; { cybozu::ZlibCompressorT<std::stringstream> enc(ss); cybozu::save(enc, m); } { cybozu::ZlibDecompressorT<std::stringstream> dec(ss); cybozu::load(mm, dec); } CYBOZU_TEST_EQUAL(m.size(), mm.size()); for (Map::const_iterator i = m.begin(), ie = m.end(), j = mm.begin(); i != ie; ++i, ++j) { CYBOZU_TEST_EQUAL(i->first, j->first); CYBOZU_TEST_EQUAL(i->second, j->second); } } <commit_msg>add test serializer with zlib<commit_after>#include <cybozu/test.hpp> #include <cybozu/zlib.hpp> #include <cybozu/file.hpp> #include <cybozu/stream.hpp> #include <cybozu/serializer.hpp> #include <cybozu/nlp/sparse.hpp> #include <sstream> #include <fstream> #include <string> #include <vector> #include <map> const char *g_testFile = "zlib_test.log"; CYBOZU_TEST_AUTO(test1_deflate) { typedef cybozu::ZlibCompressorT<std::stringstream> Compressor; typedef cybozu::ZlibDecompressorT<std::stringstream> Decompressor; const std::string in = "this is a pen"; std::stringstream os; { Compressor comp(os); comp.write(in.c_str(), in.size()); comp.flush(); } const std::string enc = os.str(); const char encTbl[] = "\x78\x9c\x2b\xc9\xc8\x2c\x56\x00\xa2\x44\x85\x82\xd4\x3c\x00\x21\x0c\x04\x99"; const std::string encOk(encTbl, encTbl + sizeof(encTbl) - 1); CYBOZU_TEST_EQUAL(enc, encOk); std::stringstream is; is << encOk; { Decompressor dec(is); char buf[2048]; std::string out; for (;;) { size_t size = dec.readSome(buf, sizeof(buf)); if (size == 0) break; out.append(buf, buf + size); } CYBOZU_TEST_EQUAL(in, out); } } CYBOZU_TEST_AUTO(test2_deflate) { typedef cybozu::ZlibCompressorT<std::stringstream, 1> Compressor; typedef cybozu::ZlibDecompressorT<std::stringstream, 1> Decompressor; const std::string in = "this is a pen"; std::stringstream os; { Compressor comp(os); for (size_t i = 0; i < in.size(); i++) { comp.write(&in[i], 1); } comp.flush(); } const std::string enc = os.str(); const char encTbl[] = "\x78\x9c\x2b\xc9\xc8\x2c\x56\x00\xa2\x44\x85\x82\xd4\x3c\x00\x21\x0c\x04\x99"; const std::string encOk(encTbl, encTbl + sizeof(encTbl) - 1); CYBOZU_TEST_EQUAL(enc, encOk); std::stringstream is; is << encOk; { Decompressor dec(is); char buf[2048]; std::string out; for (;;) { size_t size = dec.readSome(buf, sizeof(buf)); if (size == 0) break; out.append(buf, buf + size); } CYBOZU_TEST_EQUAL(in, out); } } CYBOZU_TEST_AUTO(enc_and_dec) { std::string body = "From: cybozu\r\n" "To: cybozu\r\n" "\r\n" "hello with zlib compressed\r\n" ".\r\n"; std::stringstream ss; cybozu::ZlibCompressorT<std::stringstream> comp(ss); comp.write(&body[0], body.size()); comp.flush(); std::string enc = ss.str(); cybozu::StringInputStream ims(enc); cybozu::ZlibDecompressorT<cybozu::StringInputStream> dec(ims); char buf[4096]; size_t size = dec.readSome(buf, sizeof(buf)); std::string decStr(buf, buf + size); CYBOZU_TEST_EQUAL(body, decStr); } CYBOZU_TEST_AUTO(output_gzip1) { std::string str = "Only a test, test, test, test, test, test, test, test!\n"; std::stringstream ss; cybozu::ZlibCompressorT<std::stringstream> comp(ss, true); comp.write(&str[0], str.size()); comp.flush(); std::string enc = ss.str(); { cybozu::ZlibDecompressorT<std::stringstream> dec(ss, true); char buf[4096]; size_t size = dec.readSome(buf, sizeof(buf)); std::string decStr(buf, buf + size); CYBOZU_TEST_EQUAL(decStr, str); } { cybozu::StringInputStream is(enc); cybozu::ZlibDecompressorT<cybozu::StringInputStream> dec(is, true); char buf[4096]; size_t size = dec.readSome(buf, sizeof(buf)); std::string decStr(buf, buf + size); CYBOZU_TEST_EQUAL(decStr, str); } } #ifdef _MSC_VER #pragma warning(disable : 4309) #endif CYBOZU_TEST_AUTO(output_gzip2) { const uint8_t textBufTbl[] = { 0x23, 0x69, 0x6E, 0x63, 0x6C, 0x75, 0x64, 0x65, 0x20, 0x3C, 0x73, 0x74, 0x64, 0x69, 0x6F, 0x2E, 0x68, 0x3E, 0x0A, 0x0A, 0x69, 0x6E, 0x74, 0x20, 0x6D, 0x61, 0x69, 0x6E, 0x28, 0x29, 0x0A, 0x7B, 0x0A, 0x09, 0x70, 0x75, 0x74, 0x73, 0x28, 0x22, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x22, 0x29, 0x3B, 0x0A, 0x09, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x20, 0x30, 0x3B, 0x0A, 0x7D, 0x0A, 0x0A, }; const uint8_t encBufTbl[] = { 0x1F, 0x8B, 0x08, 0x08, 0xA4, 0x7E, 0x20, 0x4B, 0x00, 0x03, 0x74, 0x2E, 0x63, 0x70, 0x70, 0x00, 0x53, 0xCE, 0xCC, 0x4B, 0xCE, 0x29, 0x4D, 0x49, 0x55, 0xB0, 0x29, 0x2E, 0x49, 0xC9, 0xCC, 0xD7, 0xCB, 0xB0, 0xE3, 0xE2, 0xCA, 0xCC, 0x2B, 0x51, 0xC8, 0x4D, 0xCC, 0xCC, 0xD3, 0xD0, 0xE4, 0xAA, 0xE6, 0xE2, 0x2C, 0x28, 0x2D, 0x29, 0xD6, 0x50, 0xCA, 0x48, 0xCD, 0xC9, 0xC9, 0x57, 0xD2, 0xB4, 0xE6, 0xE2, 0x2C, 0x4A, 0x2D, 0x29, 0x2D, 0xCA, 0x53, 0x30, 0xB0, 0xE6, 0xAA, 0xE5, 0xE2, 0x02, 0x00, 0x48, 0xAB, 0x48, 0x61, 0x3F, 0x00, 0x00, 0x00, }; const char *const textBuf = cybozu::cast<const char*>(textBufTbl); const char *const encBuf = cybozu::cast<const char*>(encBufTbl); const std::string text(textBuf, textBuf + sizeof(textBufTbl)); { std::stringstream ss; ss.write(encBuf, sizeof(encBufTbl)); cybozu::ZlibDecompressorT<std::stringstream> dec(ss, true); char buf[4096]; size_t size = dec.readSome(buf, sizeof(buf)); std::string decStr(buf, buf + size); CYBOZU_TEST_EQUAL(decStr, text); } } template<class InputStream, class OutputStream> void testSerializer(InputStream& is, OutputStream& os) { { cybozu::ZlibCompressorT<OutputStream> enc(os); cybozu::save(enc, m); } { cybozu::ZlibDecompressorT<InputStream> dec(is); cybozu::load(mm, dec); } } template<class Map> void compareMap(const Map& x, const Map& y) { CYBOZU_TEST_EQUAL(x.size(), y.size()); for (Map::const_iterator i = x.begin(), ie = x.end(), j = y.begin(); i != ie; ++i, ++j) { CYBOZU_TEST_EQUAL(i->first, j->first); CYBOZU_TEST_EQUAL(i->second, j->second); } } CYBOZU_TEST_AUTO(serializer_with_zlib) { typedef std::map<int, double> Map; Map src; for (int i = 0; i < 100; i++) { src[i * i] = (i + i * i) / 3.42; } std::stringstream ss; { cybozu::ZlibCompressorT<std::stringstream> enc(ss); cybozu::save(enc, src); } { cybozu::ZlibDecompressorT<std::stringstream> dec(ss); Map dst; cybozu::load(dst, dec); compareMap(src, dst); } { std::ofstream ofs(g_testFile, std::ios::binary); cybozu::ZlibCompressorT<std::ofstream> enc(ofs); cybozu::save(enc, src); } { std::ifstream ifs(g_testFile, std::ios::binary); cybozu::ZlibDecompressorT<std::ifstream> dec(ifs); Map dst; cybozu::load(dst, dec); compareMap(src, dst); } } #if 0 CYBOZU_TEST_AUTO(sparse_with_zlib) { typedef cybozu::nlp::SparseVector<double> Vec; Vec x; const struct { int pos; double val; } tbl[] = { { 3, 1.2 }, { 5, 9.4 }, { 8, 123.4 }, { 999, -324.0 }, }; for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) { x.push_back(tbl[i].pos, tbl[i].val); } { std::ofstream ofs(g_testFile, std::ios::binary); cybozu::ZlibCompressorT<std::ofstream> enc(ofs); cybozu::save(enc, x); } { Vec y; std::ifstream ifs(g_testFile, std::ios::binary); cybozu::ZlibCompressorT<std::ifstream> dec(ifs); // cybozu::load(y, ifs); // CYBOZU_TEST_EQUAL(x, y); } } #endif <|endoftext|>
<commit_before>// // broadcast_test.cpp // orwell // // Created by Massimo Gengarelli on 15/02/14. // // #include "RawMessage.hpp" #include <zmq.hpp> #include "controller.pb.h" #include "server-game.pb.h" #include "Sender.hpp" #include "Receiver.hpp" #include "Server.hpp" #include "Common.hpp" #include <log4cxx/logger.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/ndc.h> #include <string> #include <cstring> #include <netinet/udp.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <iostream> #include <sstream> using namespace log4cxx; using namespace orwell::com; using namespace orwell::messages; using namespace std; struct IP4 { uint8_t b1, b2, b3, b4 = 0; operator std::string() const { char buffer[32]; sprintf(&buffer[0], "%u.%u.%u.%u", b1, b2, b3, b4); return std::string(buffer); }; operator bool() const { return (not (b1 == 0 and b2 == 0 and b3 == 0 and b4 == 0)); }; friend std::ostream & operator<<(std::ostream & _stream, IP4 const & ip4) { _stream << (std::string) ip4; return _stream; }; }; bool get_ip4(IP4 & oIp4) { char szBuffer[1024]; if(gethostname(szBuffer, sizeof(szBuffer)) == -1) { return false; } struct hostent *host = gethostbyname(szBuffer); if(host == NULL) { return false; } //Obtain the computer's IP oIp4.b1 = (uint8_t) host->h_addr_list[0][0]; oIp4.b2 = (uint8_t) host->h_addr_list[0][1]; oIp4.b3 = (uint8_t) host->h_addr_list[0][2]; oIp4.b4 = (uint8_t) host->h_addr_list[0][3]; return true; } uint32_t simulateClient(log4cxx::LoggerPtr iLogger) { int aSocket; ssize_t aMessageLength; struct sockaddr_in aDestination; unsigned int aDestinationLength; char aReply[256]; char *aMessageToSend = (char*) "1AFTW"; aMessageLength = strlen(aMessageToSend); int broadcast = 1; // Build the socket if ( (aSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) ) < 0) { perror("socket()"); return 255; } IP4 address; if (not get_ip4(address)) { LOG4CXX_ERROR(iLogger, "Couldn't retrieve local address"); return 255; } address.b4 = 255; if (address) { LOG4CXX_INFO(iLogger, "IP: " << address); } // Build the destination object memset(&aDestination, 0, sizeof(aDestination)); aDestination.sin_family = AF_INET; aDestination.sin_addr.s_addr = inet_addr( ((std::string) address).c_str()); aDestination.sin_port = htons(9080); // Set the destination to the socket setsockopt(aSocket, IPPROTO_IP, IP_MULTICAST_IF, &aDestination, sizeof(aDestination)); // Allow the socket to send broadcast messages if ( (setsockopt(aSocket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(int))) == -1) { LOG4CXX_ERROR(iLogger, "Not allowed to send broadcast"); return 255; } if (sendto(aSocket, aMessageToSend, aMessageLength, 0, (struct sockaddr *) &aDestination, sizeof(aDestination)) != aMessageLength) { LOG4CXX_ERROR(iLogger, "Did not send the right number of bytes.."); return 255; } aDestinationLength = sizeof(aDestination); if (recvfrom(aSocket, aReply, sizeof(aReply), 0, (struct sockaddr *) &aDestination, &aDestinationLength) == -1) { LOG4CXX_ERROR(iLogger, "Did not receive a message..."); return 255; } uint8_t aFirstSeparator, aSecondSeparator, aFirstSize, aSecondSize; std::string aFirstUrl, aSecondUrl; aFirstSeparator = (uint8_t) aReply[0]; aFirstSize = (uint8_t) aReply[1]; aFirstUrl = std::string(&aReply[2], aFirstSize); aSecondSeparator = (uint8_t) aReply[2 + aFirstSize]; aSecondSize = (uint8_t) aReply[2 + aFirstSize + 1]; aSecondUrl = std::string(&aReply[2 + aFirstSize + 2], aSecondSize); char aBufferForLogger[128]; sprintf(aBufferForLogger, "0x%X %d (%s) 0x%X %d (%s)\n", aFirstSeparator, aFirstSize, aFirstUrl.c_str(), aSecondSeparator, aSecondSize, aSecondUrl.c_str()); LOG4CXX_INFO(iLogger, aBufferForLogger); close(aSocket); return (aFirstSeparator == 0xA0 and aSecondSeparator == 0xA1) ? 0 : 1; } void simulateServer(log4cxx::LoggerPtr iLogger) { orwell::tasks::Server aServer("tcp://*:9801", "tcp://*:9991", 500, iLogger); LOG4CXX_INFO(iLogger, "Running broadcast receiver on server"); aServer.runBroadcastReceiver(); LOG4CXX_INFO(iLogger, "Server stopped correctly"); } int main(int argc, const char * argv []) { int aRc(0); auto logger = Common::SetupLogger("hello"); NDC ndc("broadcast"); switch (fork()) { case 0: simulateServer(logger); return 0; default: usleep(2543); aRc = simulateClient(logger); usleep(2545); } return aRc; }<commit_msg>Cleaning include paths.<commit_after>// // broadcast_test.cpp // orwell // // Created by Massimo Gengarelli on 15/02/14. // // #include "orwell/com/RawMessage.hpp" #include <zmq.hpp> #include "controller.pb.h" #include "server-game.pb.h" #include "orwell/com/Sender.hpp" #include "orwell/com/Receiver.hpp" #include "orwell/Server.hpp" #include "Common.hpp" #include <log4cxx/logger.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/ndc.h> #include <string> #include <cstring> #include <netinet/udp.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <iostream> #include <sstream> using namespace log4cxx; using namespace orwell::com; using namespace orwell::messages; using namespace std; struct IP4 { uint8_t b1, b2, b3, b4 = 0; operator std::string() const { char buffer[32]; sprintf(&buffer[0], "%u.%u.%u.%u", b1, b2, b3, b4); return std::string(buffer); }; operator bool() const { return (not (b1 == 0 and b2 == 0 and b3 == 0 and b4 == 0)); }; friend std::ostream & operator<<(std::ostream & _stream, IP4 const & ip4) { _stream << (std::string) ip4; return _stream; }; }; bool get_ip4(IP4 & oIp4) { char szBuffer[1024]; if(gethostname(szBuffer, sizeof(szBuffer)) == -1) { return false; } struct hostent *host = gethostbyname(szBuffer); if(host == NULL) { return false; } //Obtain the computer's IP oIp4.b1 = (uint8_t) host->h_addr_list[0][0]; oIp4.b2 = (uint8_t) host->h_addr_list[0][1]; oIp4.b3 = (uint8_t) host->h_addr_list[0][2]; oIp4.b4 = (uint8_t) host->h_addr_list[0][3]; return true; } uint32_t simulateClient(log4cxx::LoggerPtr iLogger) { int aSocket; ssize_t aMessageLength; struct sockaddr_in aDestination; unsigned int aDestinationLength; char aReply[256]; char *aMessageToSend = (char*) "1AFTW"; aMessageLength = strlen(aMessageToSend); int broadcast = 1; // Build the socket if ( (aSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) ) < 0) { perror("socket()"); return 255; } IP4 address; if (not get_ip4(address)) { LOG4CXX_ERROR(iLogger, "Couldn't retrieve local address"); return 255; } address.b4 = 255; if (address) { LOG4CXX_INFO(iLogger, "IP: " << address); } // Build the destination object memset(&aDestination, 0, sizeof(aDestination)); aDestination.sin_family = AF_INET; aDestination.sin_addr.s_addr = inet_addr( ((std::string) address).c_str()); aDestination.sin_port = htons(9080); // Set the destination to the socket setsockopt(aSocket, IPPROTO_IP, IP_MULTICAST_IF, &aDestination, sizeof(aDestination)); // Allow the socket to send broadcast messages if ( (setsockopt(aSocket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(int))) == -1) { LOG4CXX_ERROR(iLogger, "Not allowed to send broadcast"); return 255; } if (sendto(aSocket, aMessageToSend, aMessageLength, 0, (struct sockaddr *) &aDestination, sizeof(aDestination)) != aMessageLength) { LOG4CXX_ERROR(iLogger, "Did not send the right number of bytes.."); return 255; } aDestinationLength = sizeof(aDestination); if (recvfrom(aSocket, aReply, sizeof(aReply), 0, (struct sockaddr *) &aDestination, &aDestinationLength) == -1) { LOG4CXX_ERROR(iLogger, "Did not receive a message..."); return 255; } uint8_t aFirstSeparator, aSecondSeparator, aFirstSize, aSecondSize; std::string aFirstUrl, aSecondUrl; aFirstSeparator = (uint8_t) aReply[0]; aFirstSize = (uint8_t) aReply[1]; aFirstUrl = std::string(&aReply[2], aFirstSize); aSecondSeparator = (uint8_t) aReply[2 + aFirstSize]; aSecondSize = (uint8_t) aReply[2 + aFirstSize + 1]; aSecondUrl = std::string(&aReply[2 + aFirstSize + 2], aSecondSize); char aBufferForLogger[128]; sprintf(aBufferForLogger, "0x%X %d (%s) 0x%X %d (%s)\n", aFirstSeparator, aFirstSize, aFirstUrl.c_str(), aSecondSeparator, aSecondSize, aSecondUrl.c_str()); LOG4CXX_INFO(iLogger, aBufferForLogger); close(aSocket); return (aFirstSeparator == 0xA0 and aSecondSeparator == 0xA1) ? 0 : 1; } void simulateServer(log4cxx::LoggerPtr iLogger) { orwell::tasks::Server aServer("tcp://*:9801", "tcp://*:9991", 500, iLogger); LOG4CXX_INFO(iLogger, "Running broadcast receiver on server"); aServer.runBroadcastReceiver(); LOG4CXX_INFO(iLogger, "Server stopped correctly"); } int main(int argc, const char * argv []) { int aRc(0); auto logger = Common::SetupLogger("hello"); NDC ndc("broadcast"); switch (fork()) { case 0: simulateServer(logger); return 0; default: usleep(2543); aRc = simulateClient(logger); usleep(2545); } return aRc; } <|endoftext|>
<commit_before>#include <algorithm> #include <cstring> #include <ctime> #include "frame/test_macros.h" #include "time/time_utility.h" #include <time/jiffies_timer.h> CASE_TEST(time_test, global_offset) { util::time::time_utility::update(); time_t now = util::time::time_utility::get_now(); util::time::time_utility::set_global_now_offset(std::chrono::duration_cast<std::chrono::system_clock::duration>(std::chrono::seconds(5))); CASE_EXPECT_EQ(now + 5, util::time::time_utility::get_now()); CASE_EXPECT_EQ(std::chrono::duration_cast<std::chrono::system_clock::duration>(std::chrono::seconds(5)), util::time::time_utility::get_global_now_offset()); util::time::time_utility::reset_global_now_offset(); CASE_EXPECT_EQ(now, util::time::time_utility::get_now()); } CASE_TEST(time_test, zone_offset) { util::time::time_utility::update(); time_t offset = util::time::time_utility::get_sys_zone_offset() - 5 * util::time::time_utility::HOUR_SECONDS; util::time::time_utility::set_zone_offset(offset); CASE_EXPECT_EQ(offset, util::time::time_utility::get_zone_offset()); CASE_EXPECT_NE(offset, util::time::time_utility::get_sys_zone_offset()); // 恢复时区设置 util::time::time_utility::set_zone_offset(util::time::time_utility::get_sys_zone_offset()); } CASE_TEST(time_test, today_offset) { using std::abs; struct tm tobj; time_t tnow, loffset, cnow; util::time::time_utility::update(); tnow = util::time::time_utility::get_now(); UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj); loffset = tobj.tm_hour * util::time::time_utility::HOUR_SECONDS + tobj.tm_min * util::time::time_utility::MINITE_SECONDS + tobj.tm_sec; cnow = util::time::time_utility::get_today_offset(loffset); // 只有闰秒误差,肯定在5秒以内 // 容忍夏时令误差,所以要加一小时 time_t toff = (cnow + util::time::time_utility::DAY_SECONDS - tnow) % util::time::time_utility::DAY_SECONDS; if (tobj.tm_isdst > 0) { CASE_EXPECT_LE(toff, 3605); } else { CASE_EXPECT_LE(toff, 5); } } CASE_TEST(time_test, is_same_day) { struct tm tobj; time_t lt, rt; util::time::time_utility::update(); lt = util::time::time_utility::get_now(); UTIL_STRFUNC_LOCALTIME_S(&lt, &tobj); tobj.tm_isdst = 0; tobj.tm_hour = 0; tobj.tm_min = 0; tobj.tm_sec = 5; lt = mktime(&tobj); rt = lt + 5; CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt)); tobj.tm_isdst = 0; tobj.tm_hour = 23; tobj.tm_min = 59; tobj.tm_sec = 55; rt = mktime(&tobj); CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt)); lt = rt - 5; CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt)); // 容忍夏时令误差 lt = rt + 3610; CASE_EXPECT_FALSE(util::time::time_utility::is_same_day(lt, rt)); } CASE_TEST(time_test, is_same_day_with_offset) { struct tm tobj; time_t lt, rt; int zero_hore = 5; time_t day_offset = zero_hore * util::time::time_utility::HOUR_SECONDS; util::time::time_utility::update(); lt = util::time::time_utility::get_now(); UTIL_STRFUNC_LOCALTIME_S(&lt, &tobj); tobj.tm_isdst = 0; tobj.tm_hour = zero_hore; tobj.tm_min = 0; tobj.tm_sec = 5; lt = mktime(&tobj); rt = lt + 5; CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt, day_offset)); tobj.tm_isdst = 0; tobj.tm_hour = zero_hore - 1; tobj.tm_min = 59; tobj.tm_sec = 55; rt = mktime(&tobj); CASE_EXPECT_FALSE(util::time::time_utility::is_same_day(lt, rt, day_offset)); } CASE_TEST(time_test, is_same_week) { struct tm tobj; time_t lt, rt, tnow; util::time::time_utility::update(); tnow = util::time::time_utility::get_now(); UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj); tobj.tm_isdst = 0; tobj.tm_hour = 0; tobj.tm_min = 0; tobj.tm_sec = 5; lt = mktime(&tobj); lt -= util::time::time_utility::DAY_SECONDS * tobj.tm_wday; rt = lt + util::time::time_utility::WEEK_SECONDS; CASE_EXPECT_FALSE(util::time::time_utility::is_same_week(lt, rt)); rt -= 10; CASE_EXPECT_TRUE(util::time::time_utility::is_same_week(lt, rt)); CASE_EXPECT_TRUE(util::time::time_utility::is_same_week(lt, tnow)); } CASE_TEST(time_test, get_week_day) { struct tm tobj; time_t lt, rt, tnow; util::time::time_utility::update(); tnow = util::time::time_utility::get_now(); UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj); bool isdst = tobj.tm_isdst > 0; tobj.tm_isdst = 0; tobj.tm_hour = 0; tobj.tm_min = 0; tobj.tm_sec = 5; lt = mktime(&tobj); tobj.tm_isdst = 0; tobj.tm_hour = 23; tobj.tm_min = 59; tobj.tm_sec = 55; rt = mktime(&tobj); CASE_MSG_INFO() << "lt=" << lt << ",tnow=" << tnow << ",rt=" << rt << std::endl; // 夏时令会导致lt和rt可能提前一天 if (isdst && lt > tnow + 5) { lt -= util::time::time_utility::DAY_SECONDS; rt -= util::time::time_utility::DAY_SECONDS; } CASE_EXPECT_EQ(util::time::time_utility::get_week_day(lt), util::time::time_utility::get_week_day(tnow)); CASE_EXPECT_EQ(util::time::time_utility::get_week_day(lt), util::time::time_utility::get_week_day(rt)); } CASE_TEST(time_test, is_same_month) { // nothing todo use libc now } typedef util::time::jiffies_timer<6, 3, 4> short_timer_t; struct jiffies_timer_fn { void *check_priv_data; jiffies_timer_fn(void *pd) : check_priv_data(pd) {} void operator()(time_t, const short_timer_t::timer_t &timer) { if (NULL != check_priv_data) { CASE_EXPECT_EQ(short_timer_t::get_timer_private_data(timer), check_priv_data); } else if (NULL != short_timer_t::get_timer_private_data(timer)) { ++(*reinterpret_cast<int *>(short_timer_t::get_timer_private_data(timer))); } CASE_MSG_INFO() << "jiffies_timer " << short_timer_t::get_timer_sequence(timer) << " actived" << std::endl; } }; CASE_TEST(time_test, jiffies_timer_basic) { short_timer_t short_timer; int count = 0; time_t max_tick = short_timer.get_max_tick_distance() + 1; CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_NOT_INITED, short_timer.add_timer(123, jiffies_timer_fn(NULL), NULL)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_NOT_INITED, short_timer.tick(456)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.init(max_tick)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_ALREADY_INITED, short_timer.init(max_tick)); CASE_EXPECT_EQ(32767, short_timer.get_max_tick_distance()); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_TIMEOUT_EXTENDED, short_timer.add_timer(short_timer.get_max_tick_distance() + 1, jiffies_timer_fn(NULL), NULL)); // 理论上会被放在(数组下标: 2^6*3=192) CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(short_timer.get_max_tick_distance(), jiffies_timer_fn(&short_timer), &short_timer)); // 理论上会被放在(数组下标: 2^6*4-1=255) CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(short_timer.get_max_tick_distance() - short_timer_t::LVL_GRAN(3), jiffies_timer_fn(&short_timer), &short_timer)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(-123, jiffies_timer_fn(NULL), &count)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(30, jiffies_timer_fn(NULL), &count)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(40, jiffies_timer_fn(NULL), &count)); CASE_EXPECT_EQ(5, static_cast<int>(short_timer.size())); CASE_EXPECT_EQ(0, count); short_timer.tick(max_tick); CASE_EXPECT_EQ(0, count); short_timer.tick(max_tick + 1); CASE_EXPECT_EQ(1, count); CASE_EXPECT_EQ(4, static_cast<int>(short_timer.size())); // +30的触发点是+31。因为添加定时器的时候会认为当前时间是+0.XXX,并且由于触发只会延后不会提前 short_timer.tick(max_tick + 30); CASE_EXPECT_EQ(1, count); short_timer.tick(max_tick + 31); CASE_EXPECT_EQ(2, count); // 跨tick short_timer.tick(max_tick + 64); CASE_EXPECT_EQ(3, count); CASE_EXPECT_EQ(2, static_cast<int>(short_timer.size())); // 非第一层、非第一个定时器组.(512+64*5-1 = 831) CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(831, jiffies_timer_fn(NULL), &count)); short_timer.tick(max_tick + 64 + 831); CASE_EXPECT_EQ(3, count); // 768-831 share tick short_timer.tick(max_tick + 64 + 832); CASE_EXPECT_EQ(4, count); // 32767 short_timer.tick(32767 + max_tick); // 这个应该会放在数组下标为0的位置 CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(0, jiffies_timer_fn(NULL), &count)); // 环状数组的复用 CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(1000, jiffies_timer_fn(NULL), &count)); // 全部执行掉 short_timer.tick(32767 + max_tick + 2000); CASE_EXPECT_EQ(6, count); CASE_EXPECT_EQ(0, static_cast<int>(short_timer.size())); } CASE_TEST(time_test, jiffies_timer_slot) { size_t timer_list_count[short_timer_t::WHEEL_SIZE] = {0}; time_t blank_area[short_timer_t::WHEEL_SIZE / short_timer_t::LVL_SIZE] = {0}; time_t max_tick = short_timer_t::get_max_tick_distance(); for (time_t i = 0; i <= max_tick; ++i) { size_t idx = short_timer_t::calc_wheel_index(i, 0); CASE_EXPECT_LT(idx, static_cast<size_t>(short_timer_t::WHEEL_SIZE)); ++timer_list_count[idx]; } // 每个idx的计数器测试 for (size_t i = 0; i < short_timer_t::WHEEL_SIZE; ++i) { size_t timer_count = timer_list_count[i]; // 除了第一个定时器区间外,每个定时器区间都有一段空白区域 if (0 == timer_count) { ++blank_area[i / short_timer_t::LVL_SIZE]; } else { CASE_EXPECT_EQ(timer_count, static_cast<size_t>(short_timer_t::LVL_GRAN(i / short_timer_t::LVL_SIZE))); } } // 定时器空白区间的个数应该等于重合区域 for (size_t i = 1; i < short_timer_t::WHEEL_SIZE / short_timer_t::LVL_SIZE; ++i) { CASE_EXPECT_EQ(blank_area[i], short_timer_t::LVL_START(i) / short_timer_t::LVL_GRAN(i)); } } <commit_msg>1. remove FindLibwebsockets.cmake and we can using new cmake module for libwebsockets now. 2. add time_utility global offset supported 3. fix linking problem for unit test when enable openssl<commit_after>#include <algorithm> #include <cstring> #include <ctime> #include "frame/test_macros.h" #include "time/time_utility.h" #include <time/jiffies_timer.h> CASE_TEST(time_test, global_offset) { util::time::time_utility::update(); time_t now = util::time::time_utility::get_now(); util::time::time_utility::set_global_now_offset(std::chrono::duration_cast<std::chrono::system_clock::duration>(std::chrono::seconds(5))); CASE_EXPECT_EQ(now + 5, util::time::time_utility::get_now()); CASE_EXPECT_EQ(std::chrono::duration_cast<std::chrono::system_clock::duration>(std::chrono::seconds(5)).count(), util::time::time_utility::get_global_now_offset().count()); util::time::time_utility::reset_global_now_offset(); CASE_EXPECT_EQ(now, util::time::time_utility::get_now()); } CASE_TEST(time_test, zone_offset) { util::time::time_utility::update(); time_t offset = util::time::time_utility::get_sys_zone_offset() - 5 * util::time::time_utility::HOUR_SECONDS; util::time::time_utility::set_zone_offset(offset); CASE_EXPECT_EQ(offset, util::time::time_utility::get_zone_offset()); CASE_EXPECT_NE(offset, util::time::time_utility::get_sys_zone_offset()); // 恢复时区设置 util::time::time_utility::set_zone_offset(util::time::time_utility::get_sys_zone_offset()); } CASE_TEST(time_test, today_offset) { using std::abs; struct tm tobj; time_t tnow, loffset, cnow; util::time::time_utility::update(); tnow = util::time::time_utility::get_now(); UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj); loffset = tobj.tm_hour * util::time::time_utility::HOUR_SECONDS + tobj.tm_min * util::time::time_utility::MINITE_SECONDS + tobj.tm_sec; cnow = util::time::time_utility::get_today_offset(loffset); // 只有闰秒误差,肯定在5秒以内 // 容忍夏时令误差,所以要加一小时 time_t toff = (cnow + util::time::time_utility::DAY_SECONDS - tnow) % util::time::time_utility::DAY_SECONDS; if (tobj.tm_isdst > 0) { CASE_EXPECT_LE(toff, 3605); } else { CASE_EXPECT_LE(toff, 5); } } CASE_TEST(time_test, is_same_day) { struct tm tobj; time_t lt, rt; util::time::time_utility::update(); lt = util::time::time_utility::get_now(); UTIL_STRFUNC_LOCALTIME_S(&lt, &tobj); tobj.tm_isdst = 0; tobj.tm_hour = 0; tobj.tm_min = 0; tobj.tm_sec = 5; lt = mktime(&tobj); rt = lt + 5; CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt)); tobj.tm_isdst = 0; tobj.tm_hour = 23; tobj.tm_min = 59; tobj.tm_sec = 55; rt = mktime(&tobj); CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt)); lt = rt - 5; CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt)); // 容忍夏时令误差 lt = rt + 3610; CASE_EXPECT_FALSE(util::time::time_utility::is_same_day(lt, rt)); } CASE_TEST(time_test, is_same_day_with_offset) { struct tm tobj; time_t lt, rt; int zero_hore = 5; time_t day_offset = zero_hore * util::time::time_utility::HOUR_SECONDS; util::time::time_utility::update(); lt = util::time::time_utility::get_now(); UTIL_STRFUNC_LOCALTIME_S(&lt, &tobj); tobj.tm_isdst = 0; tobj.tm_hour = zero_hore; tobj.tm_min = 0; tobj.tm_sec = 5; lt = mktime(&tobj); rt = lt + 5; CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt, day_offset)); tobj.tm_isdst = 0; tobj.tm_hour = zero_hore - 1; tobj.tm_min = 59; tobj.tm_sec = 55; rt = mktime(&tobj); CASE_EXPECT_FALSE(util::time::time_utility::is_same_day(lt, rt, day_offset)); } CASE_TEST(time_test, is_same_week) { struct tm tobj; time_t lt, rt, tnow; util::time::time_utility::update(); tnow = util::time::time_utility::get_now(); UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj); tobj.tm_isdst = 0; tobj.tm_hour = 0; tobj.tm_min = 0; tobj.tm_sec = 5; lt = mktime(&tobj); lt -= util::time::time_utility::DAY_SECONDS * tobj.tm_wday; rt = lt + util::time::time_utility::WEEK_SECONDS; CASE_EXPECT_FALSE(util::time::time_utility::is_same_week(lt, rt)); rt -= 10; CASE_EXPECT_TRUE(util::time::time_utility::is_same_week(lt, rt)); CASE_EXPECT_TRUE(util::time::time_utility::is_same_week(lt, tnow)); } CASE_TEST(time_test, get_week_day) { struct tm tobj; time_t lt, rt, tnow; util::time::time_utility::update(); tnow = util::time::time_utility::get_now(); UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj); bool isdst = tobj.tm_isdst > 0; tobj.tm_isdst = 0; tobj.tm_hour = 0; tobj.tm_min = 0; tobj.tm_sec = 5; lt = mktime(&tobj); tobj.tm_isdst = 0; tobj.tm_hour = 23; tobj.tm_min = 59; tobj.tm_sec = 55; rt = mktime(&tobj); CASE_MSG_INFO() << "lt=" << lt << ",tnow=" << tnow << ",rt=" << rt << std::endl; // 夏时令会导致lt和rt可能提前一天 if (isdst && lt > tnow + 5) { lt -= util::time::time_utility::DAY_SECONDS; rt -= util::time::time_utility::DAY_SECONDS; } CASE_EXPECT_EQ(util::time::time_utility::get_week_day(lt), util::time::time_utility::get_week_day(tnow)); CASE_EXPECT_EQ(util::time::time_utility::get_week_day(lt), util::time::time_utility::get_week_day(rt)); } CASE_TEST(time_test, is_same_month) { // nothing todo use libc now } typedef util::time::jiffies_timer<6, 3, 4> short_timer_t; struct jiffies_timer_fn { void *check_priv_data; jiffies_timer_fn(void *pd) : check_priv_data(pd) {} void operator()(time_t, const short_timer_t::timer_t &timer) { if (NULL != check_priv_data) { CASE_EXPECT_EQ(short_timer_t::get_timer_private_data(timer), check_priv_data); } else if (NULL != short_timer_t::get_timer_private_data(timer)) { ++(*reinterpret_cast<int *>(short_timer_t::get_timer_private_data(timer))); } CASE_MSG_INFO() << "jiffies_timer " << short_timer_t::get_timer_sequence(timer) << " actived" << std::endl; } }; CASE_TEST(time_test, jiffies_timer_basic) { short_timer_t short_timer; int count = 0; time_t max_tick = short_timer.get_max_tick_distance() + 1; CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_NOT_INITED, short_timer.add_timer(123, jiffies_timer_fn(NULL), NULL)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_NOT_INITED, short_timer.tick(456)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.init(max_tick)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_ALREADY_INITED, short_timer.init(max_tick)); CASE_EXPECT_EQ(32767, short_timer.get_max_tick_distance()); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_TIMEOUT_EXTENDED, short_timer.add_timer(short_timer.get_max_tick_distance() + 1, jiffies_timer_fn(NULL), NULL)); // 理论上会被放在(数组下标: 2^6*3=192) CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(short_timer.get_max_tick_distance(), jiffies_timer_fn(&short_timer), &short_timer)); // 理论上会被放在(数组下标: 2^6*4-1=255) CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(short_timer.get_max_tick_distance() - short_timer_t::LVL_GRAN(3), jiffies_timer_fn(&short_timer), &short_timer)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(-123, jiffies_timer_fn(NULL), &count)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(30, jiffies_timer_fn(NULL), &count)); CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(40, jiffies_timer_fn(NULL), &count)); CASE_EXPECT_EQ(5, static_cast<int>(short_timer.size())); CASE_EXPECT_EQ(0, count); short_timer.tick(max_tick); CASE_EXPECT_EQ(0, count); short_timer.tick(max_tick + 1); CASE_EXPECT_EQ(1, count); CASE_EXPECT_EQ(4, static_cast<int>(short_timer.size())); // +30的触发点是+31。因为添加定时器的时候会认为当前时间是+0.XXX,并且由于触发只会延后不会提前 short_timer.tick(max_tick + 30); CASE_EXPECT_EQ(1, count); short_timer.tick(max_tick + 31); CASE_EXPECT_EQ(2, count); // 跨tick short_timer.tick(max_tick + 64); CASE_EXPECT_EQ(3, count); CASE_EXPECT_EQ(2, static_cast<int>(short_timer.size())); // 非第一层、非第一个定时器组.(512+64*5-1 = 831) CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(831, jiffies_timer_fn(NULL), &count)); short_timer.tick(max_tick + 64 + 831); CASE_EXPECT_EQ(3, count); // 768-831 share tick short_timer.tick(max_tick + 64 + 832); CASE_EXPECT_EQ(4, count); // 32767 short_timer.tick(32767 + max_tick); // 这个应该会放在数组下标为0的位置 CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(0, jiffies_timer_fn(NULL), &count)); // 环状数组的复用 CASE_EXPECT_EQ(short_timer_t::error_type_t::EN_JTET_SUCCESS, short_timer.add_timer(1000, jiffies_timer_fn(NULL), &count)); // 全部执行掉 short_timer.tick(32767 + max_tick + 2000); CASE_EXPECT_EQ(6, count); CASE_EXPECT_EQ(0, static_cast<int>(short_timer.size())); } CASE_TEST(time_test, jiffies_timer_slot) { size_t timer_list_count[short_timer_t::WHEEL_SIZE] = {0}; time_t blank_area[short_timer_t::WHEEL_SIZE / short_timer_t::LVL_SIZE] = {0}; time_t max_tick = short_timer_t::get_max_tick_distance(); for (time_t i = 0; i <= max_tick; ++i) { size_t idx = short_timer_t::calc_wheel_index(i, 0); CASE_EXPECT_LT(idx, static_cast<size_t>(short_timer_t::WHEEL_SIZE)); ++timer_list_count[idx]; } // 每个idx的计数器测试 for (size_t i = 0; i < short_timer_t::WHEEL_SIZE; ++i) { size_t timer_count = timer_list_count[i]; // 除了第一个定时器区间外,每个定时器区间都有一段空白区域 if (0 == timer_count) { ++blank_area[i / short_timer_t::LVL_SIZE]; } else { CASE_EXPECT_EQ(timer_count, static_cast<size_t>(short_timer_t::LVL_GRAN(i / short_timer_t::LVL_SIZE))); } } // 定时器空白区间的个数应该等于重合区域 for (size_t i = 1; i < short_timer_t::WHEEL_SIZE / short_timer_t::LVL_SIZE; ++i) { CASE_EXPECT_EQ(blank_area[i], short_timer_t::LVL_START(i) / short_timer_t::LVL_GRAN(i)); } } <|endoftext|>
<commit_before>// Convert DMD CodeView/DWARF debug information to PDB files // Copyright (c) 2009-2012 by Rainer Schuetze, All Rights Reserved // // License for redistribution is given by the Artistic License 2.0 // see file LICENSE for further details // #include "PEImage.h" #include "mspdb.h" #include "dwarf.h" #include "readDwarf.h" bool isRelativePath(const std::string& s) { if(s.length() < 1) return true; if(s[0] == '/' || s[0] == '\\') return false; if(s.length() < 2) return true; if(s[1] == ':') return false; return true; } static int cmpAdr(const void* s1, const void* s2) { const mspdb::LineInfoEntry* e1 = (const mspdb::LineInfoEntry*) s1; const mspdb::LineInfoEntry* e2 = (const mspdb::LineInfoEntry*) s2; return e1->offset - e2->offset; } bool printLines(char const *fname, unsigned short sec, char const *secname, mspdb::LineInfoEntry* pLineInfo, long numLineInfo) { printf("Sym: %s\n", secname ? secname : "<none>"); printf("File: %s\n", fname); for (int i = 0; i < numLineInfo; i++) printf("\tOff 0x%x: Line %d\n", pLineInfo[i].offset, pLineInfo[i].line); return true; } bool _flushDWARFLines(const PEImage& img, mspdb::Mod* mod, DWARF_LineState& state) { if(state.lineInfo.size() == 0) return true; unsigned int saddr = state.lineInfo[0].offset; unsigned int eaddr = state.lineInfo.back().offset; int segIndex = state.section; if (segIndex < 0) segIndex = img.findSection(saddr + state.seg_offset); if(segIndex < 0) { // throw away invalid lines (mostly due to "set address to 0") state.lineInfo.resize(0); return true; //return false; } // if(saddr >= 0x4000) // return true; const DWARF_FileName* dfn; if(state.lineInfo_file == 0) dfn = state.file_ptr; else if(state.lineInfo_file > 0 && state.lineInfo_file <= state.files.size()) dfn = &state.files[state.lineInfo_file - 1]; else return false; std::string fname = dfn->file_name; if(isRelativePath(fname) && dfn->dir_index > 0 && dfn->dir_index <= state.include_dirs.size()) { std::string dir = state.include_dirs[dfn->dir_index - 1]; if(dir.length() > 0 && dir[dir.length() - 1] != '/' && dir[dir.length() - 1] != '\\') dir.append("\\"); fname = dir + fname; } for(size_t i = 0; i < fname.length(); i++) if(fname[i] == '/') fname[i] = '\\'; if (!mod) { printLines(fname.c_str(), segIndex, img.findSectionSymbolName(segIndex), state.lineInfo.data(), state.lineInfo.size()); state.lineInfo.resize(0); return true; } #if 1 bool dump = false; // (fname == "cvtest.d"); //qsort(&state.lineInfo[0], state.lineInfo.size(), sizeof(state.lineInfo[0]), cmpAdr); #if 0 printf("%s:\n", fname.c_str()); for(size_t ln = 0; ln < state.lineInfo.size(); ln++) printf(" %08x: %4d\n", state.lineInfo[ln].offset + 0x401000, state.lineInfo[ln].line); #endif int rc = 1; unsigned int low_offset = state.lineInfo[0].offset; unsigned short low_line = state.lineInfo[0].line; for (size_t ln = 0; ln < state.lineInfo.size(); ++ln) { auto& line_entry = state.lineInfo[ln]; line_entry.line -= low_line; line_entry.offset -= low_offset; } unsigned int high_offset = state.address - state.seg_offset; // PDB address ranges are fully closed, so point to before the next instruction --high_offset; unsigned int address_range_length = high_offset - low_offset; if (dump) printf("AddLines(%08x+%04x, Line=%4d+%3d, %s)\n", low_offset, address_range_length, low_line, state.lineInfo.size(), fname.c_str()); rc = mod->AddLines(fname.c_str(), segIndex + 1, low_offset, address_range_length, low_offset, low_line, (unsigned char*)&state.lineInfo[0], state.lineInfo.size() * sizeof(state.lineInfo[0])); #else unsigned int firstLine = 0; unsigned int firstAddr = 0; int rc = mod->AddLines(fname.c_str(), segIndex + 1, saddr, eaddr - saddr, firstAddr, firstLine, (unsigned char*) &state.lineInfo[0], state.lineInfo.size() * sizeof(state.lineInfo[0])); #endif state.lineInfo.resize(0); return rc > 0; } bool addLineInfo(const PEImage& img, mspdb::Mod* mod, DWARF_LineState& state) { // The DWARF standard says about end_sequence: "indicating that the current // address is that of the first byte after the end of a sequence of target // machine instructions". So if this is a end_sequence row, don't append any // lines to the list, just flush it. if (state.end_sequence) return _flushDWARFLines(img, mod, state); #if 0 const char* fname = (state.file == 0 ? state.file_ptr->file_name : state.files[state.file - 1].file_name); printf("Adr:%08x Line: %5d File: %s\n", state.address, state.line, fname); #endif if (state.address < state.seg_offset) return true; mspdb::LineInfoEntry entry; entry.offset = state.address - state.seg_offset; entry.line = state.line; if (!state.lineInfo.empty()) { auto first_entry = state.lineInfo.front(); auto last_entry = state.lineInfo.back(); if (entry.line < first_entry.line || entry.offset < first_entry.offset || state.lineInfo_file != state.file) { if (!_flushDWARFLines(img, mod, state)) return false; } else if (entry.line == last_entry.line && entry.offset == last_entry.offset) { // There's no need to add duplicate entries return true; } } state.lineInfo.push_back(entry); state.lineInfo_file = state.file; return true; } bool interpretDWARFLines(const PEImage& img, mspdb::Mod* mod) { DWARF_CompilationUnit* cu = (DWARF_CompilationUnit*)img.debug_info; int ptrsize = cu ? cu->address_size : 4; for(unsigned long off = 0; off < img.debug_line_length; ) { DWARF_LineNumberProgramHeader* hdr = (DWARF_LineNumberProgramHeader*) (img.debug_line + off); int length = hdr->unit_length; if(length < 0) break; length += sizeof(length); unsigned char* p = (unsigned char*) (hdr + 1); unsigned char* end = (unsigned char*) hdr + length; std::vector<unsigned int> opcode_lengths; opcode_lengths.resize(hdr->opcode_base); if (hdr->opcode_base > 0) { opcode_lengths[0] = 0; for(int o = 1; o < hdr->opcode_base && p < end; o++) opcode_lengths[o] = LEB128(p); } DWARF_LineState state; state.seg_offset = img.getImageBase() + img.getSection(img.codeSegment).VirtualAddress; // dirs while(p < end) { if(*p == 0) break; state.include_dirs.push_back((const char*) p); p += strlen((const char*) p) + 1; } p++; // files DWARF_FileName fname; while(p < end && *p) { fname.read(p); state.files.push_back(fname); } p++; state.init(hdr); while(p < end) { int opcode = *p++; if(opcode >= hdr->opcode_base) { // special opcode int adjusted_opcode = opcode - hdr->opcode_base; int operation_advance = adjusted_opcode / hdr->line_range; state.advance_addr(hdr, operation_advance); int line_advance = hdr->line_base + (adjusted_opcode % hdr->line_range); state.line += line_advance; if (!addLineInfo(img, mod, state)) return false; state.basic_block = false; state.prologue_end = false; state.epilogue_end = false; state.discriminator = 0; } else { switch(opcode) { case 0: // extended { int exlength = LEB128(p); unsigned char* q = p + exlength; int excode = *p++; switch(excode) { case DW_LNE_end_sequence: if((char*)p - img.debug_line >= 0xe4e0) p = p; state.end_sequence = true; state.last_addr = state.address; if(!addLineInfo(img, mod, state)) return false; state.init(hdr); break; case DW_LNE_set_address: { if (!mod && state.section == -1) state.section = img.getRelocationInLineSegment((char*)p - img.debug_line); unsigned long adr = ptrsize == 8 ? RD8(p) : RD4(p); state.address = adr; state.op_index = 0; break; } case DW_LNE_define_file: fname.read(p); state.file_ptr = &fname; state.file = 0; break; case DW_LNE_set_discriminator: state.discriminator = LEB128(p); break; } p = q; break; } case DW_LNS_copy: if (!addLineInfo(img, mod, state)) return false; state.basic_block = false; state.prologue_end = false; state.epilogue_end = false; state.discriminator = 0; break; case DW_LNS_advance_pc: state.advance_addr(hdr, LEB128(p)); break; case DW_LNS_advance_line: state.line += SLEB128(p); break; case DW_LNS_set_file: state.file = LEB128(p); break; case DW_LNS_set_column: state.column = LEB128(p); break; case DW_LNS_negate_stmt: state.is_stmt = !state.is_stmt; break; case DW_LNS_set_basic_block: state.basic_block = true; break; case DW_LNS_const_add_pc: state.advance_addr(hdr, (255 - hdr->opcode_base) / hdr->line_range); break; case DW_LNS_fixed_advance_pc: state.address += RD2(p); state.op_index = 0; break; case DW_LNS_set_prologue_end: state.prologue_end = true; break; case DW_LNS_set_epilogue_begin: state.epilogue_end = true; break; case DW_LNS_set_isa: state.isa = LEB128(p); break; default: // unknown standard opcode for(unsigned int arg = 0; arg < opcode_lengths[opcode]; arg++) LEB128(p); break; } } } if(!_flushDWARFLines(img, mod, state)) return false; off += length; } return true; } <commit_msg>Don't write line sequences containing decreasing addresses<commit_after>// Convert DMD CodeView/DWARF debug information to PDB files // Copyright (c) 2009-2012 by Rainer Schuetze, All Rights Reserved // // License for redistribution is given by the Artistic License 2.0 // see file LICENSE for further details // #include "PEImage.h" #include "mspdb.h" #include "dwarf.h" #include "readDwarf.h" bool isRelativePath(const std::string& s) { if(s.length() < 1) return true; if(s[0] == '/' || s[0] == '\\') return false; if(s.length() < 2) return true; if(s[1] == ':') return false; return true; } static int cmpAdr(const void* s1, const void* s2) { const mspdb::LineInfoEntry* e1 = (const mspdb::LineInfoEntry*) s1; const mspdb::LineInfoEntry* e2 = (const mspdb::LineInfoEntry*) s2; return e1->offset - e2->offset; } bool printLines(char const *fname, unsigned short sec, char const *secname, mspdb::LineInfoEntry* pLineInfo, long numLineInfo) { printf("Sym: %s\n", secname ? secname : "<none>"); printf("File: %s\n", fname); for (int i = 0; i < numLineInfo; i++) printf("\tOff 0x%x: Line %d\n", pLineInfo[i].offset, pLineInfo[i].line); return true; } bool _flushDWARFLines(const PEImage& img, mspdb::Mod* mod, DWARF_LineState& state) { if(state.lineInfo.size() == 0) return true; unsigned int saddr = state.lineInfo[0].offset; unsigned int eaddr = state.lineInfo.back().offset; int segIndex = state.section; if (segIndex < 0) segIndex = img.findSection(saddr + state.seg_offset); if(segIndex < 0) { // throw away invalid lines (mostly due to "set address to 0") state.lineInfo.resize(0); return true; //return false; } // if(saddr >= 0x4000) // return true; const DWARF_FileName* dfn; if(state.lineInfo_file == 0) dfn = state.file_ptr; else if(state.lineInfo_file > 0 && state.lineInfo_file <= state.files.size()) dfn = &state.files[state.lineInfo_file - 1]; else return false; std::string fname = dfn->file_name; if(isRelativePath(fname) && dfn->dir_index > 0 && dfn->dir_index <= state.include_dirs.size()) { std::string dir = state.include_dirs[dfn->dir_index - 1]; if(dir.length() > 0 && dir[dir.length() - 1] != '/' && dir[dir.length() - 1] != '\\') dir.append("\\"); fname = dir + fname; } for(size_t i = 0; i < fname.length(); i++) if(fname[i] == '/') fname[i] = '\\'; if (!mod) { printLines(fname.c_str(), segIndex, img.findSectionSymbolName(segIndex), state.lineInfo.data(), state.lineInfo.size()); state.lineInfo.resize(0); return true; } #if 1 bool dump = false; // (fname == "cvtest.d"); //qsort(&state.lineInfo[0], state.lineInfo.size(), sizeof(state.lineInfo[0]), cmpAdr); #if 0 printf("%s:\n", fname.c_str()); for(size_t ln = 0; ln < state.lineInfo.size(); ln++) printf(" %08x: %4d\n", state.lineInfo[ln].offset + 0x401000, state.lineInfo[ln].line); #endif int rc = 1; unsigned int low_offset = state.lineInfo[0].offset; unsigned short low_line = state.lineInfo[0].line; for (size_t ln = 0; ln < state.lineInfo.size(); ++ln) { auto& line_entry = state.lineInfo[ln]; line_entry.line -= low_line; line_entry.offset -= low_offset; } unsigned int high_offset = state.address - state.seg_offset; if (high_offset < state.lineInfo.back().offset + low_offset) // The current address is before the previous address; use that as the end instead to ensure we capture all of the preceeding line info high_offset = state.lineInfo.back().offset + low_offset; // PDB address ranges are fully closed, so point to before the next instruction --high_offset; // This subtraction can underflow to (unsigned)-1 if this info is only for a single instruction, but AddLines will immediately increment it to 0, so this is fine. Not underflowing this can cause the debugger to ignore other line info for address ranges that include this address. unsigned int address_range_length = high_offset - low_offset; if (dump) printf("AddLines(%08x+%04x, Line=%4d+%3d, %s)\n", low_offset, address_range_length, low_line, state.lineInfo.size(), fname.c_str()); rc = mod->AddLines(fname.c_str(), segIndex + 1, low_offset, address_range_length, low_offset, low_line, (unsigned char*)&state.lineInfo[0], state.lineInfo.size() * sizeof(state.lineInfo[0])); #else unsigned int firstLine = 0; unsigned int firstAddr = 0; int rc = mod->AddLines(fname.c_str(), segIndex + 1, saddr, eaddr - saddr, firstAddr, firstLine, (unsigned char*) &state.lineInfo[0], state.lineInfo.size() * sizeof(state.lineInfo[0])); #endif state.lineInfo.resize(0); return rc > 0; } bool addLineInfo(const PEImage& img, mspdb::Mod* mod, DWARF_LineState& state) { // The DWARF standard says about end_sequence: "indicating that the current // address is that of the first byte after the end of a sequence of target // machine instructions". So if this is a end_sequence row, don't append any // lines to the list, just flush it. if (state.end_sequence) return _flushDWARFLines(img, mod, state); #if 0 const char* fname = (state.file == 0 ? state.file_ptr->file_name : state.files[state.file - 1].file_name); printf("Adr:%08x Line: %5d File: %s\n", state.address, state.line, fname); #endif if (state.address < state.seg_offset) return true; mspdb::LineInfoEntry entry; entry.offset = state.address - state.seg_offset; entry.line = state.line; if (!state.lineInfo.empty()) { auto first_entry = state.lineInfo.front(); auto last_entry = state.lineInfo.back(); // We can handle out-of-order line numbers, but we can't handle out-of-order addresses if (entry.line < first_entry.line || entry.offset < last_entry.offset || state.lineInfo_file != state.file) { if (!_flushDWARFLines(img, mod, state)) return false; } else if (entry.line == last_entry.line && entry.offset == last_entry.offset) { // There's no need to add duplicate entries return true; } } state.lineInfo.push_back(entry); state.lineInfo_file = state.file; return true; } bool interpretDWARFLines(const PEImage& img, mspdb::Mod* mod) { DWARF_CompilationUnit* cu = (DWARF_CompilationUnit*)img.debug_info; int ptrsize = cu ? cu->address_size : 4; for(unsigned long off = 0; off < img.debug_line_length; ) { DWARF_LineNumberProgramHeader* hdr = (DWARF_LineNumberProgramHeader*) (img.debug_line + off); int length = hdr->unit_length; if(length < 0) break; length += sizeof(length); unsigned char* p = (unsigned char*) (hdr + 1); unsigned char* end = (unsigned char*) hdr + length; std::vector<unsigned int> opcode_lengths; opcode_lengths.resize(hdr->opcode_base); if (hdr->opcode_base > 0) { opcode_lengths[0] = 0; for(int o = 1; o < hdr->opcode_base && p < end; o++) opcode_lengths[o] = LEB128(p); } DWARF_LineState state; state.seg_offset = img.getImageBase() + img.getSection(img.codeSegment).VirtualAddress; // dirs while(p < end) { if(*p == 0) break; state.include_dirs.push_back((const char*) p); p += strlen((const char*) p) + 1; } p++; // files DWARF_FileName fname; while(p < end && *p) { fname.read(p); state.files.push_back(fname); } p++; state.init(hdr); while(p < end) { int opcode = *p++; if(opcode >= hdr->opcode_base) { // special opcode int adjusted_opcode = opcode - hdr->opcode_base; int operation_advance = adjusted_opcode / hdr->line_range; state.advance_addr(hdr, operation_advance); int line_advance = hdr->line_base + (adjusted_opcode % hdr->line_range); state.line += line_advance; if (!addLineInfo(img, mod, state)) return false; state.basic_block = false; state.prologue_end = false; state.epilogue_end = false; state.discriminator = 0; } else { switch(opcode) { case 0: // extended { int exlength = LEB128(p); unsigned char* q = p + exlength; int excode = *p++; switch(excode) { case DW_LNE_end_sequence: if((char*)p - img.debug_line >= 0xe4e0) p = p; state.end_sequence = true; state.last_addr = state.address; if(!addLineInfo(img, mod, state)) return false; state.init(hdr); break; case DW_LNE_set_address: { if (!mod && state.section == -1) state.section = img.getRelocationInLineSegment((char*)p - img.debug_line); unsigned long adr = ptrsize == 8 ? RD8(p) : RD4(p); state.address = adr; state.op_index = 0; break; } case DW_LNE_define_file: fname.read(p); state.file_ptr = &fname; state.file = 0; break; case DW_LNE_set_discriminator: state.discriminator = LEB128(p); break; } p = q; break; } case DW_LNS_copy: if (!addLineInfo(img, mod, state)) return false; state.basic_block = false; state.prologue_end = false; state.epilogue_end = false; state.discriminator = 0; break; case DW_LNS_advance_pc: state.advance_addr(hdr, LEB128(p)); break; case DW_LNS_advance_line: state.line += SLEB128(p); break; case DW_LNS_set_file: state.file = LEB128(p); break; case DW_LNS_set_column: state.column = LEB128(p); break; case DW_LNS_negate_stmt: state.is_stmt = !state.is_stmt; break; case DW_LNS_set_basic_block: state.basic_block = true; break; case DW_LNS_const_add_pc: state.advance_addr(hdr, (255 - hdr->opcode_base) / hdr->line_range); break; case DW_LNS_fixed_advance_pc: state.address += RD2(p); state.op_index = 0; break; case DW_LNS_set_prologue_end: state.prologue_end = true; break; case DW_LNS_set_epilogue_begin: state.epilogue_end = true; break; case DW_LNS_set_isa: state.isa = LEB128(p); break; default: // unknown standard opcode for(unsigned int arg = 0; arg < opcode_lengths[opcode]; arg++) LEB128(p); break; } } } if(!_flushDWARFLines(img, mod, state)) return false; off += length; } return true; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: calendar_hijri.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: khong $ $Date: 2002-08-06 18:32:48 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _I18N_CALENDAR_HIJRI_HXX_ #define _I18N_CALENDAR_HIJRI_HXX_ #include "calendar_gregorian.hxx" // ---------------------------------------------------- // class Calendar_hijri // ---------------------------------------------------- namespace com { namespace sun { namespace star { namespace i18n { class Calendar_hijri : public Calendar_gregorian { public: // Constructors Calendar_hijri(); protected: void SAL_CALL mapToGregorian() throw(com::sun::star::uno::RuntimeException); void SAL_CALL mapFromGregorian() throw(com::sun::star::uno::RuntimeException); // radians per degree (pi/180) static const double RadPerDeg; // Synodic Period (mean time between 2 successive new moon: 29d, 12 hr, 44min, 3sec static const double SynPeriod; static const double SynMonth; // Solar days in a year/SynPeriod // Julian day on Jan 1, 1900 static const double jd1900; // Reference point: September 1984 25d 3h 10m UT. == 1405 Hijri == 1048 Synodial month from 1900 static const sal_Int32 SynRef; static const sal_Int32 GregRef; // Local time (Saudi Arabia) static const double SA_TimeZone; // Time Zone // Period between 1.30pm - 6:30pm static const double EveningPeriod; // "Leap" years static const sal_Int32 LeapYear[]; private: double NewMoon(sal_Int32 n); void getHijri(sal_Int32 *day, sal_Int32 *month, sal_Int32 *year); double getJulianDay(); }; } } } } #endif <commit_msg>#102027# add Hijri Input<commit_after>/************************************************************************* * * $RCSfile: calendar_hijri.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: bustamam $ $Date: 2002-08-15 03:10:04 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _I18N_CALENDAR_HIJRI_HXX_ #define _I18N_CALENDAR_HIJRI_HXX_ #include "calendar_gregorian.hxx" // ---------------------------------------------------- // class Calendar_hijri // ---------------------------------------------------- namespace com { namespace sun { namespace star { namespace i18n { class Calendar_hijri : public Calendar_gregorian { public: // Constructors Calendar_hijri(); protected: void SAL_CALL mapToGregorian() throw(com::sun::star::uno::RuntimeException); void SAL_CALL mapFromGregorian() throw(com::sun::star::uno::RuntimeException); // radians per degree (pi/180) static const double RadPerDeg; // Synodic Period (mean time between 2 successive new moon: 29d, 12 hr, 44min, 3sec static const double SynPeriod; static const double SynMonth; // Solar days in a year/SynPeriod // Julian day on Jan 1, 1900 static const double jd1900; // Reference point: September 1984 25d 3h 10m UT. == 1405 Hijri == 1048 Synodial month from 1900 static const sal_Int32 SynRef; static const sal_Int32 GregRef; // Local time (Saudi Arabia) static const double SA_TimeZone; // Time Zone // Period between 1.30pm - 6:30pm static const double EveningPeriod; // "Leap" years static const sal_Int32 LeapYear[]; private: double NewMoon(sal_Int32 n); void getHijri(sal_Int32 *day, sal_Int32 *month, sal_Int32 *year); void ToGregorian(sal_Int32 *day, sal_Int32 *month, sal_Int32 *year); double getJulianDay(sal_Int32 day, sal_Int32 month, sal_Int32 year); }; } } } } #endif <|endoftext|>
<commit_before>#include <vector> #include <string.h> #include "gtest/gtest.h" #include "radix_sorter.h" #include "codesearch.h" #include "content.h" class radix_sorter_test : public ::testing::Test { protected: radix_sorter_test() : data_("line 1\n" "line 2\n" "another line\n" "another line\n" "line 3\n" "\n" "int main()\n" "really long line that is definitely longer than the word size\n" "really long line that is definitely longer than the word size and then some\n" "really long line that is definitely longer than the word size like whoa\n"), sort_(reinterpret_cast<const unsigned char*>(data_), strlen(data_)) { const char *p = data_; while (p) { lines_.push_back(p - data_); p = strchr(p, '\n'); if (p) p++; } } const char *data_; std::vector<uint32_t> lines_; radix_sorter sort_; }; TEST_F(radix_sorter_test, test_cmp) { radix_sorter::cmp_suffix cmp(sort_); struct { uint32_t lhs, rhs; int cmp; } tests[] = { { lines_[0], lines_[0], 0 }, { lines_[0], lines_[1], -1 }, { lines_[7], lines_[8], -1 }, { lines_[7], lines_[9], -1 }, { lines_[8], lines_[9], -1 }, { lines_[5], lines_[9], -1 }, { lines_[5], lines_[5], 0 }, { lines_[0] + 6, lines_[5], 0 }, }; for (auto it = &tests[0]; it != &(tests + 1)[0]; ++it) { EXPECT_EQ(cmp(it->lhs, it->rhs), it->cmp < 0) << "Expected " << it->lhs << " " << (it->cmp < 0 ? "<" : ">") << " " << it->rhs; EXPECT_EQ(cmp(it->rhs, it->lhs), it->cmp > 0) << "Expected " << it->rhs << " " << (it->cmp > 0 ? "<" : ">") << " " << it->lhs; } } class codesearch_test : public ::testing::Test { protected: codesearch_test() { cs_.set_alloc(make_mem_allocator()); repo_ = cs_.open_repo("REPO", 0); tree_ = cs_.open_revision(repo_, "REV0"); } code_searcher cs_; const indexed_repo *repo_; const indexed_tree *tree_; }; const char *file1 = "The quick brown fox\n" \ "jumps over the lazy\n\n\n" \ "dog.\n"; TEST_F(codesearch_test, IndexTest) { cs_.index_file(tree_, "/data/file1", file1); cs_.finalize(); EXPECT_EQ(1, cs_.end_files() - cs_.begin_files()); indexed_file *f = *cs_.begin_files(); EXPECT_EQ("/data/file1", f->paths[0].path); EXPECT_EQ(tree_, f->paths[0].tree); string content; for (auto it = f->content->begin(cs_.alloc()); it != f->content->end(cs_.alloc()); ++it) { content += it->ToString(); content += "\n"; } EXPECT_EQ(string(file1), content); } <commit_msg>atomic_int tests<commit_after>#include <vector> #include <string.h> #include "gtest/gtest.h" #include "radix_sorter.h" #include "codesearch.h" #include "content.h" #include "atomic.h" class radix_sorter_test : public ::testing::Test { protected: radix_sorter_test() : data_("line 1\n" "line 2\n" "another line\n" "another line\n" "line 3\n" "\n" "int main()\n" "really long line that is definitely longer than the word size\n" "really long line that is definitely longer than the word size and then some\n" "really long line that is definitely longer than the word size like whoa\n"), sort_(reinterpret_cast<const unsigned char*>(data_), strlen(data_)) { const char *p = data_; while (p) { lines_.push_back(p - data_); p = strchr(p, '\n'); if (p) p++; } } const char *data_; std::vector<uint32_t> lines_; radix_sorter sort_; }; TEST_F(radix_sorter_test, test_cmp) { radix_sorter::cmp_suffix cmp(sort_); struct { uint32_t lhs, rhs; int cmp; } tests[] = { { lines_[0], lines_[0], 0 }, { lines_[0], lines_[1], -1 }, { lines_[7], lines_[8], -1 }, { lines_[7], lines_[9], -1 }, { lines_[8], lines_[9], -1 }, { lines_[5], lines_[9], -1 }, { lines_[5], lines_[5], 0 }, { lines_[0] + 6, lines_[5], 0 }, }; for (auto it = &tests[0]; it != &(tests + 1)[0]; ++it) { EXPECT_EQ(cmp(it->lhs, it->rhs), it->cmp < 0) << "Expected " << it->lhs << " " << (it->cmp < 0 ? "<" : ">") << " " << it->rhs; EXPECT_EQ(cmp(it->rhs, it->lhs), it->cmp > 0) << "Expected " << it->rhs << " " << (it->cmp > 0 ? "<" : ">") << " " << it->lhs; } } class codesearch_test : public ::testing::Test { protected: codesearch_test() { cs_.set_alloc(make_mem_allocator()); repo_ = cs_.open_repo("REPO", 0); tree_ = cs_.open_revision(repo_, "REV0"); } code_searcher cs_; const indexed_repo *repo_; const indexed_tree *tree_; }; const char *file1 = "The quick brown fox\n" \ "jumps over the lazy\n\n\n" \ "dog.\n"; TEST_F(codesearch_test, IndexTest) { cs_.index_file(tree_, "/data/file1", file1); cs_.finalize(); EXPECT_EQ(1, cs_.end_files() - cs_.begin_files()); indexed_file *f = *cs_.begin_files(); EXPECT_EQ("/data/file1", f->paths[0].path); EXPECT_EQ(tree_, f->paths[0].tree); string content; for (auto it = f->content->begin(cs_.alloc()); it != f->content->end(cs_.alloc()); ++it) { content += it->ToString(); content += "\n"; } EXPECT_EQ(string(file1), content); } TEST(atomic_int, Basic) { atomic_int i; EXPECT_EQ(0, i.load()); EXPECT_EQ(1, ++i); EXPECT_EQ(1, i.load()); EXPECT_EQ(10, i += 9); EXPECT_EQ(10, i.load()); EXPECT_EQ(9, --i); EXPECT_EQ(9, i.load()); EXPECT_EQ(4, i -= 5); atomic_int j(42); EXPECT_EQ(42, j.load()); } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RL78/G13 グループ SAU/UART 制御 @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "G13/system.hpp" #include "G13/sau.hpp" #include "common/fifo.hpp" /// F_CLK はボーレートパラメーター計算で必要、設定が無いとエラーにします。 #ifndef F_CLK # error "uart_io.hpp requires F_CLK to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief UART 制御クラス @param[in] recv_size 受信バッファサイズ @param[in] send+size 送信バッファサイズ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint16_t recv_size, uint16_t send_size> class uart_io { static utils::fifo<recv_size> recv_; static utils::fifo<send_size> send_; bool polling_ = false; bool crlf_ = true; // ※必要なら、実装する void sleep_() { } public: //-----------------------------------------------------------------// /*! @brief ボーレートを設定して、UART を有効にする @param[in] baud ボーレート @param[in] polling ポーリングの場合「true」 @return エラーなら「false」 */ //-----------------------------------------------------------------// bool start(uint32_t baud, bool polling = false) { polling_ = polling; PER0.SAU0EN = 1; SPS0.PRS0 = 1; // 16MHz SMR00 = 0x20 | SMR00.MD.b(1); // 1 stop, 8 data SCR00 = 0x0004 | SCR00.TXE.b(1) | SCR00.RXE.b(1) | SCR00.SLC.b(1) | SCR00.DLS.b(3); SDR00H = 68; // 16MHz / 136 := 115200 (115942) SOL00 = 0; SO00 = 1; SOE00 = 1; PM1.B2 = 0; /// P12 output /// POM1.B2 = 1; /// open drain output P1.B2 = 1; /// "1" SS00 = 1; return true; } //-----------------------------------------------------------------// /*! @brief 出力バッファのサイズを返す @return バッファのサイズ */ //-----------------------------------------------------------------// uint16_t send_length() const { if(polling_) { return 0; } else { return send_.length(); } } //-----------------------------------------------------------------// /*! @brief 文字出力 @param[in] ch 文字コード */ //-----------------------------------------------------------------// void putch(char ch) { if(crlf_ && ch == '\n') { putch('\r'); } if(polling_) { while(SSR00.BFF() != 0) sleep_(); SDR00L = ch; } else { /// 7/8 を超えてた場合は、バッファが空になるまで待つ。 if(send_.length() >= (send_.size() * 7 / 8)) { while(send_.length() != 0) sleep_(); } send_.put(ch); /// SCIx::SCR.TEIE = 1; } } //-----------------------------------------------------------------// /*! @brief 文字列出力 @param[in] s 出力ストリング */ //-----------------------------------------------------------------// void puts(const char* s) { char ch; while((ch = *s++) != 0) { putch(ch); } } }; // recv_、send_ の実体を定義 template<uint16_t recv_size, uint16_t send_size> utils::fifo<recv_size> uart_io<recv_size, send_size>::recv_; template<uint16_t recv_size, uint16_t send_size> utils::fifo<send_size> uart_io<recv_size, send_size>::send_; } <commit_msg>uart_io send/recv polling<commit_after>#pragma once //=====================================================================// /*! @file @brief RL78/G13 グループ SAU/UART 制御 @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "G13/system.hpp" #include "G13/sau.hpp" #include "common/fifo.hpp" /// F_CLK はボーレートパラメーター計算で必要、設定が無いとエラーにします。 #ifndef F_CLK # error "uart_io.hpp requires F_CLK to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief UART 制御クラス @param[in] SAUtx シリアル・アレイ・ユニット送信・クラス @param[in] SAUrx シリアル・アレイ・ユニット受信・クラス @param[in] send+size 送信バッファサイズ @param[in] recv_size 受信バッファサイズ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> class uart_io { static SAUtx tx_; ///< 送信リソース static SAUrx rx_; ///< 受信リソース static utils::fifo<send_size> send_; static utils::fifo<recv_size> recv_; bool polling_ = false; bool crlf_ = true; // ※必要なら、実装する void sleep_() { asm("nop"); } public: //-----------------------------------------------------------------// /*! @brief ボーレートを設定して、UART を有効にする @param[in] baud ボーレート @param[in] polling ポーリングの場合「true」 @return エラーなら「false」 */ //-----------------------------------------------------------------// bool start(uint32_t baud, bool polling = false) { polling_ = polling; // ボーレートと分周比の計算 auto div = static_cast<uint32_t>(F_CLK) / baud; uint8_t master = 0; while(div > 256) { div /= 2; ++master; if(master >= 16) { /// ボーレート設定範囲外 return false; } } --div; div &= 0xfe; if(div <= 2) { /// ボーレート設定範囲外 return false; } // 対応するユニットを有効にする if(tx_.get_unit_no() == 0) { PER0.SAU0EN = 1; } else { PER0.SAU1EN = 1; } // チャネル0、1で共有の為、どちらか片方のみの設定 tx_.SPS = SAUtx::SPS.PRS0.b(master); // rx_.SPS = SAUrx::SPS.PRS0.b(master); tx_.SMR = 0x20 | SAUtx::SMR.MD.b(1) | SAUtx::SMR.MD0.b(1); rx_.SMR = 0x20 | SAUrx::SMR.STS.b(1) | SAUrx::SMR.MD.b(1); // 8 date, 1 stop, no-parity LSB-first // 送信設定 tx_.SCR = 0x0004 | SAUtx::SCR.TXE.b(1) | SAUtx::SCR.SLC.b(1) | SAUtx::SCR.DLS.b(3) | SAUtx::SCR.DIR.b(1); // 受信設定 rx_.SCR = 0x0004 | SAUrx::SCR.RXE.b(1) | SAUrx::SCR.SLC.b(1) | SAUrx::SCR.DLS.b(3) | SAUrx::SCR.DIR.b(1); // ボーレート・ジェネレーター設定 tx_.SDR = div << 8; rx_.SDR = div << 8; tx_.SOL = 0; // TxD tx_.SO = 1; // シリアル出力設定 tx_.SOE = 1; // シリアル出力許可(Txd) PM1.B1 = 1; /// P1-1 input (RxD) PM1.B2 = 0; /// P1-2 output (TxD) P1.B2 = 1; /// ポートレジスター (TxD) tx_.SS = 1; /// TxD enable rx_.SS = 1; /// RxD enable return true; } //-----------------------------------------------------------------// /*! @brief 送信バッファのサイズを返す @return バッファのサイズ */ //-----------------------------------------------------------------// uint16_t send_length() const { if(polling_) { return tx_.SSR.TSF(); } else { return send_.length(); } } //-----------------------------------------------------------------// /*! @brief 受信バッファのサイズを返す @n ※ポーリング時、データが無い:0、データがある:1 @return バッファのサイズ */ //-----------------------------------------------------------------// uint16_t recv_length() const { if(polling_) { return rx_.SSR.BFF(); } else { return recv_.length(); } } //-----------------------------------------------------------------// /*! @brief 文字出力 @param[in] ch 文字コード */ //-----------------------------------------------------------------// void putch(char ch) { if(crlf_ && ch == '\n') { putch('\r'); } if(polling_) { while(tx_.SSR.TSF() != 0) sleep_(); tx_.SDR_L = ch; } else { /// 7/8 を超えてた場合は、バッファが空になるまで待つ。 if(send_.length() >= (send_.size() * 7 / 8)) { while(send_.length() != 0) sleep_(); } send_.put(ch); /// SCIx::SCR.TEIE = 1; } } //-----------------------------------------------------------------// /*! @brief 文字入力 @return 文字コード */ //-----------------------------------------------------------------// char getch() { if(polling_) { while(rx_.SSR.BFF() == 0) sleep_(); return rx_.SDR_L(); } else { while(recv_.length() == 0) sleep_(); return recv_.get(); } } //-----------------------------------------------------------------// /*! @brief 文字列出力 @param[in] s 出力ストリング */ //-----------------------------------------------------------------// void puts(const char* s) { char ch; while((ch = *s) != 0) { putch(ch); ++s; } } }; // send_、recv_ の実体を定義 template<class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> utils::fifo<send_size> uart_io<SAUtx, SAUrx, send_size, recv_size>::send_; template<class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> utils::fifo<recv_size> uart_io<SAUtx, SAUrx, send_size, recv_size>::recv_; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkCell.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkCell.h" // Description: // Construct cell. vtkCell::vtkCell(): Points(VTK_CELL_SIZE), PointIds(VTK_CELL_SIZE) { this->Points.ReferenceCountingOff(); } // // Instantiate cell from outside // void vtkCell::Initialize(int npts, int *pts, vtkPoints *p) { this->PointIds.Reset(); for (int i=0; i<npts; i++) { this->PointIds.InsertId(i,pts[i]); this->Points.SetPoint(i,p->GetPoint(pts[i])); } } #define VTK_RIGHT 0 #define VTK_LEFT 1 #define VTK_MIDDLE 2 // Description: // Bounding box intersection modified from Graphics Gems Vol I. // Note: the intersection ray is assumed normalized, such that // valid intersections can only occur between [0,1]. Method returns non-zero // value if bounding box is hit. Origin[3] starts the ray, dir[3] is the // components of the ray in the x-y-z directions, coord[3] is the location // of hit, and t is the parametric coordinate along line. char vtkCell::HitBBox (float bounds[6], float origin[3], float dir[3], float coord[3], float& t) { char inside=1; char quadrant[3]; int i, whichPlane=0; float maxT[3], candidatePlane[3]; // // First find closest planes // for (i=0; i<3; i++) { if ( origin[i] < bounds[2*i] ) { quadrant[i] = VTK_LEFT; candidatePlane[i] = bounds[2*i]; inside = 0; } else if ( origin[i] > bounds[2*i+1] ) { quadrant[i] = VTK_RIGHT; candidatePlane[i] = bounds[2*i+1]; inside = 0; } else { quadrant[i] = VTK_MIDDLE; } } // // Check whether origin of ray is inside bbox // if (inside) { coord[0] = origin[0]; coord[1] = origin[1]; coord[2] = origin[2]; t = 0; return 1; } // // Calculate parametric distances to plane // for (i=0; i<3; i++) { if ( quadrant[i] != VTK_MIDDLE && dir[i] != 0.0 ) { maxT[i] = (candidatePlane[i]-origin[i]) / dir[i]; } else { maxT[i] = -1.0; } } // // Find the largest parametric value of intersection // for (i=0; i<3; i++) if ( maxT[whichPlane] < maxT[i] ) whichPlane = i; // // Check for valid intersection along line // if ( maxT[whichPlane] > 1.0 || maxT[whichPlane] < 0.0 ) return 0; else t = maxT[whichPlane]; // // Intersection point along line is okay. Check bbox. // for (i=0; i<3; i++) { if (whichPlane != i) { coord[i] = origin[i] + maxT[whichPlane]*dir[i]; if ( coord[i] < bounds[2*i] || coord[i] > bounds[2*i+1] ) return 0; } else { coord[i] = candidatePlane[i]; } } return 1; } // Description: // Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Return pointer // to array of six float values. float *vtkCell::GetBounds () { float *x; int i, j; static float bounds[6]; bounds[0] = bounds[2] = bounds[4] = VTK_LARGE_FLOAT; bounds[1] = bounds[3] = bounds[5] = -VTK_LARGE_FLOAT; for (i=0; i<this->Points.GetNumberOfPoints(); i++) { x = this->Points.GetPoint(i); for (j=0; j<3; j++) { if ( x[j] < bounds[2*j] ) bounds[2*j] = x[j]; if ( x[j] > bounds[2*j+1] ) bounds[2*j+1] = x[j]; } } return bounds; } // Description: // Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Copy result into // user provided array. void vtkCell::GetBounds(float bounds[6]) { float *b=this->GetBounds(); for (int i=0; i < 6; i++) bounds[i] = b[i]; } // Description: // Compute Length squared of cell (i.e., bounding box diagonal squared). float vtkCell::GetLength2 () { float diff, l=0.0; float *bounds; int i; bounds = this->GetBounds(); for (i=0; i<3; i++) { diff = bounds[2*i+1] - bounds[2*i]; l += diff * diff; } return l; } void vtkCell::PrintSelf(ostream& os, vtkIndent indent) { float *bounds; int i; vtkObject::PrintSelf(os,indent); os << indent << "Number Of Points: " << this->PointIds.GetNumberOfIds() << "\n"; bounds = this->GetBounds(); os << indent << "Bounds: \n"; os << indent << " Xmin,Xmax: (" << bounds[0] << ", " << bounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << bounds[2] << ", " << bounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << bounds[4] << ", " << bounds[5] << ")\n"; os << indent << " Point ids are: "; for (i=0; this->PointIds.GetNumberOfIds(); i++) { os << ", " << this->PointIds.GetId(i); if ( i && !(i % 12) ) os << "\n\t"; } os << indent << "\n"; } <commit_msg>bug fixed in Initialize<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkCell.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkCell.h" // Description: // Construct cell. vtkCell::vtkCell(): Points(VTK_CELL_SIZE), PointIds(VTK_CELL_SIZE) { this->Points.ReferenceCountingOff(); } // // Instantiate cell from outside // void vtkCell::Initialize(int npts, int *pts, vtkPoints *p) { this->PointIds.Reset(); this->Points.Reset(); for (int i=0; i<npts; i++) { this->PointIds.InsertId(i,pts[i]); this->Points.SetPoint(i,p->GetPoint(pts[i])); } } #define VTK_RIGHT 0 #define VTK_LEFT 1 #define VTK_MIDDLE 2 // Description: // Bounding box intersection modified from Graphics Gems Vol I. // Note: the intersection ray is assumed normalized, such that // valid intersections can only occur between [0,1]. Method returns non-zero // value if bounding box is hit. Origin[3] starts the ray, dir[3] is the // components of the ray in the x-y-z directions, coord[3] is the location // of hit, and t is the parametric coordinate along line. char vtkCell::HitBBox (float bounds[6], float origin[3], float dir[3], float coord[3], float& t) { char inside=1; char quadrant[3]; int i, whichPlane=0; float maxT[3], candidatePlane[3]; // // First find closest planes // for (i=0; i<3; i++) { if ( origin[i] < bounds[2*i] ) { quadrant[i] = VTK_LEFT; candidatePlane[i] = bounds[2*i]; inside = 0; } else if ( origin[i] > bounds[2*i+1] ) { quadrant[i] = VTK_RIGHT; candidatePlane[i] = bounds[2*i+1]; inside = 0; } else { quadrant[i] = VTK_MIDDLE; } } // // Check whether origin of ray is inside bbox // if (inside) { coord[0] = origin[0]; coord[1] = origin[1]; coord[2] = origin[2]; t = 0; return 1; } // // Calculate parametric distances to plane // for (i=0; i<3; i++) { if ( quadrant[i] != VTK_MIDDLE && dir[i] != 0.0 ) { maxT[i] = (candidatePlane[i]-origin[i]) / dir[i]; } else { maxT[i] = -1.0; } } // // Find the largest parametric value of intersection // for (i=0; i<3; i++) if ( maxT[whichPlane] < maxT[i] ) whichPlane = i; // // Check for valid intersection along line // if ( maxT[whichPlane] > 1.0 || maxT[whichPlane] < 0.0 ) return 0; else t = maxT[whichPlane]; // // Intersection point along line is okay. Check bbox. // for (i=0; i<3; i++) { if (whichPlane != i) { coord[i] = origin[i] + maxT[whichPlane]*dir[i]; if ( coord[i] < bounds[2*i] || coord[i] > bounds[2*i+1] ) return 0; } else { coord[i] = candidatePlane[i]; } } return 1; } // Description: // Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Return pointer // to array of six float values. float *vtkCell::GetBounds () { float *x; int i, j; static float bounds[6]; bounds[0] = bounds[2] = bounds[4] = VTK_LARGE_FLOAT; bounds[1] = bounds[3] = bounds[5] = -VTK_LARGE_FLOAT; for (i=0; i<this->Points.GetNumberOfPoints(); i++) { x = this->Points.GetPoint(i); for (j=0; j<3; j++) { if ( x[j] < bounds[2*j] ) bounds[2*j] = x[j]; if ( x[j] > bounds[2*j+1] ) bounds[2*j+1] = x[j]; } } return bounds; } // Description: // Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Copy result into // user provided array. void vtkCell::GetBounds(float bounds[6]) { float *b=this->GetBounds(); for (int i=0; i < 6; i++) bounds[i] = b[i]; } // Description: // Compute Length squared of cell (i.e., bounding box diagonal squared). float vtkCell::GetLength2 () { float diff, l=0.0; float *bounds; int i; bounds = this->GetBounds(); for (i=0; i<3; i++) { diff = bounds[2*i+1] - bounds[2*i]; l += diff * diff; } return l; } void vtkCell::PrintSelf(ostream& os, vtkIndent indent) { float *bounds; int i; vtkObject::PrintSelf(os,indent); os << indent << "Number Of Points: " << this->PointIds.GetNumberOfIds() << "\n"; bounds = this->GetBounds(); os << indent << "Bounds: \n"; os << indent << " Xmin,Xmax: (" << bounds[0] << ", " << bounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << bounds[2] << ", " << bounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << bounds[4] << ", " << bounds[5] << ")\n"; os << indent << " Point ids are: "; for (i=0; this->PointIds.GetNumberOfIds(); i++) { os << ", " << this->PointIds.GetId(i); if ( i && !(i % 12) ) os << "\n\t"; } os << indent << "\n"; } <|endoftext|>
<commit_before><commit_msg>convert this debugging thing over too<commit_after><|endoftext|>
<commit_before> /************************************************************************* * * $RCSfile: accpage.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2003-04-24 16:12:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _RTL_UUID_H_ #include <rtl/uuid.h> #endif #ifndef _SV_WINDOW_HXX #include <vcl/window.hxx> #endif #ifndef _SV_SVAPP_HXX //autogen #include <vcl/svapp.hxx> #endif #ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_ #include <unotools/accessiblestatesethelper.hxx> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_ #include <com/sun/star/accessibility/AccessibleStateType.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_ #include <com/sun/star/accessibility/AccessibleRole.hpp> #endif #ifndef _ACCPAGE_HXX #include "accpage.hxx" #endif #ifndef _ACCESS_HRC #include "access.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _PAGEFRM_HXX #include <pagefrm.hxx> #endif using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::RuntimeException; using ::com::sun::star::uno::Sequence; using namespace ::com::sun::star::accessibility; using ::rtl::OUString; using ::com::sun::star::accessibility::XAccessibleContext; const sal_Char sServiceName[] = "com.sun.star.text.AccessiblePageView"; const sal_Char sImplementationName[] = "com.sun.star.comp.Writer.SwAccessiblePageView"; sal_Bool SwAccessiblePage::IsSelected() { return GetMap()->IsPageSelected( static_cast < const SwPageFrm * >( GetFrm() ) ); } void SwAccessiblePage::GetStates( ::utl::AccessibleStateSetHelper& rStateSet ) { SwAccessibleContext::GetStates( rStateSet ); // FOCUSABLE rStateSet.AddState( AccessibleStateType::FOCUSABLE ); // FOCUSED if( IsSelected() ) { ASSERT( bIsSelected, "bSelected out of sync" ); ::vos::ORef < SwAccessibleContext > xThis( this ); GetMap()->SetCursorContext( xThis ); Window *pWin = GetWindow(); if( pWin && pWin->HasFocus() ) rStateSet.AddState( AccessibleStateType::FOCUSED ); } } void SwAccessiblePage::_InvalidateCursorPos() { sal_Bool bNewSelected = IsSelected(); sal_Bool bOldSelected; { vos::OGuard aGuard( aMutex ); bOldSelected = bIsSelected; bIsSelected = bNewSelected; } if( bNewSelected ) { // remember that object as the one that has the caret. This is // neccessary to notify that object if the cursor leaves it. ::vos::ORef < SwAccessibleContext > xThis( this ); GetMap()->SetCursorContext( xThis ); } if( bOldSelected != bNewSelected ) { Window *pWin = GetWindow(); if( pWin && pWin->HasFocus() ) FireStateChangedEvent( AccessibleStateType::FOCUSED, bNewSelected ); } } void SwAccessiblePage::_InvalidateFocus() { Window *pWin = GetWindow(); if( pWin ) { sal_Bool bSelected; { vos::OGuard aGuard( aMutex ); bSelected = bIsSelected; } ASSERT( bSelected, "focus object should be selected" ); FireStateChangedEvent( AccessibleStateType::FOCUSED, pWin->HasFocus() && bSelected ); } } SwAccessiblePage::SwAccessiblePage( SwAccessibleMap* pMap, const SwPageFrm *pFrame ) : SwAccessibleContext( pMap, AccessibleRole::PANEL, pFrame ) { DBG_ASSERT( pFrame != NULL, "need frame" ); DBG_ASSERT( pMap != NULL, "need map" ); vos::OGuard aGuard(Application::GetSolarMutex()); OUString sPage = OUString::valueOf( static_cast<sal_Int32>( static_cast<const SwPageFrm*>( GetFrm() )->GetPhyPageNum() ) ); SetName( GetResource( STR_ACCESS_PAGE_NAME, &sPage ) ); } SwAccessiblePage::SwAccessiblePage( SwAccessibleMap* pMap, const SwFrm *pFrame ) : SwAccessibleContext( pMap, AccessibleRole::PANEL, pFrame ) { DBG_ASSERT( pFrame != NULL, "need frame" ); DBG_ASSERT( pMap != NULL, "need map" ); DBG_ASSERT( pFrame->IsPageFrm(), "need page frame" ); vos::OGuard aGuard(Application::GetSolarMutex()); OUString sPage = OUString::valueOf( static_cast<sal_Int32>( static_cast<const SwPageFrm*>( GetFrm() )->GetPhyPageNum() ) ); SetName( GetResource( STR_ACCESS_PAGE_NAME, &sPage ) ); } SwAccessiblePage::~SwAccessiblePage() { } sal_Bool SwAccessiblePage::HasCursor() { vos::OGuard aGuard( aMutex ); return bIsSelected; } OUString SwAccessiblePage::getImplementationName( ) throw( RuntimeException ) { return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationName)); } sal_Bool SwAccessiblePage::supportsService( const OUString& rServiceName) throw( RuntimeException ) { return rServiceName.equalsAsciiL( sServiceName, sizeof(sServiceName)-1 ) || rServiceName.equalsAsciiL( sAccessibleServiceName, sizeof(sAccessibleServiceName)-1 ); } Sequence<OUString> SwAccessiblePage::getSupportedServiceNames( ) throw( RuntimeException ) { Sequence< OUString > aRet(2); OUString* pArray = aRet.getArray(); pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceName) ); pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) ); return aRet; } Sequence< sal_Int8 > SAL_CALL SwAccessiblePage::getImplementationId() throw(RuntimeException) { vos::OGuard aGuard(Application::GetSolarMutex()); static Sequence< sal_Int8 > aId( 16 ); static sal_Bool bInit = sal_False; if(!bInit) { rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True ); bInit = sal_True; } return aId; } OUString SwAccessiblePage::getAccessibleDescription( ) throw( RuntimeException ) { CHECK_FOR_DEFUNC( XAccessibleContext ); OUString sArg( GetFormattedPageNumber() ); return GetResource( STR_ACCESS_PAGE_DESC, &sArg ); } <commit_msg>INTEGRATION: CWS tune05 (1.9.564); FILE MERGED 2004/07/19 09:43:46 cmc 1.9.564.1: #i30554# unused dup ctor<commit_after> /************************************************************************* * * $RCSfile: accpage.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2004-08-12 12:10:55 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _RTL_UUID_H_ #include <rtl/uuid.h> #endif #ifndef _SV_WINDOW_HXX #include <vcl/window.hxx> #endif #ifndef _SV_SVAPP_HXX //autogen #include <vcl/svapp.hxx> #endif #ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_ #include <unotools/accessiblestatesethelper.hxx> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_ #include <com/sun/star/accessibility/AccessibleStateType.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_ #include <com/sun/star/accessibility/AccessibleRole.hpp> #endif #ifndef _ACCPAGE_HXX #include "accpage.hxx" #endif #ifndef _ACCESS_HRC #include "access.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _PAGEFRM_HXX #include <pagefrm.hxx> #endif using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::RuntimeException; using ::com::sun::star::uno::Sequence; using namespace ::com::sun::star::accessibility; using ::rtl::OUString; using ::com::sun::star::accessibility::XAccessibleContext; const sal_Char sServiceName[] = "com.sun.star.text.AccessiblePageView"; const sal_Char sImplementationName[] = "com.sun.star.comp.Writer.SwAccessiblePageView"; sal_Bool SwAccessiblePage::IsSelected() { return GetMap()->IsPageSelected( static_cast < const SwPageFrm * >( GetFrm() ) ); } void SwAccessiblePage::GetStates( ::utl::AccessibleStateSetHelper& rStateSet ) { SwAccessibleContext::GetStates( rStateSet ); // FOCUSABLE rStateSet.AddState( AccessibleStateType::FOCUSABLE ); // FOCUSED if( IsSelected() ) { ASSERT( bIsSelected, "bSelected out of sync" ); ::vos::ORef < SwAccessibleContext > xThis( this ); GetMap()->SetCursorContext( xThis ); Window *pWin = GetWindow(); if( pWin && pWin->HasFocus() ) rStateSet.AddState( AccessibleStateType::FOCUSED ); } } void SwAccessiblePage::_InvalidateCursorPos() { sal_Bool bNewSelected = IsSelected(); sal_Bool bOldSelected; { vos::OGuard aGuard( aMutex ); bOldSelected = bIsSelected; bIsSelected = bNewSelected; } if( bNewSelected ) { // remember that object as the one that has the caret. This is // neccessary to notify that object if the cursor leaves it. ::vos::ORef < SwAccessibleContext > xThis( this ); GetMap()->SetCursorContext( xThis ); } if( bOldSelected != bNewSelected ) { Window *pWin = GetWindow(); if( pWin && pWin->HasFocus() ) FireStateChangedEvent( AccessibleStateType::FOCUSED, bNewSelected ); } } void SwAccessiblePage::_InvalidateFocus() { Window *pWin = GetWindow(); if( pWin ) { sal_Bool bSelected; { vos::OGuard aGuard( aMutex ); bSelected = bIsSelected; } ASSERT( bSelected, "focus object should be selected" ); FireStateChangedEvent( AccessibleStateType::FOCUSED, pWin->HasFocus() && bSelected ); } } SwAccessiblePage::SwAccessiblePage( SwAccessibleMap* pMap, const SwFrm *pFrame ) : SwAccessibleContext( pMap, AccessibleRole::PANEL, pFrame ) { DBG_ASSERT( pFrame != NULL, "need frame" ); DBG_ASSERT( pMap != NULL, "need map" ); DBG_ASSERT( pFrame->IsPageFrm(), "need page frame" ); vos::OGuard aGuard(Application::GetSolarMutex()); OUString sPage = OUString::valueOf( static_cast<sal_Int32>( static_cast<const SwPageFrm*>( GetFrm() )->GetPhyPageNum() ) ); SetName( GetResource( STR_ACCESS_PAGE_NAME, &sPage ) ); } SwAccessiblePage::~SwAccessiblePage() { } sal_Bool SwAccessiblePage::HasCursor() { vos::OGuard aGuard( aMutex ); return bIsSelected; } OUString SwAccessiblePage::getImplementationName( ) throw( RuntimeException ) { return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationName)); } sal_Bool SwAccessiblePage::supportsService( const OUString& rServiceName) throw( RuntimeException ) { return rServiceName.equalsAsciiL( sServiceName, sizeof(sServiceName)-1 ) || rServiceName.equalsAsciiL( sAccessibleServiceName, sizeof(sAccessibleServiceName)-1 ); } Sequence<OUString> SwAccessiblePage::getSupportedServiceNames( ) throw( RuntimeException ) { Sequence< OUString > aRet(2); OUString* pArray = aRet.getArray(); pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceName) ); pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) ); return aRet; } Sequence< sal_Int8 > SAL_CALL SwAccessiblePage::getImplementationId() throw(RuntimeException) { vos::OGuard aGuard(Application::GetSolarMutex()); static Sequence< sal_Int8 > aId( 16 ); static sal_Bool bInit = sal_False; if(!bInit) { rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True ); bInit = sal_True; } return aId; } OUString SwAccessiblePage::getAccessibleDescription( ) throw( RuntimeException ) { CHECK_FOR_DEFUNC( XAccessibleContext ); OUString sArg( GetFormattedPageNumber() ); return GetResource( STR_ACCESS_PAGE_DESC, &sArg ); } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/InvocationOptions.h" #include "cling/Interpreter/ClingOptions.h" #include "clang/Driver/Options.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" #include "llvm/Option/OptTable.h" #include "llvm/Support/raw_ostream.h" #include <memory> using namespace clang; using namespace cling::driver::clingoptions; using namespace llvm; using namespace llvm::opt; namespace { #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR) #include "cling/Interpreter/ClingOptions.inc" #undef OPTION #undef PREFIX static const OptTable::Info ClingInfoTable[] = { #define PREFIX(NAME, VALUE) #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR) \ { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \ FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS }, #include "cling/Interpreter/ClingOptions.inc" #undef OPTION #undef PREFIX }; class ClingOptTable : public OptTable { public: ClingOptTable() : OptTable(ClingInfoTable, sizeof(ClingInfoTable) / sizeof(ClingInfoTable[0])) {} }; static OptTable* CreateClingOptTable() { return new ClingOptTable(); } static void ParseStartupOpts(cling::InvocationOptions& Opts, InputArgList& Args /* , Diags */) { Opts.ErrorOut = Args.hasArg(OPT__errorout); Opts.NoLogo = Args.hasArg(OPT__nologo); Opts.ShowVersion = Args.hasArg(OPT_version); Opts.Verbose = Args.hasArg(OPT_v); Opts.Help = Args.hasArg(OPT_help); if (Args.hasArg(OPT__metastr, OPT__metastr_EQ)) { Arg* MetaStringArg = Args.getLastArg(OPT__metastr, OPT__metastr_EQ); Opts.MetaString = MetaStringArg->getValue(); if (Opts.MetaString.length() == 0) { llvm::errs() << "ERROR: meta string must be non-empty! Defaulting to '.'.\n"; Opts.MetaString = "."; } } } static void ParseLinkerOpts(cling::InvocationOptions& Opts, InputArgList& Args /* , Diags */) { Opts.LibsToLoad = Args.getAllArgValues(OPT_l); std::vector<std::string> LibPaths = Args.getAllArgValues(OPT_L); for (size_t i = 0; i < LibPaths.size(); ++i) Opts.LibSearchPath.push_back(LibPaths[i]); } static void ParseInputs(cling::InvocationOptions& Opts, int argc, const char* const argv[]) { if (argc <= 1) { return; } unsigned MissingArgIndex, MissingArgCount; std::unique_ptr<OptTable> OptsC1(clang::driver::createDriverOptTable()); Opts.Inputs.clear(); // see Driver::getIncludeExcludeOptionFlagMasks() unsigned ExcludeOptionFlagMasks = clang::driver::options::NoDriverOption | clang::driver::options::CLOption; ArrayRef<const char *> ArgStrings(argv+1, argv + argc); InputArgList Args( OptsC1->ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount, 0, ExcludeOptionFlagMasks)); for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { if ( (*it)->getOption().getKind() == Option::InputClass ) { Opts.Inputs.push_back(std::string( (*it)->getValue() ) ); } } } } cling::InvocationOptions cling::InvocationOptions::CreateFromArgs(int argc, const char* const argv[], std::vector<unsigned>& leftoverArgs /* , Diagnostic &Diags */) { InvocationOptions ClingOpts; std::unique_ptr<OptTable> Opts(CreateClingOptTable()); unsigned MissingArgIndex, MissingArgCount; // see Driver::getIncludeExcludeOptionFlagMasks() unsigned ExcludeOptionFlagMasks = clang::driver::options::NoDriverOption | clang::driver::options::CLOption; ArrayRef<const char *> ArgStrings(argv, argv + argc); InputArgList Args( Opts->ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount, 0, ExcludeOptionFlagMasks)); //if (MissingArgCount) // Diags.Report(diag::err_drv_missing_argument) // << Args->getArgString(MissingArgIndex) << MissingArgCount; // Forward unknown arguments. for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { if ((*it)->getOption().getKind() == Option::UnknownClass ||(*it)->getOption().getKind() == Option::InputClass) { leftoverArgs.push_back((*it)->getIndex()); } } ParseStartupOpts(ClingOpts, Args /* , Diags */); ParseLinkerOpts(ClingOpts, Args /* , Diags */); ParseInputs(ClingOpts, argc, argv); return ClingOpts; } void cling::InvocationOptions::PrintHelp() { std::unique_ptr<OptTable> Opts(CreateClingOptTable()); Opts->PrintHelp(llvm::outs(), "cling", "cling: LLVM/clang C++ Interpreter: http://cern.ch/cling"); llvm::outs() << "\n\n"; std::unique_ptr<OptTable> OptsC1(clang::driver::createDriverOptTable()); OptsC1->PrintHelp(llvm::outs(), "clang -cc1", "LLVM 'Clang' Compiler: http://clang.llvm.org"); } <commit_msg>llvm-upgrade.<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/InvocationOptions.h" #include "cling/Interpreter/ClingOptions.h" #include "clang/Driver/Options.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" #include "llvm/Option/OptTable.h" #include "llvm/Support/raw_ostream.h" #include <memory> using namespace clang; using namespace cling::driver::clingoptions; using namespace llvm; using namespace llvm::opt; namespace { #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR) #include "cling/Interpreter/ClingOptions.inc" #undef OPTION #undef PREFIX static const OptTable::Info ClingInfoTable[] = { #define PREFIX(NAME, VALUE) #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR) \ { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \ FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS }, #include "cling/Interpreter/ClingOptions.inc" #undef OPTION #undef PREFIX }; class ClingOptTable : public OptTable { public: ClingOptTable() : OptTable(ClingInfoTable) {} }; static OptTable* CreateClingOptTable() { return new ClingOptTable(); } static void ParseStartupOpts(cling::InvocationOptions& Opts, InputArgList& Args /* , Diags */) { Opts.ErrorOut = Args.hasArg(OPT__errorout); Opts.NoLogo = Args.hasArg(OPT__nologo); Opts.ShowVersion = Args.hasArg(OPT_version); Opts.Verbose = Args.hasArg(OPT_v); Opts.Help = Args.hasArg(OPT_help); if (Args.hasArg(OPT__metastr, OPT__metastr_EQ)) { Arg* MetaStringArg = Args.getLastArg(OPT__metastr, OPT__metastr_EQ); Opts.MetaString = MetaStringArg->getValue(); if (Opts.MetaString.length() == 0) { llvm::errs() << "ERROR: meta string must be non-empty! Defaulting to '.'.\n"; Opts.MetaString = "."; } } } static void ParseLinkerOpts(cling::InvocationOptions& Opts, InputArgList& Args /* , Diags */) { Opts.LibsToLoad = Args.getAllArgValues(OPT_l); std::vector<std::string> LibPaths = Args.getAllArgValues(OPT_L); for (size_t i = 0; i < LibPaths.size(); ++i) Opts.LibSearchPath.push_back(LibPaths[i]); } static void ParseInputs(cling::InvocationOptions& Opts, int argc, const char* const argv[]) { if (argc <= 1) { return; } unsigned MissingArgIndex, MissingArgCount; std::unique_ptr<OptTable> OptsC1(clang::driver::createDriverOptTable()); Opts.Inputs.clear(); // see Driver::getIncludeExcludeOptionFlagMasks() unsigned ExcludeOptionFlagMasks = clang::driver::options::NoDriverOption | clang::driver::options::CLOption; ArrayRef<const char *> ArgStrings(argv+1, argv + argc); InputArgList Args( OptsC1->ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount, 0, ExcludeOptionFlagMasks)); for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { if ( (*it)->getOption().getKind() == Option::InputClass ) { Opts.Inputs.push_back(std::string( (*it)->getValue() ) ); } } } } cling::InvocationOptions cling::InvocationOptions::CreateFromArgs(int argc, const char* const argv[], std::vector<unsigned>& leftoverArgs /* , Diagnostic &Diags */) { InvocationOptions ClingOpts; std::unique_ptr<OptTable> Opts(CreateClingOptTable()); unsigned MissingArgIndex, MissingArgCount; // see Driver::getIncludeExcludeOptionFlagMasks() unsigned ExcludeOptionFlagMasks = clang::driver::options::NoDriverOption | clang::driver::options::CLOption; ArrayRef<const char *> ArgStrings(argv, argv + argc); InputArgList Args( Opts->ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount, 0, ExcludeOptionFlagMasks)); //if (MissingArgCount) // Diags.Report(diag::err_drv_missing_argument) // << Args->getArgString(MissingArgIndex) << MissingArgCount; // Forward unknown arguments. for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { if ((*it)->getOption().getKind() == Option::UnknownClass ||(*it)->getOption().getKind() == Option::InputClass) { leftoverArgs.push_back((*it)->getIndex()); } } ParseStartupOpts(ClingOpts, Args /* , Diags */); ParseLinkerOpts(ClingOpts, Args /* , Diags */); ParseInputs(ClingOpts, argc, argv); return ClingOpts; } void cling::InvocationOptions::PrintHelp() { std::unique_ptr<OptTable> Opts(CreateClingOptTable()); Opts->PrintHelp(llvm::outs(), "cling", "cling: LLVM/clang C++ Interpreter: http://cern.ch/cling"); llvm::outs() << "\n\n"; std::unique_ptr<OptTable> OptsC1(clang::driver::createDriverOptTable()); OptsC1->PrintHelp(llvm::outs(), "clang -cc1", "LLVM 'Clang' Compiler: http://clang.llvm.org"); } <|endoftext|>
<commit_before><commit_msg>sal_uInt16 to (const) short<commit_after><|endoftext|>
<commit_before><commit_msg>Fix -fsanitize=signed-integer-overflow (when long int is 32-bit)<commit_after><|endoftext|>
<commit_before><commit_msg>sal_uInt16 to more proper types<commit_after><|endoftext|>
<commit_before>#pragma once #include <vector> #include <thread> #include <cmath> #include <iostream> #include <cstdlib> #include <Discreture/TimeHelpers.hpp> namespace dscr { template <class RAIter> std::vector<RAIter> divide_work(RAIter first, RAIter last, size_t num_processors) { auto n = std::distance(first, last); size_t block_size = n/num_processors; std::vector<RAIter> result; result.reserve(num_processors+1); for (size_t i = 0; i < num_processors; ++i) { result.emplace_back(first); std::advance(first,block_size); } result.emplace_back(last); return result; } template <class Container> auto divide_work(const Container& C, size_t num_processors) -> std::vector<typename Container::iterator> { return divide_work(C.begin(), C.end(), num_processors); } template <class RAIter, class Function> void parallel_for_each(RAIter first, RAIter last, Function f, size_t num_processors) { using namespace std; Chronometer C; auto work = divide_work(first,last,num_processors); std::vector<std::thread> threads; threads.reserve(num_processors); for (size_t i = 0; i < num_processors; ++i) { threads.emplace_back(std::thread([&work, &f, i]() { auto local_first = work[i]; auto local_last = work[i+1]; for ( ; local_first != local_last; ++local_first) { f(*local_first); } })); } for (auto& t : threads) { t.join(); } } template <class Container, class Function> void parallel_for_each(Container& C, Function f, size_t num_processors) { parallel_for_each(C.begin(), C.end(), f, num_processors); } } // namespace dscr <commit_msg>Fixed stupid include bug<commit_after>#pragma once #include <vector> #include <thread> #include <cmath> #include <iostream> #include <cstdlib> #include "TimeHelpers.hpp" namespace dscr { template <class RAIter> std::vector<RAIter> divide_work(RAIter first, RAIter last, size_t num_processors) { auto n = std::distance(first, last); size_t block_size = n/num_processors; std::vector<RAIter> result; result.reserve(num_processors+1); for (size_t i = 0; i < num_processors; ++i) { result.emplace_back(first); std::advance(first,block_size); } result.emplace_back(last); return result; } template <class Container> auto divide_work(const Container& C, size_t num_processors) -> std::vector<typename Container::iterator> { return divide_work(C.begin(), C.end(), num_processors); } template <class RAIter, class Function> void parallel_for_each(RAIter first, RAIter last, Function f, size_t num_processors) { using namespace std; Chronometer C; auto work = divide_work(first,last,num_processors); std::vector<std::thread> threads; threads.reserve(num_processors); for (size_t i = 0; i < num_processors; ++i) { threads.emplace_back(std::thread([&work, &f, i]() { auto local_first = work[i]; auto local_last = work[i+1]; for ( ; local_first != local_last; ++local_first) { f(*local_first); } })); } for (auto& t : threads) { t.join(); } } template <class Container, class Function> void parallel_for_each(Container& C, Function f, size_t num_processors) { parallel_for_each(C.begin(), C.end(), f, num_processors); } } // namespace dscr <|endoftext|>
<commit_before>// Copyright 2014 BVLC and contributors. #ifndef CAFFE_NEURON_LAYERS_HPP_ #define CAFFE_NEURON_LAYERS_HPP_ #include <string> #include <utility> #include <vector> #include "leveldb/db.h" #include "pthread.h" #include "boost/scoped_ptr.hpp" #include "hdf5.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #define HDF5_DATA_DATASET_NAME "data" #define HDF5_DATA_LABEL_NAME "label" namespace caffe { /* NeuronLayer An interface for layers that take one blob as input (x), and produce one blob as output (y). */ template <typename Dtype> class NeuronLayer : public Layer<Dtype> { public: explicit NeuronLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); }; /* BNLLLayer y = x + log(1 + exp(-x)) if x > 0 y = log(1 + exp(x)) if x <= 0 y' = exp(x) / (exp(x) + 1) */ template <typename Dtype> class BNLLLayer : public NeuronLayer<Dtype> { public: explicit BNLLLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); }; /* DropoutLayer During training only, sets some portion of x to 0, adjusting the vector magnitude accordingly. mask = bernoulli(1 - threshold) scale = 1 / (1 - threshold) y = x * mask * scale y' = mask * scale */ template <typename Dtype> class DropoutLayer : public NeuronLayer<Dtype> { public: explicit DropoutLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); shared_ptr<Blob<unsigned int> > rand_vec_; Dtype threshold_; Dtype scale_; unsigned int uint_thres_; }; /* PowerLayer y = (shift + scale * x) ^ power y' = scale * power * (shift + scale * x) ^ (power - 1) = scale * power * y / (shift + scale * x) */ template <typename Dtype> class PowerLayer : public NeuronLayer<Dtype> { public: explicit PowerLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); Dtype power_; Dtype scale_; Dtype shift_; Dtype diff_scale_; }; /* ReLULayer Rectified Linear Unit non-linearity. The simple max is fast to compute, and the function does not saturate. y = max(0, x). y' = 0 if x < 0 y' = 1 if x > 0 */ template <typename Dtype> class ReLULayer : public NeuronLayer<Dtype> { public: explicit ReLULayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); }; /* SigmoidLayer Sigmoid function non-linearity, a classic choice in neural networks. Note that the gradient vanishes as the values move away from 0. The ReLULayer is often a better choice for this reason. y = 1. / (1 + exp(-x)) y ' = exp(x) / (1 + exp(x))^2 or y' = y * (1 - y) */ template <typename Dtype> class SigmoidLayer : public NeuronLayer<Dtype> { public: explicit SigmoidLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); }; /* TanHLayer Hyperbolic tangent non-linearity, popular in auto-encoders. y = 1. * (exp(2x) - 1) / (exp(2x) + 1) y' = 1 - ( (exp(2x) - 1) / (exp(2x) + 1) ) ^ 2 */ template <typename Dtype> class TanHLayer : public NeuronLayer<Dtype> { public: explicit TanHLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); }; /* ThresholdLayer Outputs 1 if value in input is above threshold, 0 otherwise. The defult threshold = 0, which means positive values would become 1 and negative or 0, would become 0 y = 1 if x > threshold y = 0 if x <= threshold y' = don't differenciable */ template <typename Dtype> class ThresholdLayer : public NeuronLayer<Dtype> { public: explicit DropoutLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { NOT_IMPLEMENTED; } Dtype threshold_; }; } // namespace caffe #endif // CAFFE_NEURON_LAYERS_HPP_ <commit_msg>Fixed typo in Threshold Layer definition<commit_after>// Copyright 2014 BVLC and contributors. #ifndef CAFFE_NEURON_LAYERS_HPP_ #define CAFFE_NEURON_LAYERS_HPP_ #include <string> #include <utility> #include <vector> #include "leveldb/db.h" #include "pthread.h" #include "boost/scoped_ptr.hpp" #include "hdf5.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #define HDF5_DATA_DATASET_NAME "data" #define HDF5_DATA_LABEL_NAME "label" namespace caffe { /* NeuronLayer An interface for layers that take one blob as input (x), and produce one blob as output (y). */ template <typename Dtype> class NeuronLayer : public Layer<Dtype> { public: explicit NeuronLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); }; /* BNLLLayer y = x + log(1 + exp(-x)) if x > 0 y = log(1 + exp(x)) if x <= 0 y' = exp(x) / (exp(x) + 1) */ template <typename Dtype> class BNLLLayer : public NeuronLayer<Dtype> { public: explicit BNLLLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); }; /* DropoutLayer During training only, sets some portion of x to 0, adjusting the vector magnitude accordingly. mask = bernoulli(1 - threshold) scale = 1 / (1 - threshold) y = x * mask * scale y' = mask * scale */ template <typename Dtype> class DropoutLayer : public NeuronLayer<Dtype> { public: explicit DropoutLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); shared_ptr<Blob<unsigned int> > rand_vec_; Dtype threshold_; Dtype scale_; unsigned int uint_thres_; }; /* PowerLayer y = (shift + scale * x) ^ power y' = scale * power * (shift + scale * x) ^ (power - 1) = scale * power * y / (shift + scale * x) */ template <typename Dtype> class PowerLayer : public NeuronLayer<Dtype> { public: explicit PowerLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); Dtype power_; Dtype scale_; Dtype shift_; Dtype diff_scale_; }; /* ReLULayer Rectified Linear Unit non-linearity. The simple max is fast to compute, and the function does not saturate. y = max(0, x). y' = 0 if x < 0 y' = 1 if x > 0 */ template <typename Dtype> class ReLULayer : public NeuronLayer<Dtype> { public: explicit ReLULayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); }; /* SigmoidLayer Sigmoid function non-linearity, a classic choice in neural networks. Note that the gradient vanishes as the values move away from 0. The ReLULayer is often a better choice for this reason. y = 1. / (1 + exp(-x)) y ' = exp(x) / (1 + exp(x))^2 or y' = y * (1 - y) */ template <typename Dtype> class SigmoidLayer : public NeuronLayer<Dtype> { public: explicit SigmoidLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); }; /* TanHLayer Hyperbolic tangent non-linearity, popular in auto-encoders. y = 1. * (exp(2x) - 1) / (exp(2x) + 1) y' = 1 - ( (exp(2x) - 1) / (exp(2x) + 1) ) ^ 2 */ template <typename Dtype> class TanHLayer : public NeuronLayer<Dtype> { public: explicit TanHLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom); }; /* ThresholdLayer Outputs 1 if value in input is above threshold, 0 otherwise. The defult threshold = 0, which means positive values would become 1 and negative or 0, would become 0 y = 1 if x > threshold y = 0 if x <= threshold y' = don't differenciable */ template <typename Dtype> class ThresholdLayer : public NeuronLayer<Dtype> { public: explicit ThresholdLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); protected: virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { NOT_IMPLEMENTED; } Dtype threshold_; }; } // namespace caffe #endif // CAFFE_NEURON_LAYERS_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextHeaderFooterContext.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2006-09-17 11:13:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_ #include <com/sun/star/text/XText.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XRELATIVETEXTCONTENTREMOVE_HPP_ #include <com/sun/star/text/XRelativeTextContentRemove.hpp> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_TEXTHEADERFOOTERCONTEXT_HXX_ #include "XMLTextHeaderFooterContext.hxx" #endif #ifndef _XMLOFF_TEXTTABLECONTEXT_HXX_ #include "XMLTextTableContext.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; //using namespace ::com::sun::star::style; using namespace ::com::sun::star::text; using namespace ::com::sun::star::beans; //using namespace ::com::sun::star::container; //using namespace ::com::sun::star::lang; //using namespace ::com::sun::star::text; TYPEINIT1( XMLTextHeaderFooterContext, SvXMLImportContext ); XMLTextHeaderFooterContext::XMLTextHeaderFooterContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const uno::Reference< xml::sax::XAttributeList > &, const Reference < XPropertySet > & rPageStylePropSet, sal_Bool bFooter, sal_Bool bLft ) : SvXMLImportContext( rImport, nPrfx, rLName ), xPropSet( rPageStylePropSet ), sOn( OUString::createFromAscii( bFooter ? "FooterIsOn" : "HeaderIsOn" ) ), sShareContent( OUString::createFromAscii( bFooter ? "FooterIsShared" : "HeaderIsShared" ) ), sText( OUString::createFromAscii( bFooter ? "FooterText" : "HeaderText" ) ), sTextLeft( OUString::createFromAscii( bFooter ? "FooterTextLeft" : "HeaderTextLeft" ) ), bInsertContent( sal_True ), bLeft( bLft ) { if( bLeft ) { Any aAny; aAny = xPropSet->getPropertyValue( sOn ); sal_Bool bOn = *(sal_Bool *)aAny.getValue(); if( bOn ) { aAny = xPropSet->getPropertyValue( sShareContent ); sal_Bool bShared = *(sal_Bool *)aAny.getValue(); if( bShared ) { // Don't share headers any longer bShared = sal_False; aAny.setValue( &bShared, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sShareContent, aAny ); } } else { // If headers or footers are switched off, no content must be // inserted. bInsertContent = sal_False; } } } XMLTextHeaderFooterContext::~XMLTextHeaderFooterContext() { } SvXMLImportContext *XMLTextHeaderFooterContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const uno::Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if( bInsertContent ) { if( !xOldTextCursor.is() ) { sal_Bool bRemoveContent = sal_True; Any aAny; if( bLeft ) { // Headers and footers are switched on already, // and they aren't shared. aAny = xPropSet->getPropertyValue( sTextLeft ); } else { aAny = xPropSet->getPropertyValue( sOn ); sal_Bool bOn = *(sal_Bool *)aAny.getValue(); if( !bOn ) { // Switch header on bOn = sal_True; aAny.setValue( &bOn, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sOn, aAny ); // The content has not to be removed, because the header // or footer is empty already. bRemoveContent = sal_False; } // If a header or footer is not shared, share it now. aAny = xPropSet->getPropertyValue( sShareContent ); sal_Bool bShared = *(sal_Bool *)aAny.getValue(); if( !bShared ) { bShared = sal_True; aAny.setValue( &bShared, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sShareContent, aAny ); } aAny = xPropSet->getPropertyValue( sText ); } Reference < XText > xText; aAny >>= xText; if( bRemoveContent ) { OUString aText; xText->setString( aText ); } UniReference < XMLTextImportHelper > xTxtImport = GetImport().GetTextImport(); xOldTextCursor = xTxtImport->GetCursor(); xTxtImport->SetCursor( xText->createTextCursor() ); } pContext = GetImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList, XML_TEXT_TYPE_HEADER_FOOTER ); } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } void XMLTextHeaderFooterContext::EndElement() { if( xOldTextCursor.is() ) { GetImport().GetTextImport()->DeleteParagraph(); GetImport().GetTextImport()->SetCursor( xOldTextCursor ); } else if( !bLeft ) { // If no content has been inserted inro the header or footer, // switch it off. sal_Bool bOn = sal_False; Any aAny; aAny.setValue( &bOn, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sOn, aAny ); } } <commit_msg>INTEGRATION: CWS vgbugs07 (1.10.124); FILE MERGED 2007/06/04 13:23:39 vg 1.10.124.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextHeaderFooterContext.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2007-06-27 16:09:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_ #include <com/sun/star/text/XText.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XRELATIVETEXTCONTENTREMOVE_HPP_ #include <com/sun/star/text/XRelativeTextContentRemove.hpp> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_TEXTHEADERFOOTERCONTEXT_HXX_ #include "XMLTextHeaderFooterContext.hxx" #endif #ifndef _XMLOFF_TEXTTABLECONTEXT_HXX_ #include <xmloff/XMLTextTableContext.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; //using namespace ::com::sun::star::style; using namespace ::com::sun::star::text; using namespace ::com::sun::star::beans; //using namespace ::com::sun::star::container; //using namespace ::com::sun::star::lang; //using namespace ::com::sun::star::text; TYPEINIT1( XMLTextHeaderFooterContext, SvXMLImportContext ); XMLTextHeaderFooterContext::XMLTextHeaderFooterContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const uno::Reference< xml::sax::XAttributeList > &, const Reference < XPropertySet > & rPageStylePropSet, sal_Bool bFooter, sal_Bool bLft ) : SvXMLImportContext( rImport, nPrfx, rLName ), xPropSet( rPageStylePropSet ), sOn( OUString::createFromAscii( bFooter ? "FooterIsOn" : "HeaderIsOn" ) ), sShareContent( OUString::createFromAscii( bFooter ? "FooterIsShared" : "HeaderIsShared" ) ), sText( OUString::createFromAscii( bFooter ? "FooterText" : "HeaderText" ) ), sTextLeft( OUString::createFromAscii( bFooter ? "FooterTextLeft" : "HeaderTextLeft" ) ), bInsertContent( sal_True ), bLeft( bLft ) { if( bLeft ) { Any aAny; aAny = xPropSet->getPropertyValue( sOn ); sal_Bool bOn = *(sal_Bool *)aAny.getValue(); if( bOn ) { aAny = xPropSet->getPropertyValue( sShareContent ); sal_Bool bShared = *(sal_Bool *)aAny.getValue(); if( bShared ) { // Don't share headers any longer bShared = sal_False; aAny.setValue( &bShared, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sShareContent, aAny ); } } else { // If headers or footers are switched off, no content must be // inserted. bInsertContent = sal_False; } } } XMLTextHeaderFooterContext::~XMLTextHeaderFooterContext() { } SvXMLImportContext *XMLTextHeaderFooterContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const uno::Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if( bInsertContent ) { if( !xOldTextCursor.is() ) { sal_Bool bRemoveContent = sal_True; Any aAny; if( bLeft ) { // Headers and footers are switched on already, // and they aren't shared. aAny = xPropSet->getPropertyValue( sTextLeft ); } else { aAny = xPropSet->getPropertyValue( sOn ); sal_Bool bOn = *(sal_Bool *)aAny.getValue(); if( !bOn ) { // Switch header on bOn = sal_True; aAny.setValue( &bOn, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sOn, aAny ); // The content has not to be removed, because the header // or footer is empty already. bRemoveContent = sal_False; } // If a header or footer is not shared, share it now. aAny = xPropSet->getPropertyValue( sShareContent ); sal_Bool bShared = *(sal_Bool *)aAny.getValue(); if( !bShared ) { bShared = sal_True; aAny.setValue( &bShared, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sShareContent, aAny ); } aAny = xPropSet->getPropertyValue( sText ); } Reference < XText > xText; aAny >>= xText; if( bRemoveContent ) { OUString aText; xText->setString( aText ); } UniReference < XMLTextImportHelper > xTxtImport = GetImport().GetTextImport(); xOldTextCursor = xTxtImport->GetCursor(); xTxtImport->SetCursor( xText->createTextCursor() ); } pContext = GetImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList, XML_TEXT_TYPE_HEADER_FOOTER ); } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } void XMLTextHeaderFooterContext::EndElement() { if( xOldTextCursor.is() ) { GetImport().GetTextImport()->DeleteParagraph(); GetImport().GetTextImport()->SetCursor( xOldTextCursor ); } else if( !bLeft ) { // If no content has been inserted inro the header or footer, // switch it off. sal_Bool bOn = sal_False; Any aAny; aAny.setValue( &bOn, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sOn, aAny ); } } <|endoftext|>
<commit_before>#include <stdio.h> #include "xbyak/xbyak_util.h" #define NUM_OF_ARRAY(x) (sizeof(x) / sizeof(x[0])) struct PopCountTest : public Xbyak::CodeGenerator { PopCountTest(int n) : Xbyak::CodeGenerator(4096, Xbyak::DontSetProtectRWE) { mov(eax, n); popcnt(eax, eax); ret(); } }; void putCPUinfo() { using namespace Xbyak::util; Cpu cpu; printf("vendor %s\n", cpu.has(Cpu::tINTEL) ? "intel" : "amd"); static const struct { Cpu::Type type; const char *str; } tbl[] = { { Cpu::tMMX, "mmx" }, { Cpu::tMMX2, "mmx2" }, { Cpu::tCMOV, "cmov" }, { Cpu::tSSE, "sse" }, { Cpu::tSSE2, "sse2" }, { Cpu::tSSE3, "sse3" }, { Cpu::tSSSE3, "ssse3" }, { Cpu::tSSE41, "sse41" }, { Cpu::tSSE42, "sse42" }, { Cpu::tPOPCNT, "popcnt" }, { Cpu::t3DN, "3dn" }, { Cpu::tE3DN, "e3dn" }, { Cpu::tAESNI, "aesni" }, { Cpu::tRDTSCP, "rdtscp" }, { Cpu::tOSXSAVE, "osxsave(xgetvb)" }, { Cpu::tPCLMULQDQ, "pclmulqdq" }, { Cpu::tAVX, "avx" }, { Cpu::tFMA, "fma" }, { Cpu::tAVX2, "avx2" }, { Cpu::tBMI1, "bmi1" }, { Cpu::tBMI2, "bmi2" }, { Cpu::tLZCNT, "lzcnt" }, { Cpu::tPREFETCHW, "prefetchw" }, { Cpu::tENHANCED_REP, "enh_rep" }, { Cpu::tRDRAND, "rdrand" }, { Cpu::tADX, "adx" }, { Cpu::tRDSEED, "rdseed" }, { Cpu::tSMAP, "smap" }, { Cpu::tHLE, "hle" }, { Cpu::tRTM, "rtm" }, { Cpu::tMPX, "mpx" }, { Cpu::tSHA, "sha" }, { Cpu::tPREFETCHWT1, "prefetchwt1" }, { Cpu::tF16C, "f16c" }, { Cpu::tMOVBE, "movbe" }, { Cpu::tAVX512F, "avx512f" }, { Cpu::tAVX512DQ, "avx512dq" }, { Cpu::tAVX512IFMA, "avx512_ifma" }, { Cpu::tAVX512PF, "avx512pf" }, { Cpu::tAVX512ER, "avx512er" }, { Cpu::tAVX512CD, "avx512cd" }, { Cpu::tAVX512BW, "avx512bw" }, { Cpu::tAVX512VL, "avx512vl" }, { Cpu::tAVX512VBMI, "avx512_vbmi" }, { Cpu::tAVX512_4VNNIW, "avx512_4vnniw" }, { Cpu::tAVX512_4FMAPS, "avx512_4fmaps" }, { Cpu::tAVX512_VBMI2, "avx512_vbmi2" }, { Cpu::tGFNI, "gfni" }, { Cpu::tVAES, "vaes" }, { Cpu::tVPCLMULQDQ, "vpclmulqdq" }, { Cpu::tAVX512_VNNI, "avx512_vnni" }, { Cpu::tAVX512_BITALG, "avx512_bitalg" }, { Cpu::tAVX512_VPOPCNTDQ, "avx512_vpopcntdq" }, { Cpu::tAVX512_BF16, "avx512_bf16" }, { Cpu::tAVX512_VP2INTERSECT, "avx512_vp2intersect" }, { Cpu::tAMX_TILE, "amx(tile)" }, { Cpu::tAMX_INT8, "amx(int8)" }, { Cpu::tAMX_BF16, "amx(bf16)" }, { Cpu::tAVX_VNNI, "avx_vnni" }, { Cpu::tAVX512_FP16, "avx512_fp16" }, { Cpu::tWAITPKG, "waitpkg" }, { Cpu::tCLFLUSHOPT, "clflushopt" }, { Cpu::tCLDEMOTE, "cldemote" }, { Cpu::tMOVDIRI, "movidiri" }, { Cpu::tMOVDIR64B, "movidir64b" }, }; for (size_t i = 0; i < NUM_OF_ARRAY(tbl); i++) { if (cpu.has(tbl[i].type)) printf(" %s", tbl[i].str); } printf("\n"); if (cpu.has(Cpu::tPOPCNT)) { const int n = 0x12345678; // bitcount = 13 const int ok = 13; PopCountTest code(n); code.setProtectModeRE(); int (*f)() = code.getCode<int (*)()>(); int r = f(); if (r == ok) { puts("popcnt ok"); } else { printf("popcnt ng %d %d\n", r, ok); } code.setProtectModeRW(); } /* displayFamily displayModel Opteron 2376 10 4 Core2 Duo T7100 6 F Core i3-2120T 6 2A Core i7-2600 6 2A Xeon X5650 6 2C Core i7-3517 6 3A Core i7-3930K 6 2D */ cpu.putFamily(); if (!cpu.has(Cpu::tINTEL)) return; for (unsigned int i = 0; i < cpu.getDataCacheLevels(); i++) { printf("cache level=%u data cache size=%u cores sharing data cache=%u\n", i, cpu.getDataCacheSize(i), cpu.getCoresSharingDataCache(i)); } printf("SmtLevel =%u\n", cpu.getNumCores(Xbyak::util::SmtLevel)); printf("CoreLevel=%u\n", cpu.getNumCores(Xbyak::util::CoreLevel)); } int main() { #ifdef XBYAK32 puts("32bit"); #else puts("64bit"); #endif putCPUinfo(); } <commit_msg>fix typo<commit_after>#include <stdio.h> #include "xbyak/xbyak_util.h" #define NUM_OF_ARRAY(x) (sizeof(x) / sizeof(x[0])) struct PopCountTest : public Xbyak::CodeGenerator { PopCountTest(int n) : Xbyak::CodeGenerator(4096, Xbyak::DontSetProtectRWE) { mov(eax, n); popcnt(eax, eax); ret(); } }; void putCPUinfo() { using namespace Xbyak::util; Cpu cpu; printf("vendor %s\n", cpu.has(Cpu::tINTEL) ? "intel" : "amd"); static const struct { Cpu::Type type; const char *str; } tbl[] = { { Cpu::tMMX, "mmx" }, { Cpu::tMMX2, "mmx2" }, { Cpu::tCMOV, "cmov" }, { Cpu::tSSE, "sse" }, { Cpu::tSSE2, "sse2" }, { Cpu::tSSE3, "sse3" }, { Cpu::tSSSE3, "ssse3" }, { Cpu::tSSE41, "sse41" }, { Cpu::tSSE42, "sse42" }, { Cpu::tPOPCNT, "popcnt" }, { Cpu::t3DN, "3dn" }, { Cpu::tE3DN, "e3dn" }, { Cpu::tAESNI, "aesni" }, { Cpu::tRDTSCP, "rdtscp" }, { Cpu::tOSXSAVE, "osxsave(xgetvb)" }, { Cpu::tPCLMULQDQ, "pclmulqdq" }, { Cpu::tAVX, "avx" }, { Cpu::tFMA, "fma" }, { Cpu::tAVX2, "avx2" }, { Cpu::tBMI1, "bmi1" }, { Cpu::tBMI2, "bmi2" }, { Cpu::tLZCNT, "lzcnt" }, { Cpu::tPREFETCHW, "prefetchw" }, { Cpu::tENHANCED_REP, "enh_rep" }, { Cpu::tRDRAND, "rdrand" }, { Cpu::tADX, "adx" }, { Cpu::tRDSEED, "rdseed" }, { Cpu::tSMAP, "smap" }, { Cpu::tHLE, "hle" }, { Cpu::tRTM, "rtm" }, { Cpu::tMPX, "mpx" }, { Cpu::tSHA, "sha" }, { Cpu::tPREFETCHWT1, "prefetchwt1" }, { Cpu::tF16C, "f16c" }, { Cpu::tMOVBE, "movbe" }, { Cpu::tAVX512F, "avx512f" }, { Cpu::tAVX512DQ, "avx512dq" }, { Cpu::tAVX512IFMA, "avx512_ifma" }, { Cpu::tAVX512PF, "avx512pf" }, { Cpu::tAVX512ER, "avx512er" }, { Cpu::tAVX512CD, "avx512cd" }, { Cpu::tAVX512BW, "avx512bw" }, { Cpu::tAVX512VL, "avx512vl" }, { Cpu::tAVX512VBMI, "avx512_vbmi" }, { Cpu::tAVX512_4VNNIW, "avx512_4vnniw" }, { Cpu::tAVX512_4FMAPS, "avx512_4fmaps" }, { Cpu::tAVX512_VBMI2, "avx512_vbmi2" }, { Cpu::tGFNI, "gfni" }, { Cpu::tVAES, "vaes" }, { Cpu::tVPCLMULQDQ, "vpclmulqdq" }, { Cpu::tAVX512_VNNI, "avx512_vnni" }, { Cpu::tAVX512_BITALG, "avx512_bitalg" }, { Cpu::tAVX512_VPOPCNTDQ, "avx512_vpopcntdq" }, { Cpu::tAVX512_BF16, "avx512_bf16" }, { Cpu::tAVX512_VP2INTERSECT, "avx512_vp2intersect" }, { Cpu::tAMX_TILE, "amx(tile)" }, { Cpu::tAMX_INT8, "amx(int8)" }, { Cpu::tAMX_BF16, "amx(bf16)" }, { Cpu::tAVX_VNNI, "avx_vnni" }, { Cpu::tAVX512_FP16, "avx512_fp16" }, { Cpu::tWAITPKG, "waitpkg" }, { Cpu::tCLFLUSHOPT, "clflushopt" }, { Cpu::tCLDEMOTE, "cldemote" }, { Cpu::tMOVDIRI, "movdiri" }, { Cpu::tMOVDIR64B, "movdir64b" }, }; for (size_t i = 0; i < NUM_OF_ARRAY(tbl); i++) { if (cpu.has(tbl[i].type)) printf(" %s", tbl[i].str); } printf("\n"); if (cpu.has(Cpu::tPOPCNT)) { const int n = 0x12345678; // bitcount = 13 const int ok = 13; PopCountTest code(n); code.setProtectModeRE(); int (*f)() = code.getCode<int (*)()>(); int r = f(); if (r == ok) { puts("popcnt ok"); } else { printf("popcnt ng %d %d\n", r, ok); } code.setProtectModeRW(); } /* displayFamily displayModel Opteron 2376 10 4 Core2 Duo T7100 6 F Core i3-2120T 6 2A Core i7-2600 6 2A Xeon X5650 6 2C Core i7-3517 6 3A Core i7-3930K 6 2D */ cpu.putFamily(); if (!cpu.has(Cpu::tINTEL)) return; for (unsigned int i = 0; i < cpu.getDataCacheLevels(); i++) { printf("cache level=%u data cache size=%u cores sharing data cache=%u\n", i, cpu.getDataCacheSize(i), cpu.getCoresSharingDataCache(i)); } printf("SmtLevel =%u\n", cpu.getNumCores(Xbyak::util::SmtLevel)); printf("CoreLevel=%u\n", cpu.getNumCores(Xbyak::util::CoreLevel)); } int main() { #ifdef XBYAK32 puts("32bit"); #else puts("64bit"); #endif putCPUinfo(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextHeaderFooterContext.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2008-03-12 11:02:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_ #include <com/sun/star/text/XText.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XRELATIVETEXTCONTENTREMOVE_HPP_ #include <com/sun/star/text/XRelativeTextContentRemove.hpp> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_TEXTHEADERFOOTERCONTEXT_HXX_ #include "XMLTextHeaderFooterContext.hxx" #endif #ifndef _XMLOFF_TEXTTABLECONTEXT_HXX_ #include <xmloff/XMLTextTableContext.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; //using namespace ::com::sun::star::style; using namespace ::com::sun::star::text; using namespace ::com::sun::star::beans; //using namespace ::com::sun::star::container; //using namespace ::com::sun::star::lang; //using namespace ::com::sun::star::text; TYPEINIT1( XMLTextHeaderFooterContext, SvXMLImportContext ); XMLTextHeaderFooterContext::XMLTextHeaderFooterContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const uno::Reference< xml::sax::XAttributeList > &, const Reference < XPropertySet > & rPageStylePropSet, sal_Bool bFooter, sal_Bool bLft ) : SvXMLImportContext( rImport, nPrfx, rLName ), xPropSet( rPageStylePropSet ), sOn( OUString::createFromAscii( bFooter ? "FooterIsOn" : "HeaderIsOn" ) ), sShareContent( OUString::createFromAscii( bFooter ? "FooterIsShared" : "HeaderIsShared" ) ), sText( OUString::createFromAscii( bFooter ? "FooterText" : "HeaderText" ) ), sTextLeft( OUString::createFromAscii( bFooter ? "FooterTextLeft" : "HeaderTextLeft" ) ), bInsertContent( sal_True ), bLeft( bLft ) { if( bLeft ) { Any aAny; aAny = xPropSet->getPropertyValue( sOn ); sal_Bool bOn = *(sal_Bool *)aAny.getValue(); if( bOn ) { aAny = xPropSet->getPropertyValue( sShareContent ); sal_Bool bShared = *(sal_Bool *)aAny.getValue(); if( bShared ) { // Don't share headers any longer bShared = sal_False; aAny.setValue( &bShared, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sShareContent, aAny ); } } else { // If headers or footers are switched off, no content must be // inserted. bInsertContent = sal_False; } } } XMLTextHeaderFooterContext::~XMLTextHeaderFooterContext() { } SvXMLImportContext *XMLTextHeaderFooterContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const uno::Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if( bInsertContent ) { if( !xOldTextCursor.is() ) { sal_Bool bRemoveContent = sal_True; Any aAny; if( bLeft ) { // Headers and footers are switched on already, // and they aren't shared. aAny = xPropSet->getPropertyValue( sTextLeft ); } else { aAny = xPropSet->getPropertyValue( sOn ); sal_Bool bOn = *(sal_Bool *)aAny.getValue(); if( !bOn ) { // Switch header on bOn = sal_True; aAny.setValue( &bOn, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sOn, aAny ); // The content has not to be removed, because the header // or footer is empty already. bRemoveContent = sal_False; } // If a header or footer is not shared, share it now. aAny = xPropSet->getPropertyValue( sShareContent ); sal_Bool bShared = *(sal_Bool *)aAny.getValue(); if( !bShared ) { bShared = sal_True; aAny.setValue( &bShared, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sShareContent, aAny ); } aAny = xPropSet->getPropertyValue( sText ); } Reference < XText > xText; aAny >>= xText; if( bRemoveContent ) { OUString aText; xText->setString( aText ); } UniReference < XMLTextImportHelper > xTxtImport = GetImport().GetTextImport(); xOldTextCursor = xTxtImport->GetCursor(); xTxtImport->SetCursor( xText->createTextCursor() ); } pContext = GetImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList, XML_TEXT_TYPE_HEADER_FOOTER ); } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } void XMLTextHeaderFooterContext::EndElement() { if( xOldTextCursor.is() ) { GetImport().GetTextImport()->DeleteParagraph(); GetImport().GetTextImport()->SetCursor( xOldTextCursor ); } else if( !bLeft ) { // If no content has been inserted inro the header or footer, // switch it off. sal_Bool bOn = sal_False; Any aAny; aAny.setValue( &bOn, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sOn, aAny ); } } <commit_msg>INTEGRATION: CWS changefileheader (1.12.18); FILE MERGED 2008/04/01 13:05:30 thb 1.12.18.2: #i85898# Stripping all external header guards 2008/03/31 16:28:37 rt 1.12.18.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextHeaderFooterContext.cxx,v $ * $Revision: 1.13 $ * * 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_xmloff.hxx" #include <com/sun/star/text/XText.hpp> #include <com/sun/star/text/XRelativeTextContentRemove.hpp> #include <xmloff/nmspmap.hxx> #include "xmlnmspe.hxx" #include "XMLTextHeaderFooterContext.hxx" #ifndef _XMLOFF_TEXTTABLECONTEXT_HXX_ #include <xmloff/XMLTextTableContext.hxx> #endif #include <xmloff/xmlimp.hxx> using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; //using namespace ::com::sun::star::style; using namespace ::com::sun::star::text; using namespace ::com::sun::star::beans; //using namespace ::com::sun::star::container; //using namespace ::com::sun::star::lang; //using namespace ::com::sun::star::text; TYPEINIT1( XMLTextHeaderFooterContext, SvXMLImportContext ); XMLTextHeaderFooterContext::XMLTextHeaderFooterContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const uno::Reference< xml::sax::XAttributeList > &, const Reference < XPropertySet > & rPageStylePropSet, sal_Bool bFooter, sal_Bool bLft ) : SvXMLImportContext( rImport, nPrfx, rLName ), xPropSet( rPageStylePropSet ), sOn( OUString::createFromAscii( bFooter ? "FooterIsOn" : "HeaderIsOn" ) ), sShareContent( OUString::createFromAscii( bFooter ? "FooterIsShared" : "HeaderIsShared" ) ), sText( OUString::createFromAscii( bFooter ? "FooterText" : "HeaderText" ) ), sTextLeft( OUString::createFromAscii( bFooter ? "FooterTextLeft" : "HeaderTextLeft" ) ), bInsertContent( sal_True ), bLeft( bLft ) { if( bLeft ) { Any aAny; aAny = xPropSet->getPropertyValue( sOn ); sal_Bool bOn = *(sal_Bool *)aAny.getValue(); if( bOn ) { aAny = xPropSet->getPropertyValue( sShareContent ); sal_Bool bShared = *(sal_Bool *)aAny.getValue(); if( bShared ) { // Don't share headers any longer bShared = sal_False; aAny.setValue( &bShared, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sShareContent, aAny ); } } else { // If headers or footers are switched off, no content must be // inserted. bInsertContent = sal_False; } } } XMLTextHeaderFooterContext::~XMLTextHeaderFooterContext() { } SvXMLImportContext *XMLTextHeaderFooterContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const uno::Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if( bInsertContent ) { if( !xOldTextCursor.is() ) { sal_Bool bRemoveContent = sal_True; Any aAny; if( bLeft ) { // Headers and footers are switched on already, // and they aren't shared. aAny = xPropSet->getPropertyValue( sTextLeft ); } else { aAny = xPropSet->getPropertyValue( sOn ); sal_Bool bOn = *(sal_Bool *)aAny.getValue(); if( !bOn ) { // Switch header on bOn = sal_True; aAny.setValue( &bOn, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sOn, aAny ); // The content has not to be removed, because the header // or footer is empty already. bRemoveContent = sal_False; } // If a header or footer is not shared, share it now. aAny = xPropSet->getPropertyValue( sShareContent ); sal_Bool bShared = *(sal_Bool *)aAny.getValue(); if( !bShared ) { bShared = sal_True; aAny.setValue( &bShared, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sShareContent, aAny ); } aAny = xPropSet->getPropertyValue( sText ); } Reference < XText > xText; aAny >>= xText; if( bRemoveContent ) { OUString aText; xText->setString( aText ); } UniReference < XMLTextImportHelper > xTxtImport = GetImport().GetTextImport(); xOldTextCursor = xTxtImport->GetCursor(); xTxtImport->SetCursor( xText->createTextCursor() ); } pContext = GetImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList, XML_TEXT_TYPE_HEADER_FOOTER ); } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } void XMLTextHeaderFooterContext::EndElement() { if( xOldTextCursor.is() ) { GetImport().GetTextImport()->DeleteParagraph(); GetImport().GetTextImport()->SetCursor( xOldTextCursor ); } else if( !bLeft ) { // If no content has been inserted inro the header or footer, // switch it off. sal_Bool bOn = sal_False; Any aAny; aAny.setValue( &bOn, ::getBooleanCppuType() ); xPropSet->setPropertyValue( sOn, aAny ); } } <|endoftext|>
<commit_before>/** * \file * \brief FifoQueue class header * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-12-04 */ #ifndef INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #define INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #include "distortos/scheduler/FifoQueueBase.hpp" namespace distortos { /** * \brief FifoQueue class is a simple FIFO queue for thread-thread, thread-interrupt or interrupt-interrupt * communication. It supports multiple readers and multiple writers. It is implemented as a thin wrapper for * scheduler::FifoQueueBase. * * \param T is the type of data in queue */ template<typename T> class FifoQueue : private scheduler::FifoQueueBase { public: /// type of uninitialized storage for data using Storage = Storage<T>; /** * \brief FifoQueue's constructor * * \param [in] storage is an array of Storage elements * \param [in] maxElements is the number of elements in storage array */ FifoQueue(Storage* const storage, const size_t maxElements) : FifoQueueBase{storage, maxElements, TypeTag<T>{}} { } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(const T& value) { return FifoQueueBase::push(value); } }; } // namespace distortos #endif // INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ <commit_msg>FifoQueue: add FifoQueue::pop()<commit_after>/** * \file * \brief FifoQueue class header * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-12-04 */ #ifndef INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #define INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #include "distortos/scheduler/FifoQueueBase.hpp" namespace distortos { /** * \brief FifoQueue class is a simple FIFO queue for thread-thread, thread-interrupt or interrupt-interrupt * communication. It supports multiple readers and multiple writers. It is implemented as a thin wrapper for * scheduler::FifoQueueBase. * * \param T is the type of data in queue */ template<typename T> class FifoQueue : private scheduler::FifoQueueBase { public: /// type of uninitialized storage for data using Storage = Storage<T>; /** * \brief FifoQueue's constructor * * \param [in] storage is an array of Storage elements * \param [in] maxElements is the number of elements in storage array */ FifoQueue(Storage* const storage, const size_t maxElements) : FifoQueueBase{storage, maxElements, TypeTag<T>{}} { } /** * \brief Pops the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::pop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int pop(T& value) { return FifoQueueBase::pop(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(const T& value) { return FifoQueueBase::push(value); } }; } // namespace distortos #endif // INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AttrTransformerAction.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-07-13 08:43:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX #define _XMLOFF_ATTRTRANSFORMERACTION_HXX #ifndef _XMLOFF_TRANSFORMERACTION_HXX #include "TransformerAction.hxx" #endif enum XMLAttrTransformerAction { XML_ATACTION_EOT=XML_TACTION_EOT, // uses for initialization only XML_ATACTION_COPY, // copy attr XML_ATACTION_RENAME, // rename attr: // - param1: namespace + // token of local name XML_ATACTION_REMOVE, // remove attr XML_ATACTION_IN2INCH, // replace "in" with "inch" XML_ATACTION_INS2INCHS, // replace "in" with "inch" // multiple times XML_ATACTION_RENAME_IN2INCH, // replace "in" with "inch" and rename // attr: // - param1: namespace + // token of local name XML_ATACTION_INCH2IN, // replace "inch" with "in" XML_ATACTION_INCHS2INS, // replace "inch" with "in" // multiple times XML_ATACTION_RENAME_INCH2IN, // replace "inch" with "in" and rename // attr: // - param1: namespace + // token of local name XML_ATACTION_STYLE_FAMILY, // NOP, used for style:family XML_ATACTION_DECODE_STYLE_NAME, // NOP, used for style:name // - param1: style family XML_ATACTION_STYLE_DISPLAY_NAME, // NOP, used for style:display_name // - param1: style family XML_ATACTION_DECODE_STYLE_NAME_REF, // NOP, used for style:name reference // - param1: style family XML_ATACTION_RENAME_DECODE_STYLE_NAME_REF, // NOP, used for style:name // - param1: namespace + // token of local name XML_ATACTION_ENCODE_STYLE_NAME, // NOP, used for style:name XML_ATACTION_ENCODE_STYLE_NAME_REF, // NOP, used for style:name XML_ATACTION_RENAME_ENCODE_STYLE_NAME_REF, // NOP, used for style:name // - param1: namespace + // token of local name // - param2: style family XML_ATACTION_MOVE_TO_ELEM, // turn attr into an elem // - param1: namespace + // token of local name XML_ATACTION_MOVE_FROM_ELEM, // turn elem into an attr: // - param1: namespace + // token of local name XML_ATACTION_NEG_PERCENT, // replace % val with 100-% XML_ATACTION_RENAME_NEG_PERCENT, // replace % val with 100-%, rename attr // - param1: namespace + // token of local name XML_ATACTION_HREF, // xmlink:href XML_ATACTION_ADD_NAMESPACE_PREFIX, // add a namespace prefix // - param1: prefix XML_ATACTION_ADD_APP_NAMESPACE_PREFIX, // add a namespace prefix // - param1: default prefix XML_ATACTION_RENAME_ADD_NAMESPACE_PREFIX, // add a namespace prefix // - param1: namespace + // token of local name // - param2: prefix XML_ATACTION_REMOVE_NAMESPACE_PREFIX,// remove a namespace prefix // - param1: prefix XML_ATACTION_REMOVE_ANY_NAMESPACE_PREFIX,// remove any namespace prefix XML_ATACTION_RENAME_REMOVE_NAMESPACE_PREFIX,// remove a namespace prefix // - param1: namespace + // token of local name // - param2: prefix XML_ATACTION_EVENT_NAME, XML_ATACTION_MACRO_NAME, XML_ATACTION_MACRO_LOCATION, XML_ATACTION_URI_OOO, // an URI in OOo notation // - param1: pacakage URI are supported XML_ATACTION_URI_OASIS, // an URI in OASIS notation // - param1: pacakage URI are supported XML_ATACTION_USER_DEFINED=0x80000000,// user defined actions start here XML_ATACTION_END=XML_TACTION_END }; #endif // _XMLOFF_ATTRTRANSFORMERACTION_HXX <commit_msg>INTEGRATION: CWS oasisbf1 (1.2.38); FILE MERGED 2004/09/14 17:07:34 toconnor 1.2.38.1: #i33735# export of bindings to Scripting Framework macros and dlg:border attributes from Oasis to OOo<commit_after>/************************************************************************* * * $RCSfile: AttrTransformerAction.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-11-09 12:20:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX #define _XMLOFF_ATTRTRANSFORMERACTION_HXX #ifndef _XMLOFF_TRANSFORMERACTION_HXX #include "TransformerAction.hxx" #endif enum XMLAttrTransformerAction { XML_ATACTION_EOT=XML_TACTION_EOT, // uses for initialization only XML_ATACTION_COPY, // copy attr XML_ATACTION_RENAME, // rename attr: // - param1: namespace + // token of local name XML_ATACTION_REMOVE, // remove attr XML_ATACTION_IN2INCH, // replace "in" with "inch" XML_ATACTION_INS2INCHS, // replace "in" with "inch" // multiple times XML_ATACTION_RENAME_IN2INCH, // replace "in" with "inch" and rename // attr: // - param1: namespace + // token of local name XML_ATACTION_INCH2IN, // replace "inch" with "in" XML_ATACTION_INCHS2INS, // replace "inch" with "in" // multiple times XML_ATACTION_RENAME_INCH2IN, // replace "inch" with "in" and rename // attr: // - param1: namespace + // token of local name XML_ATACTION_STYLE_FAMILY, // NOP, used for style:family XML_ATACTION_DECODE_STYLE_NAME, // NOP, used for style:name // - param1: style family XML_ATACTION_STYLE_DISPLAY_NAME, // NOP, used for style:display_name // - param1: style family XML_ATACTION_DECODE_STYLE_NAME_REF, // NOP, used for style:name reference // - param1: style family XML_ATACTION_RENAME_DECODE_STYLE_NAME_REF, // NOP, used for style:name // - param1: namespace + // token of local name XML_ATACTION_ENCODE_STYLE_NAME, // NOP, used for style:name XML_ATACTION_ENCODE_STYLE_NAME_REF, // NOP, used for style:name XML_ATACTION_RENAME_ENCODE_STYLE_NAME_REF, // NOP, used for style:name // - param1: namespace + // token of local name // - param2: style family XML_ATACTION_MOVE_TO_ELEM, // turn attr into an elem // - param1: namespace + // token of local name XML_ATACTION_MOVE_FROM_ELEM, // turn elem into an attr: // - param1: namespace + // token of local name XML_ATACTION_NEG_PERCENT, // replace % val with 100-% XML_ATACTION_RENAME_NEG_PERCENT, // replace % val with 100-%, rename attr // - param1: namespace + // token of local name XML_ATACTION_HREF, // xmlink:href XML_ATACTION_ADD_NAMESPACE_PREFIX, // add a namespace prefix // - param1: prefix XML_ATACTION_ADD_APP_NAMESPACE_PREFIX, // add a namespace prefix // - param1: default prefix XML_ATACTION_RENAME_ADD_NAMESPACE_PREFIX, // add a namespace prefix // - param1: namespace + // token of local name // - param2: prefix XML_ATACTION_REMOVE_NAMESPACE_PREFIX,// remove a namespace prefix // - param1: prefix XML_ATACTION_REMOVE_ANY_NAMESPACE_PREFIX,// remove any namespace prefix XML_ATACTION_RENAME_REMOVE_NAMESPACE_PREFIX,// remove a namespace prefix // - param1: namespace + // token of local name // - param2: prefix XML_ATACTION_EVENT_NAME, XML_ATACTION_MACRO_NAME, XML_ATACTION_MACRO_LOCATION, XML_ATACTION_DLG_BORDER, XML_ATACTION_URI_OOO, // an URI in OOo notation // - param1: pacakage URI are supported XML_ATACTION_URI_OASIS, // an URI in OASIS notation // - param1: pacakage URI are supported XML_ATACTION_USER_DEFINED=0x80000000,// user defined actions start here XML_ATACTION_END=XML_TACTION_END }; #endif // _XMLOFF_ATTRTRANSFORMERACTION_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: certificatechooser.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: kz $ $Date: 2005-10-05 14:56:55 $ * * 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 <xmlsecurity/certificatechooser.hxx> #include <xmlsecurity/certificateviewer.hxx> #include <xmlsecurity/biginteger.hxx> #ifndef _COM_SUN_STAR_XML_CRYPTO_XSECURITYENVIRONMENT_HPP_ #include <com/sun/star/xml/crypto/XSecurityEnvironment.hpp> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #include <com/sun/star/security/NoPasswordException.hpp> #include <com/sun/star/security/CertificateCharacters.hpp> #include <dialogs.hrc> #include <resourcemanager.hxx> #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif /* HACK: disable some warnings for MS-C */ #ifdef _MSC_VER #pragma warning (disable : 4355) // 4355: this used in initializer-list #endif using namespace ::com::sun::star; #define INVAL_SEL 0xFFFF USHORT CertificateChooser::GetSelectedEntryPos( void ) const { USHORT nSel = INVAL_SEL; SvLBoxEntry* pSel = maCertLB.FirstSelected(); if( pSel ) nSel = (USHORT) ( sal_uIntPtr ) pSel->GetUserData(); return (USHORT) nSel; } CertificateChooser::CertificateChooser( Window* _pParent, uno::Reference< dcss::xml::crypto::XSecurityEnvironment >& _rxSecurityEnvironment, const SignatureInformations& _rCertsToIgnore ) :ModalDialog ( _pParent, XMLSEC_RES( RID_XMLSECDLG_CERTCHOOSER ) ) ,maCertsToIgnore( _rCertsToIgnore ) ,maHintFT ( this, ResId( FT_HINT_SELECT ) ) ,maCertLB ( this, ResId( LB_SIGNATURES ) ) ,maViewBtn ( this, ResId( BTN_VIEWCERT ) ) ,maBottomSepFL ( this, ResId( FL_BOTTOM_SEP ) ) ,maOKBtn ( this, ResId( BTN_OK ) ) ,maCancelBtn ( this, ResId( BTN_CANCEL ) ) ,maHelpBtn ( this, ResId( BTN_HELP ) ) { static long nTabs[] = { 3, 0, 30*CS_LB_WIDTH/100, 60*CS_LB_WIDTH/100 }; maCertLB.SetTabs( &nTabs[0] ); maCertLB.InsertHeaderEntry( String( ResId( STR_HEADERBAR ) ) ); maCertLB.SetSelectHdl( LINK( this, CertificateChooser, CertificateHighlightHdl ) ); maCertLB.SetDoubleClickHdl( LINK( this, CertificateChooser, CertificateSelectHdl ) ); maViewBtn.SetClickHdl( LINK( this, CertificateChooser, ViewButtonHdl ) ); FreeResource(); mxSecurityEnvironment = _rxSecurityEnvironment; mbInitialized = FALSE; // disable buttons CertificateHighlightHdl( NULL ); } CertificateChooser::~CertificateChooser() { } short CertificateChooser::Execute() { // #i48432# // We can't check for personal certificates before raising this dialog, // because the mozilla implementation throws a NoPassword exception, // if the user pressed cancel, and also if the database does not exist! // But in the later case, the is no password query, and the user is confused // that nothing happens when pressing "Add..." in the SignatureDialog. // PostUserEvent( LINK( this, CertificateChooser, Initialize ) ); // PostUserLink behavior is to slow, so do it directly before Execute(). // Problem: This Dialog should be visible right now, and the parent should not be accessible. // Show, Update, DIsableInput... Window* pMe = this; Window* pParent = GetParent(); if ( pParent ) pParent->EnableInput( FALSE ); pMe->Show(); pMe->Update(); ImplInitialize(); if ( pParent ) pParent->EnableInput( TRUE ); return ModalDialog::Execute(); } // IMPL_LINK( CertificateChooser, Initialize, void*, EMPTYARG ) void CertificateChooser::ImplInitialize() { if ( !mbInitialized ) { try { maCerts = mxSecurityEnvironment->getPersonalCertificates(); } catch (security::NoPasswordException&) { } sal_Int32 nCertificates = maCerts.getLength(); sal_Int32 nCertificatesToIgnore = maCertsToIgnore.size(); for( sal_Int32 nCert = nCertificates; nCert; ) { uno::Reference< security::XCertificate > xCert = maCerts[ --nCert ]; sal_Bool bIgnoreThis = false; // Do we already use that? if( nCertificatesToIgnore ) { rtl::OUString aIssuerName = xCert->getIssuerName(); for( sal_Int32 nSig = 0; nSig < nCertificatesToIgnore; ++nSig ) { const SignatureInformation& rInf = maCertsToIgnore[ nSig ]; if ( ( aIssuerName == rInf.ouX509IssuerName ) && ( bigIntegerToNumericString( xCert->getSerialNumber() ) == rInf.ouX509SerialNumber ) ) { bIgnoreThis = true; break; } } } if ( !bIgnoreThis ) { // Check if we have a private key for this... long nCertificateCharacters = mxSecurityEnvironment->getCertificateCharacters( xCert ); if ( !( nCertificateCharacters & security::CertificateCharacters::HAS_PRIVATE_KEY ) ) bIgnoreThis = true; } if ( bIgnoreThis ) { ::comphelper::removeElementAt( maCerts, nCert ); nCertificates = maCerts.getLength(); } } // fill list of certificates; the first entry will be selected for ( sal_Int32 nC = 0; nC < nCertificates; ++nC ) { String sEntry( XmlSec::GetContentPart( maCerts[ nC ]->getSubjectName() ) ); sEntry += '\t'; sEntry += XmlSec::GetContentPart( maCerts[ nC ]->getIssuerName() ); sEntry += '\t'; sEntry += XmlSec::GetDateString( maCerts[ nC ]->getNotValidAfter() ); SvLBoxEntry* pEntry = maCertLB.InsertEntry( sEntry ); pEntry->SetUserData( ( void* )nC ); // missuse user data as index } // enable/disable buttons CertificateHighlightHdl( NULL ); mbInitialized = TRUE; } } uno::Reference< dcss::security::XCertificate > CertificateChooser::GetSelectedCertificate() { uno::Reference< dcss::security::XCertificate > xCert; USHORT nSelected = GetSelectedEntryPos(); if ( nSelected < maCerts.getLength() ) xCert = maCerts[ nSelected ]; return xCert; } IMPL_LINK( CertificateChooser, CertificateHighlightHdl, void*, EMPTYARG ) { sal_Bool bEnable = GetSelectedCertificate().is(); maViewBtn.Enable( bEnable ); maOKBtn.Enable( bEnable ); return 0; } IMPL_LINK( CertificateChooser, CertificateSelectHdl, void*, EMPTYARG ) { EndDialog( RET_OK ); return 0; } IMPL_LINK( CertificateChooser, ViewButtonHdl, Button*, EMPTYARG ) { ImplShowCertificateDetails(); return 0; } void CertificateChooser::ImplShowCertificateDetails() { uno::Reference< dcss::security::XCertificate > xCert = GetSelectedCertificate(); if( xCert.is() ) { CertificateViewer aViewer( this, mxSecurityEnvironment, xCert, TRUE ); aViewer.Execute(); } } <commit_msg>INTEGRATION: CWS pchfix02 (1.9.80); FILE MERGED 2006/09/01 18:00:48 kaib 1.9.80.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: certificatechooser.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2006-09-16 14:35:04 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmlsecurity.hxx" #include <xmlsecurity/certificatechooser.hxx> #include <xmlsecurity/certificateviewer.hxx> #include <xmlsecurity/biginteger.hxx> #ifndef _COM_SUN_STAR_XML_CRYPTO_XSECURITYENVIRONMENT_HPP_ #include <com/sun/star/xml/crypto/XSecurityEnvironment.hpp> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #include <com/sun/star/security/NoPasswordException.hpp> #include <com/sun/star/security/CertificateCharacters.hpp> #include <dialogs.hrc> #include <resourcemanager.hxx> #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif /* HACK: disable some warnings for MS-C */ #ifdef _MSC_VER #pragma warning (disable : 4355) // 4355: this used in initializer-list #endif using namespace ::com::sun::star; #define INVAL_SEL 0xFFFF USHORT CertificateChooser::GetSelectedEntryPos( void ) const { USHORT nSel = INVAL_SEL; SvLBoxEntry* pSel = maCertLB.FirstSelected(); if( pSel ) nSel = (USHORT) ( sal_uIntPtr ) pSel->GetUserData(); return (USHORT) nSel; } CertificateChooser::CertificateChooser( Window* _pParent, uno::Reference< dcss::xml::crypto::XSecurityEnvironment >& _rxSecurityEnvironment, const SignatureInformations& _rCertsToIgnore ) :ModalDialog ( _pParent, XMLSEC_RES( RID_XMLSECDLG_CERTCHOOSER ) ) ,maCertsToIgnore( _rCertsToIgnore ) ,maHintFT ( this, ResId( FT_HINT_SELECT ) ) ,maCertLB ( this, ResId( LB_SIGNATURES ) ) ,maViewBtn ( this, ResId( BTN_VIEWCERT ) ) ,maBottomSepFL ( this, ResId( FL_BOTTOM_SEP ) ) ,maOKBtn ( this, ResId( BTN_OK ) ) ,maCancelBtn ( this, ResId( BTN_CANCEL ) ) ,maHelpBtn ( this, ResId( BTN_HELP ) ) { static long nTabs[] = { 3, 0, 30*CS_LB_WIDTH/100, 60*CS_LB_WIDTH/100 }; maCertLB.SetTabs( &nTabs[0] ); maCertLB.InsertHeaderEntry( String( ResId( STR_HEADERBAR ) ) ); maCertLB.SetSelectHdl( LINK( this, CertificateChooser, CertificateHighlightHdl ) ); maCertLB.SetDoubleClickHdl( LINK( this, CertificateChooser, CertificateSelectHdl ) ); maViewBtn.SetClickHdl( LINK( this, CertificateChooser, ViewButtonHdl ) ); FreeResource(); mxSecurityEnvironment = _rxSecurityEnvironment; mbInitialized = FALSE; // disable buttons CertificateHighlightHdl( NULL ); } CertificateChooser::~CertificateChooser() { } short CertificateChooser::Execute() { // #i48432# // We can't check for personal certificates before raising this dialog, // because the mozilla implementation throws a NoPassword exception, // if the user pressed cancel, and also if the database does not exist! // But in the later case, the is no password query, and the user is confused // that nothing happens when pressing "Add..." in the SignatureDialog. // PostUserEvent( LINK( this, CertificateChooser, Initialize ) ); // PostUserLink behavior is to slow, so do it directly before Execute(). // Problem: This Dialog should be visible right now, and the parent should not be accessible. // Show, Update, DIsableInput... Window* pMe = this; Window* pParent = GetParent(); if ( pParent ) pParent->EnableInput( FALSE ); pMe->Show(); pMe->Update(); ImplInitialize(); if ( pParent ) pParent->EnableInput( TRUE ); return ModalDialog::Execute(); } // IMPL_LINK( CertificateChooser, Initialize, void*, EMPTYARG ) void CertificateChooser::ImplInitialize() { if ( !mbInitialized ) { try { maCerts = mxSecurityEnvironment->getPersonalCertificates(); } catch (security::NoPasswordException&) { } sal_Int32 nCertificates = maCerts.getLength(); sal_Int32 nCertificatesToIgnore = maCertsToIgnore.size(); for( sal_Int32 nCert = nCertificates; nCert; ) { uno::Reference< security::XCertificate > xCert = maCerts[ --nCert ]; sal_Bool bIgnoreThis = false; // Do we already use that? if( nCertificatesToIgnore ) { rtl::OUString aIssuerName = xCert->getIssuerName(); for( sal_Int32 nSig = 0; nSig < nCertificatesToIgnore; ++nSig ) { const SignatureInformation& rInf = maCertsToIgnore[ nSig ]; if ( ( aIssuerName == rInf.ouX509IssuerName ) && ( bigIntegerToNumericString( xCert->getSerialNumber() ) == rInf.ouX509SerialNumber ) ) { bIgnoreThis = true; break; } } } if ( !bIgnoreThis ) { // Check if we have a private key for this... long nCertificateCharacters = mxSecurityEnvironment->getCertificateCharacters( xCert ); if ( !( nCertificateCharacters & security::CertificateCharacters::HAS_PRIVATE_KEY ) ) bIgnoreThis = true; } if ( bIgnoreThis ) { ::comphelper::removeElementAt( maCerts, nCert ); nCertificates = maCerts.getLength(); } } // fill list of certificates; the first entry will be selected for ( sal_Int32 nC = 0; nC < nCertificates; ++nC ) { String sEntry( XmlSec::GetContentPart( maCerts[ nC ]->getSubjectName() ) ); sEntry += '\t'; sEntry += XmlSec::GetContentPart( maCerts[ nC ]->getIssuerName() ); sEntry += '\t'; sEntry += XmlSec::GetDateString( maCerts[ nC ]->getNotValidAfter() ); SvLBoxEntry* pEntry = maCertLB.InsertEntry( sEntry ); pEntry->SetUserData( ( void* )nC ); // missuse user data as index } // enable/disable buttons CertificateHighlightHdl( NULL ); mbInitialized = TRUE; } } uno::Reference< dcss::security::XCertificate > CertificateChooser::GetSelectedCertificate() { uno::Reference< dcss::security::XCertificate > xCert; USHORT nSelected = GetSelectedEntryPos(); if ( nSelected < maCerts.getLength() ) xCert = maCerts[ nSelected ]; return xCert; } IMPL_LINK( CertificateChooser, CertificateHighlightHdl, void*, EMPTYARG ) { sal_Bool bEnable = GetSelectedCertificate().is(); maViewBtn.Enable( bEnable ); maOKBtn.Enable( bEnable ); return 0; } IMPL_LINK( CertificateChooser, CertificateSelectHdl, void*, EMPTYARG ) { EndDialog( RET_OK ); return 0; } IMPL_LINK( CertificateChooser, ViewButtonHdl, Button*, EMPTYARG ) { ImplShowCertificateDetails(); return 0; } void CertificateChooser::ImplShowCertificateDetails() { uno::Reference< dcss::security::XCertificate > xCert = GetSelectedCertificate(); if( xCert.is() ) { CertificateViewer aViewer( this, mxSecurityEnvironment, xCert, TRUE ); aViewer.Execute(); } } <|endoftext|>
<commit_before>#pragma once #include <vector> #include <rex/asyncresourceview.hpp> namespace rex { template <typename ResourceType> class ProgressTracker { public: class Status { public: Status(int32_t waiting, int32_t done, int32_t failed); int32_t total() const; int32_t waiting() const; int32_t done() const; int32_t failed() const; float waitingRatio() const; float doneRatio() const; float failedRatio() const; private: float toRatio(int32_t amount) const; int32_t mTotal; int32_t mWaiting; int32_t mDone; int32_t mFailed; float mWaitingRatio; float mDoneRatio; float mFailedRatio; }; ProgressTracker(std::vector<AsyncResourceView<ResourceType>> toTrack); int32_t total() const; Status status() const; private: void updateValues() const; std::vector<AsyncResourceView<ResourceType>> mToTrack; mutable int32_t mDoneCount; mutable int32_t mWaitingCount; mutable int32_t mFailedCount; }; template <typename ResourceType> ProgressTracker<ResourceType>::Status::Status(int32_t waiting, int32_t done, int32_t failed): mTotal(waiting + done + failed), mWaiting(waiting), mDone(done), mFailed(failed), mWaitingRatio(toRatio(waiting)), mDoneRatio(toRatio(done)), mFailedRatio(toRatio(failed)) { } template <typename ResourceType> int32_t ProgressTracker<ResourceType>::Status::total() const { return mTotal; } template <typename ResourceType> int32_t ProgressTracker<ResourceType>::Status::waiting() const { return mWaiting; } template <typename ResourceType> int32_t ProgressTracker<ResourceType>::Status::done() const { return mDone; } template <typename ResourceType> int32_t ProgressTracker<ResourceType>::Status::failed() const { return mFailed; } template <typename ResourceType> float ProgressTracker<ResourceType>::Status::waitingRatio() const { return mWaitingRatio; } template <typename ResourceType> float ProgressTracker<ResourceType>::Status::doneRatio() const { return mDoneRatio; } template <typename ResourceType> float ProgressTracker<ResourceType>::Status::failedRatio() const { return mFailedRatio; } template <typename ResourceType> float ProgressTracker<ResourceType>::Status::toRatio(int32_t amount) const { if(amount == 0) return 0.0f; else if(amount == mTotal) return 1.0f; else return static_cast<float>(amount) / static_cast<float>(mTotal); } template <typename ResourceType> ProgressTracker<ResourceType>::ProgressTracker(std::vector<AsyncResourceView<ResourceType>> toTrack): mToTrack(std::move(toTrack)), mDoneCount(0), mWaitingCount(0), mFailedCount(0) { } template <typename ResourceType> int32_t ProgressTracker<ResourceType>::total() const { return static_cast<int32_t>(mToTrack.size()); } template <typename ResourceType> typename ProgressTracker<ResourceType>::Status ProgressTracker<ResourceType>::status() const { updateValues(); return Status( mWaitingCount, mDoneCount, mFailedCount ); } template <typename ResourceType> void ProgressTracker<ResourceType>::updateValues() const { int32_t waiting = 0; int32_t done = 0; int32_t failed = 0; for(const auto& view : mToTrack) { auto futureStatus = view.future.wait_for(std::chrono::milliseconds(0)); if(futureStatus == std::future_status::timeout) ++waiting; else if(futureStatus == std::future_status::ready) { try { view.future.get(); ++done; } catch(...) { ++failed; } } } mWaitingCount = waiting; mDoneCount = done; mFailedCount = failed; } } <commit_msg>simplified code<commit_after>#pragma once #include <vector> #include <rex/asyncresourceview.hpp> namespace rex { template <typename ResourceType> class ProgressTracker { public: class Status { public: Status(int32_t waiting, int32_t done, int32_t failed); int32_t total() const; int32_t waiting() const; int32_t done() const; int32_t failed() const; float waitingRatio() const; float doneRatio() const; float failedRatio() const; private: float toRatio(int32_t amount) const; int32_t mTotal; int32_t mWaiting; int32_t mDone; int32_t mFailed; float mWaitingRatio; float mDoneRatio; float mFailedRatio; }; ProgressTracker(std::vector<AsyncResourceView<ResourceType>> toTrack); int32_t total() const; Status status() const; private: std::vector<AsyncResourceView<ResourceType>> mToTrack; }; template <typename ResourceType> ProgressTracker<ResourceType>::Status::Status(int32_t waiting, int32_t done, int32_t failed): mTotal(waiting + done + failed), mWaiting(waiting), mDone(done), mFailed(failed), mWaitingRatio(toRatio(waiting)), mDoneRatio(toRatio(done)), mFailedRatio(toRatio(failed)) { } template <typename ResourceType> int32_t ProgressTracker<ResourceType>::Status::total() const { return mTotal; } template <typename ResourceType> int32_t ProgressTracker<ResourceType>::Status::waiting() const { return mWaiting; } template <typename ResourceType> int32_t ProgressTracker<ResourceType>::Status::done() const { return mDone; } template <typename ResourceType> int32_t ProgressTracker<ResourceType>::Status::failed() const { return mFailed; } template <typename ResourceType> float ProgressTracker<ResourceType>::Status::waitingRatio() const { return mWaitingRatio; } template <typename ResourceType> float ProgressTracker<ResourceType>::Status::doneRatio() const { return mDoneRatio; } template <typename ResourceType> float ProgressTracker<ResourceType>::Status::failedRatio() const { return mFailedRatio; } template <typename ResourceType> float ProgressTracker<ResourceType>::Status::toRatio(int32_t amount) const { if(amount == 0) return 0.0f; else if(amount == mTotal) return 1.0f; else return static_cast<float>(amount) / static_cast<float>(mTotal); } template <typename ResourceType> ProgressTracker<ResourceType>::ProgressTracker(std::vector<AsyncResourceView<ResourceType>> toTrack): mToTrack(std::move(toTrack)) { } template <typename ResourceType> int32_t ProgressTracker<ResourceType>::total() const { return static_cast<int32_t>(mToTrack.size()); } template <typename ResourceType> typename ProgressTracker<ResourceType>::Status ProgressTracker<ResourceType>::status() const { int32_t waiting = 0; int32_t done = 0; int32_t failed = 0; for(const auto& view : mToTrack) { auto futureStatus = view.future.wait_for(std::chrono::milliseconds(0)); if(futureStatus == std::future_status::timeout) ++waiting; else if(futureStatus == std::future_status::ready) { try { view.future.get(); ++done; } catch(...) { ++failed; } } } return Status( waiting, done, failed ); } } <|endoftext|>
<commit_before>/* * Use and distribution licensed under the Apache license version 2. * * See the COPYING file in the root project directory for full text. */ #include <iostream> #include <cctype> #include <sstream> #include "parser/statements/create_table.h" #include "parser/error.h" #include "parser/token.h" #include "statements/create_table.h" namespace sqltoast { // // The CREATE TABLE statement follows this EBNF form for the following SQL // dialects: // // * SQL_DIALECT_ANSI_1992 // // <table definition> ::= // CREATE [{GLOBAL|LOCAL} TEMPORARY] TABLE <table name> // <table element list> // [ON COMMIT {DELETE|PRESERVE} ROWS] // bool parse_create_table(parse_context_t& ctx) { tokens_t::iterator tok_it = ctx.tokens.begin(); tokens_t::iterator tok_ident = ctx.tokens.end(); symbol_t exp_sym = SYMBOL_CREATE; symbol_t cur_sym = (*tok_it).symbol; statements::table_type_t table_type = statements::TABLE_TYPE_NORMAL; goto next_token; // BEGIN STATE MACHINE table_kw_or_table_type: // We get here after successfully finding the CREATE symbol. We can // either match the table keyword or the table type clause tok_it = ctx.skip_comments(tok_it); cur_sym = (*tok_it).symbol; if (cur_sym == SYMBOL_GLOBAL) { table_type = statements::TABLE_TYPE_TEMPORARY_GLOBAL; tok_it++; goto expect_temporary; } else if (cur_sym == SYMBOL_LOCAL) { table_type = statements::TABLE_TYPE_TEMPORARY_LOCAL; tok_it++; goto expect_temporary; } else if (cur_sym == SYMBOL_TEMPORARY) { table_type = statements::TABLE_TYPE_TEMPORARY_GLOBAL; tok_it++; } exp_sym = SYMBOL_TABLE; goto next_token; SQLTOAST_UNREACHABLE(); expect_temporary: // We get here if we successfully matched CREATE followed by either the // GLOBAL or LOCAL symbol. If this is the case, we expect to find the // TEMPORARY keyword followed by the TABLE keyword. tok_it = ctx.skip_comments(tok_it); if (tok_it == ctx.tokens.end()) goto err_expect_temporary; cur_sym = (*tok_it).symbol; if (cur_sym != SYMBOL_TEMPORARY) goto err_expect_temporary; tok_it = ctx.skip_comments(++tok_it); if (tok_it == ctx.tokens.end()) goto err_expect_table; cur_sym = (*tok_it).symbol; if (cur_sym != SYMBOL_TABLE) goto err_expect_table; tok_it++; goto expect_table_name; SQLTOAST_UNREACHABLE(); err_expect_temporary: { parse_position_t err_pos = (*(tok_it)).start; std::stringstream estr; if (tok_it == ctx.tokens.end()) { estr << "Expected TEMPORARY after CREATE {GLOBAL | LOCAL} but found EOS"; } else { cur_sym = (*tok_it).symbol; estr << "Expected TEMPORARY after CREATE {GLOBAL | LOCAL} but found " << symbol_map::to_string(cur_sym); } estr << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); err_expect_table: { parse_position_t err_pos = (*(tok_it)).start; std::stringstream estr; if (tok_it == ctx.tokens.end()) { estr << "Expected TABLE after CREATE {GLOBAL | LOCAL} TEMPORARY but found EOS"; } else { cur_sym = (*tok_it).symbol; estr << "Expected TABLE after CREATE {GLOBAL | LOCAL} TEMPORARY but found " << symbol_map::to_string(cur_sym); } estr << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); expect_table_name: // We get here after successfully finding CREATE followed by the TABLE // symbol (after optionally processing the table type modifier). We now // need to find an identifier tok_it = ctx.skip_comments(tok_it); cur_sym = (*tok_it).symbol; if (cur_sym == SYMBOL_IDENTIFIER) { tok_ident = tok_it++; goto expect_column_list; } goto err_expect_identifier; SQLTOAST_UNREACHABLE(); err_expect_identifier: { parse_position_t err_pos = (*(tok_it)).start; std::stringstream estr; if (tok_it == ctx.tokens.end()) { estr << "Expected <identifier> after CREATE TABLE but found EOS"; } else { cur_sym = (*tok_it).symbol; estr << "Expected <identifier> after CREATE TABLE keyword but found " << symbol_map::to_string(cur_sym); } estr << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); expect_column_list: // We get here after successfully finding the CREATE ... TABLE <table name> // part of the statement. We now expect to find the <table element // list> clause tok_it = ctx.skip_comments(tok_it); cur_sym = (*tok_it).symbol; if (cur_sym == SYMBOL_LPAREN) { tok_it++; goto expect_column_list_element; } goto err_expect_lparen; SQLTOAST_UNREACHABLE(); err_expect_lparen: { parse_position_t err_pos = (*(tok_it)).start; std::stringstream estr; if (tok_it == ctx.tokens.end()) { estr << "Expected opening '(' after CREATE TABLE <table name> but found EOS"; } else { cur_sym = (*tok_it).symbol; estr << "Expected '(' after CREATE TABLE <table name> but found " << symbol_map::to_string(cur_sym); } estr << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); expect_column_list_element: // We get here after finding the LPAREN opening the <table element // list> clause. Now we expect to find one or more column or constraint // definitions tok_it = ctx.skip_comments(tok_it); // TODO(jaypipes): Parse the column definitions... cur_sym = (*tok_it).symbol; if (cur_sym == SYMBOL_RPAREN) { tok_it++; goto statement_ending; } goto err_expect_rparen; SQLTOAST_UNREACHABLE(); err_expect_rparen: { parse_position_t err_pos = (*(tok_it)).start; std::stringstream estr; if (tok_it == ctx.tokens.end()) { estr << "Expected closing ')' after CREATE TABLE <table name> but found EOS"; } else { cur_sym = (*tok_it).symbol; estr << "Expected closing ')' after CREATE TABLE <table name> but found " << symbol_map::to_string(cur_sym); } estr << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); statement_ending: // We get here if we have already successfully processed the CREATE // TABLE statement and are expecting EOS or SEMICOLON as the next // non-comment token tok_it = ctx.skip_comments(tok_it); if (tok_it == ctx.tokens.end()) { goto push_statement; } cur_sym = (*tok_it).symbol; if (cur_sym == SYMBOL_SEMICOLON) { // skip-consume the semicolon token tok_it++; goto push_statement; } { parse_position_t err_pos = (*tok_it).start; std::stringstream estr; estr << "Expected EOS or SEMICOLON but found " << symbol_map::to_string(cur_sym) << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); push_statement: { ctx.trim_to(tok_it); if (ctx.opts.disable_statement_construction) return true; identifier_t table_ident((*tok_ident).start, (*tok_ident).end); auto stmt_p = std::make_unique<statements::create_table_t>(table_type, table_ident); ctx.result.statements.emplace_back(std::move(stmt_p)); return true; } eos: if (exp_sym == SYMBOL_CREATE || exp_sym == SYMBOL_TABLE) { // Reached the end of the token stack and never found the // CREATE TABLE so just return false return false; } { // Reached the end of the token stream after already finding the // CREATE and TABLE symbols. Return a syntax error. parse_position_t err_pos = (*tok_it).start; std::stringstream estr; estr << "Expected <table_name_clause> but found EOS"; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); next_token: tok_it = ctx.skip_comments(tok_it); if (tok_it == ctx.tokens.end()) { goto eos; } cur_sym = (*tok_it).symbol; tok_it++; switch (cur_sym) { case SYMBOL_CREATE: if (exp_sym == SYMBOL_CREATE) { goto table_kw_or_table_type; } goto next_token; case SYMBOL_TABLE: if (exp_sym == SYMBOL_TABLE) { goto expect_table_name; } goto next_token; default: return false; } SQLTOAST_UNREACHABLE(); } } // namespace sqltoast <commit_msg>Quick cleanup of open/close table element list states<commit_after>/* * Use and distribution licensed under the Apache license version 2. * * See the COPYING file in the root project directory for full text. */ #include <iostream> #include <cctype> #include <sstream> #include "parser/statements/create_table.h" #include "parser/error.h" #include "parser/token.h" #include "statements/create_table.h" namespace sqltoast { // // The CREATE TABLE statement follows this EBNF form for the following SQL // dialects: // // * SQL_DIALECT_ANSI_1992 // // <table definition> ::= // CREATE [{GLOBAL|LOCAL} TEMPORARY] TABLE <table name> // <table element list> // [ON COMMIT {DELETE|PRESERVE} ROWS] // bool parse_create_table(parse_context_t& ctx) { tokens_t::iterator tok_it = ctx.tokens.begin(); tokens_t::iterator tok_ident = ctx.tokens.end(); symbol_t exp_sym = SYMBOL_CREATE; symbol_t cur_sym = (*tok_it).symbol; statements::table_type_t table_type = statements::TABLE_TYPE_NORMAL; goto next_token; // BEGIN STATE MACHINE table_kw_or_table_type: // We get here after successfully finding the CREATE symbol. We can // either match the table keyword or the table type clause tok_it = ctx.skip_comments(tok_it); cur_sym = (*tok_it).symbol; if (cur_sym == SYMBOL_GLOBAL) { table_type = statements::TABLE_TYPE_TEMPORARY_GLOBAL; tok_it++; goto expect_temporary; } else if (cur_sym == SYMBOL_LOCAL) { table_type = statements::TABLE_TYPE_TEMPORARY_LOCAL; tok_it++; goto expect_temporary; } else if (cur_sym == SYMBOL_TEMPORARY) { table_type = statements::TABLE_TYPE_TEMPORARY_GLOBAL; tok_it++; } exp_sym = SYMBOL_TABLE; goto next_token; SQLTOAST_UNREACHABLE(); expect_temporary: // We get here if we successfully matched CREATE followed by either the // GLOBAL or LOCAL symbol. If this is the case, we expect to find the // TEMPORARY keyword followed by the TABLE keyword. tok_it = ctx.skip_comments(tok_it); if (tok_it == ctx.tokens.end()) goto err_expect_temporary; cur_sym = (*tok_it).symbol; if (cur_sym != SYMBOL_TEMPORARY) goto err_expect_temporary; tok_it = ctx.skip_comments(++tok_it); if (tok_it == ctx.tokens.end()) goto err_expect_table; cur_sym = (*tok_it).symbol; if (cur_sym != SYMBOL_TABLE) goto err_expect_table; tok_it++; goto expect_table_name; SQLTOAST_UNREACHABLE(); err_expect_temporary: { parse_position_t err_pos = (*(tok_it)).start; std::stringstream estr; if (tok_it == ctx.tokens.end()) { estr << "Expected TEMPORARY after CREATE {GLOBAL | LOCAL} but found EOS"; } else { cur_sym = (*tok_it).symbol; estr << "Expected TEMPORARY after CREATE {GLOBAL | LOCAL} but found " << symbol_map::to_string(cur_sym); } estr << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); err_expect_table: { parse_position_t err_pos = (*(tok_it)).start; std::stringstream estr; if (tok_it == ctx.tokens.end()) { estr << "Expected TABLE after CREATE {GLOBAL | LOCAL} TEMPORARY but found EOS"; } else { cur_sym = (*tok_it).symbol; estr << "Expected TABLE after CREATE {GLOBAL | LOCAL} TEMPORARY but found " << symbol_map::to_string(cur_sym); } estr << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); expect_table_name: // We get here after successfully finding CREATE followed by the TABLE // symbol (after optionally processing the table type modifier). We now // need to find an identifier tok_it = ctx.skip_comments(tok_it); cur_sym = (*tok_it).symbol; if (cur_sym == SYMBOL_IDENTIFIER) { tok_ident = tok_it++; goto expect_column_list_open; } goto err_expect_identifier; SQLTOAST_UNREACHABLE(); err_expect_identifier: { parse_position_t err_pos = (*(tok_it)).start; std::stringstream estr; if (tok_it == ctx.tokens.end()) { estr << "Expected <identifier> after CREATE TABLE but found EOS"; } else { cur_sym = (*tok_it).symbol; estr << "Expected <identifier> after CREATE TABLE keyword but found " << symbol_map::to_string(cur_sym); } estr << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); expect_column_list_open: // We get here after successfully finding the CREATE ... TABLE <table name> // part of the statement. We now expect to find the <table element // list> clause tok_it = ctx.skip_comments(tok_it); cur_sym = (*tok_it).symbol; if (cur_sym == SYMBOL_LPAREN) { tok_it++; goto expect_column_list_element; } goto err_expect_lparen; SQLTOAST_UNREACHABLE(); err_expect_lparen: { parse_position_t err_pos = (*(tok_it)).start; std::stringstream estr; if (tok_it == ctx.tokens.end()) { estr << "Expected opening '(' after CREATE TABLE <table name> but found EOS"; } else { cur_sym = (*tok_it).symbol; estr << "Expected '(' after CREATE TABLE <table name> but found " << symbol_map::to_string(cur_sym); } estr << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); expect_column_list_element: // We get here after finding the LPAREN opening the <table element // list> clause. Now we expect to find one or more column or constraint // definitions tok_it = ctx.skip_comments(tok_it); // TODO(jaypipes): Parse the column definitions... goto expect_column_list_close; SQLTOAST_UNREACHABLE(); expect_column_list_close: // We get here after successfully parsing the <table element list> // column/constraint definitions and are now expecting the closing // RPAREN to indicate the end of the <table element list> tok_it = ctx.skip_comments(tok_it); cur_sym = (*tok_it).symbol; if (cur_sym == SYMBOL_RPAREN) { tok_it++; goto statement_ending; } goto err_expect_rparen; SQLTOAST_UNREACHABLE(); err_expect_rparen: { parse_position_t err_pos = (*(tok_it)).start; std::stringstream estr; if (tok_it == ctx.tokens.end()) { estr << "Expected closing ')' after CREATE TABLE <table name> but found EOS"; } else { cur_sym = (*tok_it).symbol; estr << "Expected closing ')' after CREATE TABLE <table name> but found " << symbol_map::to_string(cur_sym); } estr << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); statement_ending: // We get here if we have already successfully processed the CREATE // TABLE statement and are expecting EOS or SEMICOLON as the next // non-comment token tok_it = ctx.skip_comments(tok_it); if (tok_it == ctx.tokens.end()) { goto push_statement; } cur_sym = (*tok_it).symbol; if (cur_sym == SYMBOL_SEMICOLON) { // skip-consume the semicolon token tok_it++; goto push_statement; } { parse_position_t err_pos = (*tok_it).start; std::stringstream estr; estr << "Expected EOS or SEMICOLON but found " << symbol_map::to_string(cur_sym) << std::endl; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); push_statement: { ctx.trim_to(tok_it); if (ctx.opts.disable_statement_construction) return true; identifier_t table_ident((*tok_ident).start, (*tok_ident).end); auto stmt_p = std::make_unique<statements::create_table_t>(table_type, table_ident); ctx.result.statements.emplace_back(std::move(stmt_p)); return true; } eos: if (exp_sym == SYMBOL_CREATE || exp_sym == SYMBOL_TABLE) { // Reached the end of the token stack and never found the // CREATE TABLE so just return false return false; } { // Reached the end of the token stream after already finding the // CREATE and TABLE symbols. Return a syntax error. parse_position_t err_pos = (*tok_it).start; std::stringstream estr; estr << "Expected <table_name_clause> but found EOS"; create_syntax_error_marker(ctx, estr, err_pos); return false; } SQLTOAST_UNREACHABLE(); next_token: tok_it = ctx.skip_comments(tok_it); if (tok_it == ctx.tokens.end()) { goto eos; } cur_sym = (*tok_it).symbol; tok_it++; switch (cur_sym) { case SYMBOL_CREATE: if (exp_sym == SYMBOL_CREATE) { goto table_kw_or_table_type; } goto next_token; case SYMBOL_TABLE: if (exp_sym == SYMBOL_TABLE) { goto expect_table_name; } goto next_token; default: return false; } SQLTOAST_UNREACHABLE(); } } // namespace sqltoast <|endoftext|>
<commit_before>#ifndef VSMC_HELPER_ADAPTER_HPP #define VSMC_HELPER_ADAPTER_HPP namespace vsmc { template <typename T, template <typename, typename> class InitializeImpl> class InitializeAdapter : public InitializeImpl<T, InitializeAdapter<T, InitializeImpl> > { public : typedef InitializeImpl<T, InitializeAdapter<T, InitializeImpl> > initialize_impl_type; typedef cxx11::function<unsigned (SingleParticle<T>)> initialize_state_type; typedef cxx11::function<void (Particle<T> &, void *)> initialize_param_type; typedef cxx11::function<void (Particle<T> &)> pre_processor_type; typedef cxx11::function<void (Particle<T> &)> post_processor_type; InitializeAdapter (const initialize_state_type &init_state, const initialize_param_type &init_param = VSMC_NULLPTR, const pre_processor_type &pre = VSMC_NULLPTR, const post_processor_type &post = VSMC_NULLPTR) : initialize_state_(init_state), initialize_param_(init_param), pre_processor_(pre), post_processor_(post) {} unsigned initialize_state (SingleParticle<T> part) { return initialize_state_(part); } void initialize_param (Particle<T> &particle, void *param) { if (bool(initialize_param_)) initialize_param_(particle, param); } void pre_processor (Particle<T> &particle) { if (bool(pre_processor_)) pre_processor_(particle); } void post_processor (Particle<T> &particle) { if (bool(post_processor_)) post_processor_(particle); } private : initialize_state_type initialize_state_; initialize_param_type initialize_param_; pre_processor_type pre_processor_; post_processor_type post_processor_; }; // class InitializeAdapter template <typename T, template <typename, typename> class MoveImpl> class MoveAdapter : public MoveImpl<T, MoveAdapter<T, MoveImpl> > { public : typedef MoveImpl<T, MoveAdapter<T, MoveImpl> > move_impl_type; typedef cxx11::function<unsigned (unsigned, SingleParticle<T>)> move_state_type; typedef cxx11::function<void (unsigned, Particle<T> &)> pre_processor_type; typedef cxx11::function<void (unsigned, Particle<T> &)> post_processor_type; MoveAdapter (const move_state_type &move_state, const pre_processor_type &pre = VSMC_NULLPTR, const post_processor_type &post = VSMC_NULLPTR) : move_state_(move_state), pre_processor_(pre), post_processor_(post) {} unsigned move_state (unsigned iter, SingleParticle<T> part) { return move_state_(iter, part); } void pre_processor (unsigned iter, Particle<T> &particle) { if (bool(pre_processor_)) pre_processor_(iter, particle); } void post_processor (unsigned iter, Particle<T> &particle) { if (bool(post_processor_)) post_processor_(iter, particle); } private : move_state_type move_state_; pre_processor_type pre_processor_; post_processor_type post_processor_; }; // class MoveAdapter template <typename T, template <typename, typename> class MonitorEvalImpl> class MonitorEvalAdapter : public MonitorEvalImpl<T, MonitorEvalAdapter<T, MonitorEvalImpl> > { public : typedef MonitorEvalImpl<T, MonitorEvalAdapter<T, MonitorEvalImpl> > monitor_eval_impl_type; typedef cxx11::function< void (unsigned, unsigned, ConstSingleParticle<T>, double *)> monitor_state_type; typedef cxx11::function<void (unsigned, const Particle<T> &)> pre_processor_type; typedef cxx11::function<void (unsigned, const Particle<T> &)> post_processor_type; MonitorEvalAdapter (const monitor_state_type &monitor_state, const pre_processor_type &pre = VSMC_NULLPTR, const post_processor_type &post = VSMC_NULLPTR) : monitor_state_(monitor_state), pre_processor_(pre), post_processor_(post) {} void monitor_state (unsigned iter, unsigned dim, ConstSingleParticle<T> part, double *res) { monitor_state_(iter, dim, part, res); } void pre_processor (unsigned iter, const Particle<T> &particle) { if (bool(pre_processor_)) pre_processor_(iter, particle); } void post_processor (unsigned iter, const Particle<T> &particle) { if (bool(post_processor_)) post_processor_(iter, particle); } private : monitor_state_type monitor_state_; pre_processor_type pre_processor_; post_processor_type post_processor_; }; // class MonitorEvalAdapter template <typename T, template <typename, typename> class PathEvalImpl> class PathEvalAdapter : public PathEvalImpl<T, PathEvalAdapter<T, PathEvalImpl> > { public : typedef PathEvalImpl<T, PathEvalAdapter<T, PathEvalImpl> > path_eval_impl_type; typedef cxx11::function<double (unsigned, ConstSingleParticle<T>)> path_state_type; typedef cxx11::function<double (unsigned, const Particle<T> &)> path_width_type; typedef cxx11::function<void (unsigned, const Particle<T> &)> pre_processor_type; typedef cxx11::function<void (unsigned, const Particle<T> &)> post_processor_type; PathEvalAdapter (const path_state_type &path_state, const path_width_type &path_width, const pre_processor_type &pre = VSMC_NULLPTR, const post_processor_type &post = VSMC_NULLPTR) : path_state_(path_state), path_width_(path_width), pre_processor_(pre), post_processor_(post) {} double path_state (unsigned iter, ConstSingleParticle<T> part) { return path_state_(iter, part); } double path_width (unsigned iter, const Particle<T> &particle) { return path_width_(iter, particle); } void pre_processor (unsigned iter, const Particle<T> &particle) { if (bool(pre_processor)) pre_processor(iter, particle); } void post_processor (unsigned iter, const Particle<T> &particle) { if (bool(post_processor)) post_processor(iter, particle); } private : path_state_type path_state_; path_width_type path_width_; pre_processor_type pre_processor_; post_processor_type post_processor_; }; // class PathEvalAdapter } // namespace vsmc #endif // VSMC_HELPER_ADAPTER_HPP <commit_msg>adapter.hpp include common.hpp<commit_after>#ifndef VSMC_HELPER_ADAPTER_HPP #define VSMC_HELPER_ADAPTER_HPP #include <vsmc/internal/common.hpp> namespace vsmc { template <typename T, template <typename, typename> class InitializeImpl> class InitializeAdapter : public InitializeImpl<T, InitializeAdapter<T, InitializeImpl> > { public : typedef InitializeImpl<T, InitializeAdapter<T, InitializeImpl> > initialize_impl_type; typedef cxx11::function<unsigned (SingleParticle<T>)> initialize_state_type; typedef cxx11::function<void (Particle<T> &, void *)> initialize_param_type; typedef cxx11::function<void (Particle<T> &)> pre_processor_type; typedef cxx11::function<void (Particle<T> &)> post_processor_type; InitializeAdapter (const initialize_state_type &init_state, const initialize_param_type &init_param = VSMC_NULLPTR, const pre_processor_type &pre = VSMC_NULLPTR, const post_processor_type &post = VSMC_NULLPTR) : initialize_state_(init_state), initialize_param_(init_param), pre_processor_(pre), post_processor_(post) {} unsigned initialize_state (SingleParticle<T> part) { return initialize_state_(part); } void initialize_param (Particle<T> &particle, void *param) { if (bool(initialize_param_)) initialize_param_(particle, param); } void pre_processor (Particle<T> &particle) { if (bool(pre_processor_)) pre_processor_(particle); } void post_processor (Particle<T> &particle) { if (bool(post_processor_)) post_processor_(particle); } private : initialize_state_type initialize_state_; initialize_param_type initialize_param_; pre_processor_type pre_processor_; post_processor_type post_processor_; }; // class InitializeAdapter template <typename T, template <typename, typename> class MoveImpl> class MoveAdapter : public MoveImpl<T, MoveAdapter<T, MoveImpl> > { public : typedef MoveImpl<T, MoveAdapter<T, MoveImpl> > move_impl_type; typedef cxx11::function<unsigned (unsigned, SingleParticle<T>)> move_state_type; typedef cxx11::function<void (unsigned, Particle<T> &)> pre_processor_type; typedef cxx11::function<void (unsigned, Particle<T> &)> post_processor_type; MoveAdapter (const move_state_type &move_state, const pre_processor_type &pre = VSMC_NULLPTR, const post_processor_type &post = VSMC_NULLPTR) : move_state_(move_state), pre_processor_(pre), post_processor_(post) {} unsigned move_state (unsigned iter, SingleParticle<T> part) { return move_state_(iter, part); } void pre_processor (unsigned iter, Particle<T> &particle) { if (bool(pre_processor_)) pre_processor_(iter, particle); } void post_processor (unsigned iter, Particle<T> &particle) { if (bool(post_processor_)) post_processor_(iter, particle); } private : move_state_type move_state_; pre_processor_type pre_processor_; post_processor_type post_processor_; }; // class MoveAdapter template <typename T, template <typename, typename> class MonitorEvalImpl> class MonitorEvalAdapter : public MonitorEvalImpl<T, MonitorEvalAdapter<T, MonitorEvalImpl> > { public : typedef MonitorEvalImpl<T, MonitorEvalAdapter<T, MonitorEvalImpl> > monitor_eval_impl_type; typedef cxx11::function< void (unsigned, unsigned, ConstSingleParticle<T>, double *)> monitor_state_type; typedef cxx11::function<void (unsigned, const Particle<T> &)> pre_processor_type; typedef cxx11::function<void (unsigned, const Particle<T> &)> post_processor_type; MonitorEvalAdapter (const monitor_state_type &monitor_state, const pre_processor_type &pre = VSMC_NULLPTR, const post_processor_type &post = VSMC_NULLPTR) : monitor_state_(monitor_state), pre_processor_(pre), post_processor_(post) {} void monitor_state (unsigned iter, unsigned dim, ConstSingleParticle<T> part, double *res) { monitor_state_(iter, dim, part, res); } void pre_processor (unsigned iter, const Particle<T> &particle) { if (bool(pre_processor_)) pre_processor_(iter, particle); } void post_processor (unsigned iter, const Particle<T> &particle) { if (bool(post_processor_)) post_processor_(iter, particle); } private : monitor_state_type monitor_state_; pre_processor_type pre_processor_; post_processor_type post_processor_; }; // class MonitorEvalAdapter template <typename T, template <typename, typename> class PathEvalImpl> class PathEvalAdapter : public PathEvalImpl<T, PathEvalAdapter<T, PathEvalImpl> > { public : typedef PathEvalImpl<T, PathEvalAdapter<T, PathEvalImpl> > path_eval_impl_type; typedef cxx11::function<double (unsigned, ConstSingleParticle<T>)> path_state_type; typedef cxx11::function<double (unsigned, const Particle<T> &)> path_width_type; typedef cxx11::function<void (unsigned, const Particle<T> &)> pre_processor_type; typedef cxx11::function<void (unsigned, const Particle<T> &)> post_processor_type; PathEvalAdapter (const path_state_type &path_state, const path_width_type &path_width, const pre_processor_type &pre = VSMC_NULLPTR, const post_processor_type &post = VSMC_NULLPTR) : path_state_(path_state), path_width_(path_width), pre_processor_(pre), post_processor_(post) {} double path_state (unsigned iter, ConstSingleParticle<T> part) { return path_state_(iter, part); } double path_width (unsigned iter, const Particle<T> &particle) { return path_width_(iter, particle); } void pre_processor (unsigned iter, const Particle<T> &particle) { if (bool(pre_processor)) pre_processor(iter, particle); } void post_processor (unsigned iter, const Particle<T> &particle) { if (bool(post_processor)) post_processor(iter, particle); } private : path_state_type path_state_; path_width_type path_width_; pre_processor_type pre_processor_; post_processor_type post_processor_; }; // class PathEvalAdapter } // namespace vsmc #endif // VSMC_HELPER_ADAPTER_HPP <|endoftext|>
<commit_before>#include <cli/Session.h> #include <cli/CommandLine.h> #include <cli/PosixStreams.h> #include <cli/Tokenizer.h> #include <mtp/make_function.h> #include <stdio.h> namespace cli { Session::Session(const mtp::DevicePtr &device): _device(device), _session(_device->OpenSession(1)), _gdi(_session->GetDeviceInfo()), _cd(mtp::Session::Root), _running(true) { using namespace mtp; using namespace std::placeholders; printf("%s\n", _gdi.VendorExtensionDesc.c_str()); printf("%s ", _gdi.Manufacturer.c_str()); printf("%s ", _gdi.Model.c_str()); printf("%s ", _gdi.DeviceVersion.c_str()); //printf("%s", _gdi.SerialNumber.c_str()); printf("\n"); printf("supported op codes: "); for(OperationCode code : _gdi.OperationsSupported) { printf("%04x ", (unsigned)code); } printf("\n"); printf("supported properties: "); for(u16 code : _gdi.DevicePropertiesSupported) { printf("%04x ", (unsigned)code); } printf("\n"); AddCommand("help", "shows this help", make_function([this]() -> void { Help(); })); AddCommand("ls", "lists current directory", make_function([this]() -> void { List(); })); AddCommand("ls", "<path> lists objects in <path>", make_function([this](const Path &path) -> void { List(path); })); AddCommand("put", "<file> uploads file", make_function([this](const LocalPath &path) -> void { Put(path); })); AddCommand("put", "put <file> <dir> uploads file to directory", make_function([this](const LocalPath &path, const Path &dst) -> void { Put(path, dst); })); AddCommand("get", "<file> downloads file", make_function([this](const Path &path) -> void { Get(path); })); AddCommand("get", "<file> <dst> downloads file to <dst>", make_function([this](const Path &path, const LocalPath &dst) -> void { Get(dst, path); })); AddCommand("quit", "quits program", make_function([this]() -> void { Quit(); })); AddCommand("exit", "exits program", make_function([this]() -> void { Quit(); })); AddCommand("cd", "<path> change directory to <path>", make_function([this](const Path &path) -> void { ChangeDirectory(path); })); AddCommand("rm", "<path> removes object (WARNING: RECURSIVE, be careful!)", make_function([this](const LocalPath &path) -> void { Delete(path); })); AddCommand("mkdir", "<path> makes directory", make_function([this](const Path &path) -> void { MakeDirectory(path); })); AddCommand("storage-list", "shows available MTP storages", make_function([this]() -> void { ListStorages(); })); AddCommand("device-properties", "shows device's MTP properties", make_function([this]() -> void { ListDeviceProperties(); })); } char ** Session::CompletionCallback(const char *text, int start, int end) { if (start == 0) { char **comp = static_cast<char **>(calloc(sizeof(char *), _commands.size() + 1)); auto it = _commands.begin(); size_t i = 0, n = _commands.size(); for(; n--; ++it) { if (end != 0 && it->first.compare(0, end, text) != 0) continue; comp[i++] = strdup(it->first.c_str()); } if (i == 0) //readline silently dereference matches[0] { free(comp); comp = NULL; }; return comp; } return NULL; } void Session::ProcessCommand(const std::string &input) { Tokens tokens; Tokenizer(input, tokens); if (!tokens.empty()) ProcessCommand(std::move(tokens)); } void Session::ProcessCommand(Tokens && tokens_) { Tokens tokens(tokens_); if (tokens.empty()) throw std::runtime_error("no token passed to ProcessCommand"); std::string cmdName = tokens.front(); tokens.pop_front(); auto cmd = _commands.find(cmdName); if (cmd == _commands.end()) throw std::runtime_error("invalid command " + cmdName); cmd->second->Execute(tokens); } void Session::InteractiveInput() { using namespace mtp; std::string prompt(_gdi.Manufacturer + " " + _gdi.Model + "> "), input; cli::CommandLine::Get().SetCallback([this](const char *text, int start, int end) -> char ** { return CompletionCallback(text, start, end); }); while (cli::CommandLine::Get().ReadLine(prompt, input)) { try { ProcessCommand(input); if (!_running) //do not put newline return; } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } printf("\n"); } mtp::u32 Session::Resolve(const Path &path) { mtp::u32 id = _cd; for(size_t p = 0; p < path.size(); ) { size_t next = path.find('/', p); if (next == path.npos) next = path.size(); std::string entity(path.substr(p, next - p)); if (entity == ".") { } else if (entity == "..") { id = _session->GetObjectIntegerProperty(id, mtp::ObjectProperty::ParentObject); if (id == 0) id = mtp::Session::Root; } else { auto objectList = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, id); bool found = false; for(auto object : objectList.ObjectHandles) { std::string name = _session->GetObjectStringProperty(object, mtp::ObjectProperty::ObjectFilename); if (name == entity) { id = object; found = true; break; } } if (!found) throw std::runtime_error("could not find " + entity + " in path " + path.substr(0, p)); } p = next + 1; } return id; } void Session::List(mtp::u32 parent) { using namespace mtp; msg::ObjectHandles handles = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parent); for(u32 objectId : handles.ObjectHandles) { try { msg::ObjectInfo info = _session->GetObjectInfo(objectId); printf("%-10u %04hx %10u %s %ux%u, %s\n", objectId, info.ObjectFormat, info.ObjectCompressedSize, info.Filename.c_str(), info.ImagePixWidth, info.ImagePixHeight, info.CaptureDate.c_str()); } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } } void Session::ListStorages() { using namespace mtp; msg::StorageIDs list = _session->GetStorageIDs(); for(size_t i = 0; i < list.StorageIDs.size(); ++i) { msg::StorageInfo si = _session->GetStorageInfo(list.StorageIDs[i]); printf("%08d volume: %s, description: %s\n", list.StorageIDs[i], si.VolumeLabel.c_str(), si.StorageDescription.c_str()); } } void Session::Help() { printf("Available commands are:\n"); for(auto i : _commands) { printf("\t%-20s %s\n", i.first.c_str(), i.second->GetHelpString().c_str()); } } void Session::Get(const LocalPath &dst, mtp::u32 srcId) { _session->GetObject(srcId, std::make_shared<ObjectOutputStream>(dst)); } void Session::Get(mtp::u32 srcId) { auto info = _session->GetObjectInfo(srcId); printf("filename = %s\n", info.Filename.c_str()); Get(LocalPath(info.Filename), srcId); } void Session::Put(mtp::u32 parentId, const LocalPath &src) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = src; oi.ObjectFormat = ObjectFormatFromFilename(src); std::shared_ptr<ObjectInputStream> objectInput(new ObjectInputStream(src)); oi.SetSize(objectInput->GetSize()); auto noi = _session->SendObjectInfo(oi, 0, parentId); printf("new object id = %u\n", noi.ObjectId); _session->SendObject(objectInput); printf("done\n"); } void Session::MakeDirectory(mtp::u32 parentId, const std::string & name) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = name; oi.ObjectFormat = ObjectFormat::Association; _session->SendObjectInfo(oi, 0, parentId); } void Session::Delete(mtp::u32 id) { _session->DeleteObject(id); } void Session::ListProperties(mtp::u32 id) { auto ops = _session->GetObjectPropsSupported(id); printf("properties supported: "); for(mtp::u16 prop: ops.ObjectPropCodes) { printf("%02x ", prop); } printf("\n"); } void Session::ListDeviceProperties() { using namespace mtp; for(u16 code : _gdi.DevicePropertiesSupported) { if ((code & 0xff00) != 0x5000 ) continue; printf("property code: %04x\n", (unsigned)code); ByteArray data = _session->GetDeviceProperty((mtp::DeviceProperty)code); HexDump("value", data); } } } <commit_msg>Revert "Revert "use tokenizer for completion""<commit_after>#include <cli/Session.h> #include <cli/CommandLine.h> #include <cli/PosixStreams.h> #include <cli/Tokenizer.h> #include <mtp/make_function.h> #include <stdio.h> namespace cli { Session::Session(const mtp::DevicePtr &device): _device(device), _session(_device->OpenSession(1)), _gdi(_session->GetDeviceInfo()), _cd(mtp::Session::Root), _running(true) { using namespace mtp; using namespace std::placeholders; printf("%s\n", _gdi.VendorExtensionDesc.c_str()); printf("%s ", _gdi.Manufacturer.c_str()); printf("%s ", _gdi.Model.c_str()); printf("%s ", _gdi.DeviceVersion.c_str()); //printf("%s", _gdi.SerialNumber.c_str()); printf("\n"); printf("supported op codes: "); for(OperationCode code : _gdi.OperationsSupported) { printf("%04x ", (unsigned)code); } printf("\n"); printf("supported properties: "); for(u16 code : _gdi.DevicePropertiesSupported) { printf("%04x ", (unsigned)code); } printf("\n"); AddCommand("help", "shows this help", make_function([this]() -> void { Help(); })); AddCommand("ls", "lists current directory", make_function([this]() -> void { List(); })); AddCommand("ls", "<path> lists objects in <path>", make_function([this](const Path &path) -> void { List(path); })); AddCommand("put", "<file> uploads file", make_function([this](const LocalPath &path) -> void { Put(path); })); AddCommand("put", "put <file> <dir> uploads file to directory", make_function([this](const LocalPath &path, const Path &dst) -> void { Put(path, dst); })); AddCommand("get", "<file> downloads file", make_function([this](const Path &path) -> void { Get(path); })); AddCommand("get", "<file> <dst> downloads file to <dst>", make_function([this](const Path &path, const LocalPath &dst) -> void { Get(dst, path); })); AddCommand("quit", "quits program", make_function([this]() -> void { Quit(); })); AddCommand("exit", "exits program", make_function([this]() -> void { Quit(); })); AddCommand("cd", "<path> change directory to <path>", make_function([this](const Path &path) -> void { ChangeDirectory(path); })); AddCommand("rm", "<path> removes object (WARNING: RECURSIVE, be careful!)", make_function([this](const LocalPath &path) -> void { Delete(path); })); AddCommand("mkdir", "<path> makes directory", make_function([this](const Path &path) -> void { MakeDirectory(path); })); AddCommand("storage-list", "shows available MTP storages", make_function([this]() -> void { ListStorages(); })); AddCommand("device-properties", "shows device's MTP properties", make_function([this]() -> void { ListDeviceProperties(); })); } char ** Session::CompletionCallback(const char *text, int start, int end) { Tokens tokens; Tokenizer(text, tokens); if (tokens.size() < 2) //0 or 1 { std::string command = !tokens.empty()? tokens.back(): std::string(); char **comp = static_cast<char **>(calloc(sizeof(char *), _commands.size() + 1)); auto it = _commands.begin(); size_t i = 0, n = _commands.size(); for(; n--; ++it) { if (end != 0 && it->first.compare(0, end, command) != 0) continue; comp[i++] = strdup(it->first.c_str()); } if (i == 0) //readline silently dereference matches[0] { free(comp); comp = NULL; }; return comp; } else { //completion } return NULL; } void Session::ProcessCommand(const std::string &input) { Tokens tokens; Tokenizer(input, tokens); if (!tokens.empty()) ProcessCommand(std::move(tokens)); } void Session::ProcessCommand(Tokens && tokens_) { Tokens tokens(tokens_); if (tokens.empty()) throw std::runtime_error("no token passed to ProcessCommand"); std::string cmdName = tokens.front(); tokens.pop_front(); auto cmd = _commands.find(cmdName); if (cmd == _commands.end()) throw std::runtime_error("invalid command " + cmdName); cmd->second->Execute(tokens); } void Session::InteractiveInput() { using namespace mtp; std::string prompt(_gdi.Manufacturer + " " + _gdi.Model + "> "), input; cli::CommandLine::Get().SetCallback([this](const char *text, int start, int end) -> char ** { return CompletionCallback(text, start, end); }); while (cli::CommandLine::Get().ReadLine(prompt, input)) { try { ProcessCommand(input); if (!_running) //do not put newline return; } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } printf("\n"); } mtp::u32 Session::Resolve(const Path &path) { mtp::u32 id = _cd; for(size_t p = 0; p < path.size(); ) { size_t next = path.find('/', p); if (next == path.npos) next = path.size(); std::string entity(path.substr(p, next - p)); if (entity == ".") { } else if (entity == "..") { id = _session->GetObjectIntegerProperty(id, mtp::ObjectProperty::ParentObject); if (id == 0) id = mtp::Session::Root; } else { auto objectList = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, id); bool found = false; for(auto object : objectList.ObjectHandles) { std::string name = _session->GetObjectStringProperty(object, mtp::ObjectProperty::ObjectFilename); if (name == entity) { id = object; found = true; break; } } if (!found) throw std::runtime_error("could not find " + entity + " in path " + path.substr(0, p)); } p = next + 1; } return id; } void Session::List(mtp::u32 parent) { using namespace mtp; msg::ObjectHandles handles = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parent); for(u32 objectId : handles.ObjectHandles) { try { msg::ObjectInfo info = _session->GetObjectInfo(objectId); printf("%-10u %04hx %10u %s %ux%u, %s\n", objectId, info.ObjectFormat, info.ObjectCompressedSize, info.Filename.c_str(), info.ImagePixWidth, info.ImagePixHeight, info.CaptureDate.c_str()); } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } } void Session::ListStorages() { using namespace mtp; msg::StorageIDs list = _session->GetStorageIDs(); for(size_t i = 0; i < list.StorageIDs.size(); ++i) { msg::StorageInfo si = _session->GetStorageInfo(list.StorageIDs[i]); printf("%08d volume: %s, description: %s\n", list.StorageIDs[i], si.VolumeLabel.c_str(), si.StorageDescription.c_str()); } } void Session::Help() { printf("Available commands are:\n"); for(auto i : _commands) { printf("\t%-20s %s\n", i.first.c_str(), i.second->GetHelpString().c_str()); } } void Session::Get(const LocalPath &dst, mtp::u32 srcId) { _session->GetObject(srcId, std::make_shared<ObjectOutputStream>(dst)); } void Session::Get(mtp::u32 srcId) { auto info = _session->GetObjectInfo(srcId); printf("filename = %s\n", info.Filename.c_str()); Get(LocalPath(info.Filename), srcId); } void Session::Put(mtp::u32 parentId, const LocalPath &src) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = src; oi.ObjectFormat = ObjectFormatFromFilename(src); std::shared_ptr<ObjectInputStream> objectInput(new ObjectInputStream(src)); oi.SetSize(objectInput->GetSize()); auto noi = _session->SendObjectInfo(oi, 0, parentId); printf("new object id = %u\n", noi.ObjectId); _session->SendObject(objectInput); printf("done\n"); } void Session::MakeDirectory(mtp::u32 parentId, const std::string & name) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = name; oi.ObjectFormat = ObjectFormat::Association; _session->SendObjectInfo(oi, 0, parentId); } void Session::Delete(mtp::u32 id) { _session->DeleteObject(id); } void Session::ListProperties(mtp::u32 id) { auto ops = _session->GetObjectPropsSupported(id); printf("properties supported: "); for(mtp::u16 prop: ops.ObjectPropCodes) { printf("%02x ", prop); } printf("\n"); } void Session::ListDeviceProperties() { using namespace mtp; for(u16 code : _gdi.DevicePropertiesSupported) { if ((code & 0xff00) != 0x5000 ) continue; printf("property code: %04x\n", (unsigned)code); ByteArray data = _session->GetDeviceProperty((mtp::DeviceProperty)code); HexDump("value", data); } } } <|endoftext|>
<commit_before>#pragma once #include <type_traits> namespace gcl::mp::type_traits { template <class T> struct is_template : std::false_type {}; template <class... T_args, template <class...> class T> struct is_template<T<T_args...>> : std::true_type {}; template <auto... values, template <auto...> class T> struct is_template<T<values...>> : std::true_type {}; template <class T> inline constexpr auto is_template_v = is_template<T>::value; template <typename T, typename = void> struct is_complete : std::false_type {}; template <typename T> struct is_complete<T, std::void_t<decltype(sizeof(T))>> : std::true_type {}; template <typename T> constexpr inline auto is_complete_v = is_complete<T>::value; template <class T_concrete, template <class...> class T> struct is_instance_of : std::false_type {}; template <template <class...> class T, class... T_args> struct is_instance_of<T<T_args...>, T> : std::true_type {}; template <class T_concrete, template <class...> class T> inline constexpr auto is_instance_of_v = is_instance_of<T_concrete, T>::value; template <class T, typename... Args> class is_brace_constructible { template <typename /*= void*/, typename U, typename... U_args> struct impl : std::false_type {}; template <typename U, typename... U_args> struct impl<std::void_t<decltype(U{std::declval<U_args>()...})>, U, U_args...> : std::true_type {}; public: constexpr inline static auto value = impl<std::void_t<>, T, Args...>::value; }; template <class T, typename... Args> constexpr inline auto is_brace_constructible_v = is_brace_constructible<T, Args...>::value; template <bool evaluation> using if_t = std::conditional_t<evaluation, std::true_type, std::false_type>; template <bool evaluation> constexpr inline auto if_v = std::conditional_t<evaluation, std::true_type, std::false_type>::value; template <template <typename> typename first_trait, template<typename> typename... traits> struct merge_traits { template <typename T> using type = typename merge_traits<traits...>::template type<first_trait<T>>; }; template <template <typename> typename first_trait> struct merge_traits<first_trait> { template <typename T> using type = first_trait<T>; }; } #include <bitset> #include <tuple> #include <array> namespace gcl::mp::type_traits { template <template <typename> class trait, typename... Ts> struct trait_result { constexpr static inline auto as_bitset_v = []() consteval { using bitset_type = std::bitset<sizeof...(Ts)>; using bitset_initializer_t = unsigned long long; bitset_initializer_t value{0}; return bitset_type{((value = (value << 1 | trait<Ts>::value)), ...)}; } (); // see gcl::mp::pack_traits::pack_arguments_as for other expansion/conversions template <template <typename...> class T> using as_t = T<typename trait<Ts>::type...>; template <template <typename...> class T> constexpr static inline auto as_v = T{trait<Ts>::value...}; using as_tuple_t = as_t<std::tuple>; constexpr static inline auto as_tuple_v = std::tuple{trait<Ts>::value...}; template <class Int = int> using as_integer_sequence = std::integer_sequence<Int, trait<Ts>::value...>; // constexpr static auto as_array_v = std::array{trait<Ts>::value...}; // OK with GCC 10.2 using as_array_t = std::array<std::tuple_element_t<0, decltype(std::tuple{trait<Ts>::value...})>, sizeof...(Ts)>; constexpr static inline auto as_array_v = as_array_t{trait<Ts>::value...}; }; } // tests namespace gcl::mp::type_traits::tests::is_template { static_assert(gcl::mp::type_traits::is_template_v<std::tuple<int, char>>); static_assert(gcl::mp::type_traits::is_template_v<std::string>); // std::basic_string<charT, allocator> static_assert(not gcl::mp::type_traits::is_template_v<int>); } namespace gcl::mp::type_traits::tests::is_complete { struct complete_type {}; struct incomplete_type; static_assert(gcl::mp::type_traits::is_complete_v<complete_type>); static_assert(gcl::mp::type_traits::is_complete_v<int>); static_assert(not gcl::mp::type_traits::is_complete_v<incomplete_type>); } namespace gcl::mp::type_traits::tests::is_instance_of { static_assert(gcl::mp::type_traits::is_instance_of_v<std::tuple<int, char>, std::tuple>); static_assert(not gcl::mp::type_traits::is_instance_of_v<std::tuple<int, char>, std::pair>); } namespace gcl::mp::type_traits::tests::is_brace_constructible_v { struct toto { int i; }; struct titi { explicit titi(int) {} }; static_assert(type_traits::is_brace_constructible_v<toto>); static_assert(type_traits::is_brace_constructible_v<toto, int>); static_assert(type_traits::is_brace_constructible_v<toto, char>); static_assert(not type_traits::is_brace_constructible_v<toto, char*>); static_assert(not type_traits::is_brace_constructible_v<titi>); static_assert(type_traits::is_brace_constructible_v<titi, int>); static_assert(type_traits::is_brace_constructible_v<titi, char>); static_assert(not type_traits::is_brace_constructible_v<titi, char*>); } namespace gcl::mp::type_traits::tests::if_t { static_assert(std::is_same_v<type_traits::if_t<true>, std::true_type>); static_assert(std::is_same_v<type_traits::if_t<false>, std::false_type>); static_assert(type_traits::if_v<true> == true); static_assert(type_traits::if_v<false> == false); } #if __cpp_concepts #include <concepts> namespace gcl::mp::type_traits::tests::if_t { // clang-format off template <typename T> concept is_red_colored = requires(T) { { T::color == decltype(T::color)::red } -> std::convertible_to<bool>; { type_traits::if_t<T::color == decltype(T::color)::red>{}} -> std::same_as<std::true_type>; }; enum colors { red, blue, green }; struct smthg_blue { constexpr static auto color = colors::blue; }; struct smthg_red { constexpr static auto color = colors::red; }; // clang-format on static_assert(not is_red_colored<smthg_blue>); static_assert(is_red_colored<smthg_red>); } #endif namespace gcl::mp::type_traits::tests::merge_traits { using remove_cv_and_ref = gcl::mp::type_traits::merge_traits<std::remove_reference_t, std::decay_t>; static_assert(std::is_same_v<int, remove_cv_and_ref::type<const int&&>>); } namespace gcl::mp::type_traits::tests::trait_results { template <typename T> using is_int = std::is_same<int, T>; using results = trait_result<is_int, char, int, bool>; // static_assert(decltype(results::as_bitset_v){2UL} == results::as_bitset_v); // std::bitset::operator== is not cx constexpr auto expected_result_as_bitset = decltype(results::as_bitset_v){2UL}; static_assert(expected_result_as_bitset[0] == results::as_bitset_v[0]); static_assert(expected_result_as_bitset[1] == results::as_bitset_v[1]); static_assert(expected_result_as_bitset[2] == results::as_bitset_v[2]); using results_as_tuple = results::as_t<std::tuple>; using results_as_tuple_value_type = std::decay_t<decltype(results::as_v<std::tuple>)>; #if not defined(__clang__) // See my Q on SO : // https://stackoverflow.com/questions/66821952/clang-error-implicit-instantiation-of-undefined-template-stdtuple-sizeauto/66822584 static_assert(std::tuple_size_v<results_as_tuple> == std::tuple_size_v<results_as_tuple_value_type>); // clang and clang-cl complain here using expected_result_type = std::tuple< std::false_type, std::true_type, std::false_type>; static_assert(std::is_same_v<results_as_tuple, expected_result_type>); using expected_result_value_type = std::tuple<bool, bool, bool>; static_assert(std::is_same_v<results_as_tuple_value_type, expected_result_value_type>); #endif using expected_result_as_tuple = std::tuple<std::false_type, std::true_type, std::false_type>; static_assert(std::is_same_v<results::as_t<std::tuple>, expected_result_as_tuple>); static_assert(std::is_same_v<results::as_integer_sequence<int>, std::integer_sequence<int, 0, 1, 0>>); static_assert(results::as_array_v == std::array{false, true, false}); template <typename... Ts> struct type_pack {}; using results_as_type_pack = results::as_t<type_pack>; using expected_result_as_type_pack = type_pack<std::false_type, std::true_type, std::false_type>; static_assert(std::is_same_v<results_as_type_pack, expected_result_as_type_pack>); } <commit_msg>[mp/type_traits] add comment about if_t<commit_after>#pragma once #include <type_traits> namespace gcl::mp::type_traits { template <class T> struct is_template : std::false_type {}; template <class... T_args, template <class...> class T> struct is_template<T<T_args...>> : std::true_type {}; template <auto... values, template <auto...> class T> struct is_template<T<values...>> : std::true_type {}; template <class T> inline constexpr auto is_template_v = is_template<T>::value; template <typename T, typename = void> struct is_complete : std::false_type {}; template <typename T> struct is_complete<T, std::void_t<decltype(sizeof(T))>> : std::true_type {}; template <typename T> constexpr inline auto is_complete_v = is_complete<T>::value; template <class T_concrete, template <class...> class T> struct is_instance_of : std::false_type {}; template <template <class...> class T, class... T_args> struct is_instance_of<T<T_args...>, T> : std::true_type {}; template <class T_concrete, template <class...> class T> inline constexpr auto is_instance_of_v = is_instance_of<T_concrete, T>::value; template <class T, typename... Args> class is_brace_constructible { template <typename /*= void*/, typename U, typename... U_args> struct impl : std::false_type {}; template <typename U, typename... U_args> struct impl<std::void_t<decltype(U{std::declval<U_args>()...})>, U, U_args...> : std::true_type {}; public: constexpr inline static auto value = impl<std::void_t<>, T, Args...>::value; }; template <class T, typename... Args> constexpr inline auto is_brace_constructible_v = is_brace_constructible<T, Args...>::value; template <bool evaluation> using if_t = std::conditional_t<evaluation, std::true_type, std::false_type>; template <bool evaluation> constexpr inline auto if_v = std::conditional_t<evaluation, std::true_type, std::false_type>::value; template <template <typename> typename first_trait, template<typename> typename... traits> struct merge_traits { template <typename T> using type = typename merge_traits<traits...>::template type<first_trait<T>>; }; template <template <typename> typename first_trait> struct merge_traits<first_trait> { template <typename T> using type = first_trait<T>; }; } #include <bitset> #include <tuple> #include <array> namespace gcl::mp::type_traits { template <template <typename> class trait, typename... Ts> struct trait_result { constexpr static inline auto as_bitset_v = []() consteval { using bitset_type = std::bitset<sizeof...(Ts)>; using bitset_initializer_t = unsigned long long; bitset_initializer_t value{0}; return bitset_type{((value = (value << 1 | trait<Ts>::value)), ...)}; } (); // see gcl::mp::pack_traits::pack_arguments_as for other expansion/conversions template <template <typename...> class T> using as_t = T<typename trait<Ts>::type...>; template <template <typename...> class T> constexpr static inline auto as_v = T{trait<Ts>::value...}; using as_tuple_t = as_t<std::tuple>; constexpr static inline auto as_tuple_v = std::tuple{trait<Ts>::value...}; template <class Int = int> using as_integer_sequence = std::integer_sequence<Int, trait<Ts>::value...>; // constexpr static auto as_array_v = std::array{trait<Ts>::value...}; // OK with GCC 10.2 using as_array_t = std::array<std::tuple_element_t<0, decltype(std::tuple{trait<Ts>::value...})>, sizeof...(Ts)>; constexpr static inline auto as_array_v = as_array_t{trait<Ts>::value...}; }; } // tests namespace gcl::mp::type_traits::tests::is_template { static_assert(gcl::mp::type_traits::is_template_v<std::tuple<int, char>>); static_assert(gcl::mp::type_traits::is_template_v<std::string>); // std::basic_string<charT, allocator> static_assert(not gcl::mp::type_traits::is_template_v<int>); } namespace gcl::mp::type_traits::tests::is_complete { struct complete_type {}; struct incomplete_type; static_assert(gcl::mp::type_traits::is_complete_v<complete_type>); static_assert(gcl::mp::type_traits::is_complete_v<int>); static_assert(not gcl::mp::type_traits::is_complete_v<incomplete_type>); } namespace gcl::mp::type_traits::tests::is_instance_of { static_assert(gcl::mp::type_traits::is_instance_of_v<std::tuple<int, char>, std::tuple>); static_assert(not gcl::mp::type_traits::is_instance_of_v<std::tuple<int, char>, std::pair>); } namespace gcl::mp::type_traits::tests::is_brace_constructible_v { struct toto { int i; }; struct titi { explicit titi(int) {} }; static_assert(type_traits::is_brace_constructible_v<toto>); static_assert(type_traits::is_brace_constructible_v<toto, int>); static_assert(type_traits::is_brace_constructible_v<toto, char>); static_assert(not type_traits::is_brace_constructible_v<toto, char*>); static_assert(not type_traits::is_brace_constructible_v<titi>); static_assert(type_traits::is_brace_constructible_v<titi, int>); static_assert(type_traits::is_brace_constructible_v<titi, char>); static_assert(not type_traits::is_brace_constructible_v<titi, char*>); } namespace gcl::mp::type_traits::tests::if_t { static_assert(std::is_same_v<type_traits::if_t<true>, std::true_type>); static_assert(std::is_same_v<type_traits::if_t<false>, std::false_type>); static_assert(type_traits::if_v<true> == true); static_assert(type_traits::if_v<false> == false); } #if __cpp_concepts #include <concepts> namespace gcl::mp::type_traits::tests::if_t { // clang-format off template <typename T> concept is_red_colored = requires(T) { { T::color == decltype(T::color)::red } -> std::convertible_to<bool>; { type_traits::if_t<T::color == decltype(T::color)::red>{}} -> std::same_as<std::true_type>; // equivalent to : `requires (T::color == decltype(T::color)::red);` }; enum colors { red, blue, green }; struct smthg_blue { constexpr static auto color = colors::blue; }; struct smthg_red { constexpr static auto color = colors::red; }; // clang-format on static_assert(not is_red_colored<smthg_blue>); static_assert(is_red_colored<smthg_red>); } #endif namespace gcl::mp::type_traits::tests::merge_traits { using remove_cv_and_ref = gcl::mp::type_traits::merge_traits<std::remove_reference_t, std::decay_t>; static_assert(std::is_same_v<int, remove_cv_and_ref::type<const int&&>>); } namespace gcl::mp::type_traits::tests::trait_results { template <typename T> using is_int = std::is_same<int, T>; using results = trait_result<is_int, char, int, bool>; // static_assert(decltype(results::as_bitset_v){2UL} == results::as_bitset_v); // std::bitset::operator== is not cx constexpr auto expected_result_as_bitset = decltype(results::as_bitset_v){2UL}; static_assert(expected_result_as_bitset[0] == results::as_bitset_v[0]); static_assert(expected_result_as_bitset[1] == results::as_bitset_v[1]); static_assert(expected_result_as_bitset[2] == results::as_bitset_v[2]); using results_as_tuple = results::as_t<std::tuple>; using results_as_tuple_value_type = std::decay_t<decltype(results::as_v<std::tuple>)>; #if not defined(__clang__) // See my Q on SO : // https://stackoverflow.com/questions/66821952/clang-error-implicit-instantiation-of-undefined-template-stdtuple-sizeauto/66822584 static_assert(std::tuple_size_v<results_as_tuple> == std::tuple_size_v<results_as_tuple_value_type>); // clang and clang-cl complain here using expected_result_type = std::tuple< std::false_type, std::true_type, std::false_type>; static_assert(std::is_same_v<results_as_tuple, expected_result_type>); using expected_result_value_type = std::tuple<bool, bool, bool>; static_assert(std::is_same_v<results_as_tuple_value_type, expected_result_value_type>); #endif using expected_result_as_tuple = std::tuple<std::false_type, std::true_type, std::false_type>; static_assert(std::is_same_v<results::as_t<std::tuple>, expected_result_as_tuple>); static_assert(std::is_same_v<results::as_integer_sequence<int>, std::integer_sequence<int, 0, 1, 0>>); static_assert(results::as_array_v == std::array{false, true, false}); template <typename... Ts> struct type_pack {}; using results_as_type_pack = results::as_t<type_pack>; using expected_result_as_type_pack = type_pack<std::false_type, std::true_type, std::false_type>; static_assert(std::is_same_v<results_as_type_pack, expected_result_as_type_pack>); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmltexte.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: hr $ $Date: 2003-03-27 15:42:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLTEXTE_HXX #define _XMLTEXTE_HXX #ifndef _XMLOFF_TEXTPARAE_HXX_ #include <xmloff/txtparae.hxx> #endif #ifndef _GLOBNAME_HXX #include <tools/globname.hxx> #endif class SwXMLExport; class SvXMLAutoStylePoolP; class SwNoTxtNode; namespace com { namespace sun { namespace star { namespace style { class XStyle; } } } } class SwXMLTextParagraphExport : public XMLTextParagraphExport { const ::rtl::OUString sTextTable; const ::rtl::OUString sEmbeddedObjectProtocol; const SvGlobalName aAppletClassId; const SvGlobalName aPluginClassId; const SvGlobalName aIFrameClassId; const SvGlobalName aOutplaceClassId; SwNoTxtNode *GetNoTxtNode( const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet >& rPropSet ) const; protected: virtual void exportStyleContent( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle > & rStyle ); virtual void _collectTextEmbeddedAutoStyles( const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet > & rPropSet ); virtual void _exportTextEmbedded( const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet > & rPropSet, const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySetInfo > & rPropSetInfo ); virtual void exportTable( const ::com::sun::star::uno::Reference < ::com::sun::star::text::XTextContent > & rTextContent, sal_Bool bAutoStyles, sal_Bool bProgress ); public: SwXMLTextParagraphExport( SwXMLExport& rExp, SvXMLAutoStylePoolP& rAutoStylePool ); ~SwXMLTextParagraphExport(); virtual void setTextEmbeddedGraphicURL( const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet >& rPropSet, ::rtl::OUString& rStreamName ) const; }; #endif // _XMLTEXTE_HXX <commit_msg>INTEGRATION: CWS oasisbf2 (1.14.768); FILE MERGED 2004/11/02 17:10:14 mib 1.14.768.1: #i35133#: replacement image for embedded objects<commit_after>/************************************************************************* * * $RCSfile: xmltexte.hxx,v $ * * $Revision: 1.15 $ * * last change: $Author: rt $ $Date: 2004-11-26 13:32:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLTEXTE_HXX #define _XMLTEXTE_HXX #ifndef _XMLOFF_TEXTPARAE_HXX_ #include <xmloff/txtparae.hxx> #endif #ifndef _GLOBNAME_HXX #include <tools/globname.hxx> #endif class SwXMLExport; class SvXMLAutoStylePoolP; class SwNoTxtNode; namespace com { namespace sun { namespace star { namespace style { class XStyle; } } } } class SwXMLTextParagraphExport : public XMLTextParagraphExport { const ::rtl::OUString sTextTable; const ::rtl::OUString sEmbeddedObjectProtocol; const ::rtl::OUString sGraphicObjectProtocol; const SvGlobalName aAppletClassId; const SvGlobalName aPluginClassId; const SvGlobalName aIFrameClassId; const SvGlobalName aOutplaceClassId; SwNoTxtNode *GetNoTxtNode( const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet >& rPropSet ) const; protected: virtual void exportStyleContent( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle > & rStyle ); virtual void _collectTextEmbeddedAutoStyles( const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet > & rPropSet ); virtual void _exportTextEmbedded( const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet > & rPropSet, const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySetInfo > & rPropSetInfo ); virtual void exportTable( const ::com::sun::star::uno::Reference < ::com::sun::star::text::XTextContent > & rTextContent, sal_Bool bAutoStyles, sal_Bool bProgress ); public: SwXMLTextParagraphExport( SwXMLExport& rExp, SvXMLAutoStylePoolP& rAutoStylePool ); ~SwXMLTextParagraphExport(); virtual void setTextEmbeddedGraphicURL( const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet >& rPropSet, ::rtl::OUString& rStreamName ) const; }; #endif // _XMLTEXTE_HXX <|endoftext|>
<commit_before><commit_msg>Resolves: #i125050# correct text range for comment/annotation...<commit_after><|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2010, 2011, 2012, 2013, 2014, 2015 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade 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. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abaclade.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::to_str_backend – specialization for abc::text::char_ptr_to_str_adapter namespace abc { void to_str_backend<text::char_ptr_to_str_adapter>::write( text::char_ptr_to_str_adapter const & cs, io::text::writer * ptwOut ) { std::size_t cch = text::size_in_chars(cs.m_psz); text::encoding enc(text::guess_encoding(cs.m_psz, cs.m_psz + cch)); text::detail::str_to_str_backend::write(cs.m_psz, sizeof(char) * cch, enc, ptwOut); } } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// <commit_msg>Gracefully handle nullptr in abc::to_str_backend<abc::text::char_ptr_to_str_adapter><commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2010, 2011, 2012, 2013, 2014, 2015 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade 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. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abaclade.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::to_str_backend – specialization for abc::text::char_ptr_to_str_adapter namespace abc { void to_str_backend<text::char_ptr_to_str_adapter>::write( text::char_ptr_to_str_adapter const & cs, io::text::writer * ptwOut ) { void const * p; std::size_t cb; text::encoding enc; if (cs.m_psz) { p = cs.m_psz; std::size_t cch = text::size_in_chars(cs.m_psz); enc = text::guess_encoding(cs.m_psz, cs.m_psz + cch); cb = cch * sizeof(char); } else { static char_t const sc_achNull[] = ABC_SL("<nullptr>"); p = sc_achNull; cb = sizeof sc_achNull - sizeof sc_achNull[0] /*NUL*/; enc = text::encoding::host; } text::detail::str_to_str_backend::write(p, cb, enc, ptwOut); } } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// <|endoftext|>