{"text":"#include \"velar.h\"\n\n\/\/Smiðir\nvelar::velar()\n{\n _vNafn = _tegund = \"None\";\n _byggd = false;\n _bAr = 0;\n\n}\n\nvelar::velar(int id, string vNafn, int bAr, string tegund, bool byggd)\n{\n _id = id;\n _vNafn = vNafn;\n _bAr = bAr;\n _tegund = tegund;\n _byggd = byggd;\n}\n\n\/\/Get föll\nint velar::getID() const\n{\n return _id;\n}\n\nstring velar::getVelaNafn() const\n{\n return _vNafn;\n}\n\nint velar::getByggingarAr() const\n{\n return _bAr;\n}\n\nstring velar::getTegund() const\n{\n return _tegund;\n}\n\nbool velar::getByggd() const\n{\n return _byggd;\n}\n\n\/\/Set föll\nvoid velar::uppfVelaNafn(string nyttvNafn)\n{\n _vNafn = nyttvNafn;\n}\n\nvoid velar::uppfByggingarAr(int nyttbAr)\n{\n _bAr = nyttbAr;\n}\n\nvoid velar::uppfTegund(int nyttTegund)\n{\n _tegund = nyttTegund;\n}\n\nvoid velar::uppfByggd(bool nyttByggd)\n{\n _byggd = nyttByggd;\n}\n\n\/\/ops\nostream& operator <<(ostream& out, const velar& data)\n{\n\n string svar = \"\";\n if (data.getByggd() == 1)\n {\n svar = \"Yes\";\n }\n else\n {\n svar = \"No\";\n }\n\n \/\/out << \"Name of machine: \" << data.getVelaNafn() << endl;\n \/\/out << \"Year of creation: \" << data.getByggingarAr() << endl;\n \/\/out << \"Type: \" << data.getTegund() << endl;\n \/\/out << \"Was it built?: \" << data.getByggd() << endl;\n\n out << \"|\" << data.getVelaNafn() ;\n if(data.getVelaNafn().size() < 5)\n {\n out << \"\\t\";\n }\n out << \" \\t\\t |\" << data.getByggingarAr() << \" \\t\\t |\" << data.getTegund() << \" \\t\\t |\";\n out << svar << \" \\t\\t\\t |\" << endl;\n\n\n return out;\n}\ntharf ad pulla#include \"velar.h\"\n\n\/\/Smiðir\nvelar::velar()\n{\n _vNafn = _tegund = \"None\";\n _byggd = false;\n _bAr = 0;\n\n}\n\nvelar::velar(int id, string vNafn, int bAr, string tegund, bool byggd)\n{\n _id = id;\n _vNafn = vNafn;\n _bAr = bAr;\n _tegund = tegund;\n _byggd = byggd;\n}\n\n\/\/Get föll\nint velar::getID() const\n{\n return _id;\n}\n\nstring velar::getVelaNafn() const\n{\n return _vNafn;\n}\n\nint velar::getByggingarAr() const\n{\n return _bAr;\n}\n\nstring velar::getTegund() const\n{\n return _tegund;\n}\n\nbool velar::getByggd() const\n{\n return _byggd;\n}\n\n\/\/Set föll\nvoid velar::uppfVelaNafn(string nyttvNafn)\n{\n _vNafn = nyttvNafn;\n}\n\nvoid velar::uppfByggingarAr(int nyttbAr)\n{\n _bAr = nyttbAr;\n}\n\nvoid velar::uppfTegund(int nyttTegund)\n{\n _tegund = nyttTegund;\n}\n\nvoid velar::uppfByggd(bool nyttByggd)\n{\n _byggd = nyttByggd;\n}\n\n\/\/ops\nostream& operator <<(ostream& out, const velar& data)\n{\n\n string svar = \"\";\n if (data.getByggd() == 1)\n {\n svar = \"Yes\";\n }\n else\n {\n svar = \"No\";\n }\n\n \/\/out << \"Name of machine: \" << data.getVelaNafn() << endl;\n \/\/out << \"Year of creation: \" << data.getByggingarAr() << endl;\n \/\/out << \"Type: \" << data.getTegund() << endl;\n \/\/out << \"Was it built?: \" << data.getByggd() << endl;\n\n out << \"|\" << data.getVelaNafn() << \" \\t\\t |\" << data.getByggingarAr() << \" \\t\\t |\" << data.getTegund() << \" \\t\\t |\";\n out << svar << \" \\t\\t\\t |\" << endl;\n\n\n return out;\n}\n<|endoftext|>"} {"text":"\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/** @file WhisperHost.cpp\n * @author Gav Wood \n * @date 2014\n *\/\n\n#include \"WhisperHost.h\"\n\n#include \n#include \nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\nusing namespace dev::shh;\n\n#if defined(clogS)\n#undef clogS\n#endif\n#define clogS(X) dev::LogOutputStream(false) << \"| \" << std::setw(2) << session()->socketId() << \"] \"\n\nWhisperHost::WhisperHost()\n{\n}\n\nWhisperHost::~WhisperHost()\n{\n}\n\nvoid WhisperHost::streamMessage(h256 _m, RLPStream& _s) const\n{\n\tUpgradableGuard l(x_messages);\n\tif (m_messages.count(_m))\n\t{\n\t\tUpgradeGuard ll(l);\n\t\tm_messages.at(_m).streamOut(_s, true);\n\t}\n}\n\nvoid WhisperHost::inject(Envelope const& _m, WhisperPeer* _p)\n{\n\tif (_m.expiry() <= time(0))\n\t\treturn;\n\n\tauto h = _m.sha3();\n\t{\n\t\tUpgradableGuard l(x_messages);\n\t\tif (m_messages.count(h))\n\t\t\treturn;\n\t\tUpgradeGuard ll(l);\n\t\tm_messages[h] = _m;\n\t\tm_expiryQueue[_m.expiry()] = h;\n\t}\n\n\/\/\tif (_p)\n\t{\n\t\tGuard l(m_filterLock);\n\t\tfor (auto const& f: m_filters)\n\t\t\tif (f.second.filter.matches(_m))\n\t\t\t\tnoteChanged(h, f.first);\n\t}\n\n\tfor (auto& i: peers())\n\t\tif (i->cap().get() == _p)\n\t\t\ti->addRating(1);\n\t\telse\n\t\t\ti->cap()->noteNewMessage(h, _m);\n}\n\nvoid WhisperHost::noteChanged(h256 _messageHash, h256 _filter)\n{\n\tfor (auto& i: m_watches)\n\t\tif (i.second.id == _filter)\n\t\t{\n\t\t\tcwatshh << \"!!!\" << i.first << i.second.id;\n\t\t\ti.second.changes.push_back(_messageHash);\n\t\t}\n}\n\nunsigned WhisperHost::installWatchOnId(h256 _h)\n{\n\tauto ret = m_watches.size() ? m_watches.rbegin()->first + 1 : 0;\n\tm_watches[ret] = ClientWatch(_h);\n\tcwatshh << \"+++\" << ret << _h;\n\treturn ret;\n}\n\nunsigned WhisperHost::installWatch(shh::TopicFilter const& _f)\n{\n\tGuard l(m_filterLock);\n\n\th256 h = _f.sha3();\n\n\tif (!m_filters.count(h))\n\t\tm_filters.insert(make_pair(h, _f));\n\n\treturn installWatchOnId(h);\n}\n\nh256s WhisperHost::watchMessages(unsigned _watchId)\n{\n\tcleanup();\n\th256s ret;\n\tauto wit = m_watches.find(_watchId);\n\tif (wit == m_watches.end())\n\t\treturn ret;\n\tTopicFilter f;\n\t{\n\t\tGuard l(m_filterLock);\n\t\tauto fit = m_filters.find(wit->second.id);\n\t\tif (fit == m_filters.end())\n\t\t\treturn ret;\n\t\tf = fit->second.filter;\n\t}\n\tReadGuard l(x_messages);\n\tfor (auto const& m: m_messages)\n\t\tif (f.matches(m.second))\n\t\t\tret.push_back(m.first);\n\treturn ret;\n}\n\nvoid WhisperHost::uninstallWatch(unsigned _i)\n{\n\tcwatshh << \"XXX\" << _i;\n\n\tGuard l(m_filterLock);\n\n\tauto it = m_watches.find(_i);\n\tif (it == m_watches.end())\n\t\treturn;\n\tauto id = it->second.id;\n\tm_watches.erase(it);\n\n\tauto fit = m_filters.find(id);\n\tif (fit != m_filters.end())\n\t\tif (!--fit->second.refCount)\n\t\t\tm_filters.erase(fit);\n}\n\nvoid WhisperHost::cleanup()\n{\n\t\/\/ remove old messages.\n\t\/\/ should be called every now and again.\n\tauto now = time(0);\n\tWriteGuard l(x_messages);\n\tfor (auto it = m_expiryQueue.begin(); it != m_expiryQueue.end() && it->first <= now; it = m_expiryQueue.erase(it))\n\t\tm_messages.erase(it->second);\n}\nWhisperer in AZ. More Whisper fixups.\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/** @file WhisperHost.cpp\n * @author Gav Wood \n * @date 2014\n *\/\n\n#include \"WhisperHost.h\"\n\n#include \n#include \nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\nusing namespace dev::shh;\n\n#if defined(clogS)\n#undef clogS\n#endif\n#define clogS(X) dev::LogOutputStream(false) << \"| \" << std::setw(2) << session()->socketId() << \"] \"\n\nWhisperHost::WhisperHost()\n{\n}\n\nWhisperHost::~WhisperHost()\n{\n}\n\nvoid WhisperHost::streamMessage(h256 _m, RLPStream& _s) const\n{\n\tUpgradableGuard l(x_messages);\n\tif (m_messages.count(_m))\n\t{\n\t\tUpgradeGuard ll(l);\n\t\tauto const& m = m_messages.at(_m);\n\t\tcnote << \"streamOut: \" << m.expiry() << m.ttl() << m.topic() << toHex(m.data());\n\t\tm.streamOut(_s, true);\n\t}\n}\n\nvoid WhisperHost::inject(Envelope const& _m, WhisperPeer* _p)\n{\n\tcnote << \"inject: \" << _m.expiry() << _m.ttl() << _m.topic() << toHex(_m.data());\n\n\tif (_m.expiry() <= time(0))\n\t\treturn;\n\n\tauto h = _m.sha3();\n\t{\n\t\tUpgradableGuard l(x_messages);\n\t\tif (m_messages.count(h))\n\t\t\treturn;\n\t\tUpgradeGuard ll(l);\n\t\tm_messages[h] = _m;\n\t\tm_expiryQueue[_m.expiry()] = h;\n\t}\n\n\/\/\tif (_p)\n\t{\n\t\tGuard l(m_filterLock);\n\t\tfor (auto const& f: m_filters)\n\t\t\tif (f.second.filter.matches(_m))\n\t\t\t\tnoteChanged(h, f.first);\n\t}\n\n\tfor (auto& i: peers())\n\t\tif (i->cap().get() == _p)\n\t\t\ti->addRating(1);\n\t\telse\n\t\t\ti->cap()->noteNewMessage(h, _m);\n}\n\nvoid WhisperHost::noteChanged(h256 _messageHash, h256 _filter)\n{\n\tfor (auto& i: m_watches)\n\t\tif (i.second.id == _filter)\n\t\t{\n\t\t\tcwatshh << \"!!!\" << i.first << i.second.id;\n\t\t\ti.second.changes.push_back(_messageHash);\n\t\t}\n}\n\nunsigned WhisperHost::installWatchOnId(h256 _h)\n{\n\tauto ret = m_watches.size() ? m_watches.rbegin()->first + 1 : 0;\n\tm_watches[ret] = ClientWatch(_h);\n\tcwatshh << \"+++\" << ret << _h;\n\treturn ret;\n}\n\nunsigned WhisperHost::installWatch(shh::TopicFilter const& _f)\n{\n\tGuard l(m_filterLock);\n\n\th256 h = _f.sha3();\n\n\tif (!m_filters.count(h))\n\t\tm_filters.insert(make_pair(h, _f));\n\n\treturn installWatchOnId(h);\n}\n\nh256s WhisperHost::watchMessages(unsigned _watchId)\n{\n\tcleanup();\n\th256s ret;\n\tauto wit = m_watches.find(_watchId);\n\tif (wit == m_watches.end())\n\t\treturn ret;\n\tTopicFilter f;\n\t{\n\t\tGuard l(m_filterLock);\n\t\tauto fit = m_filters.find(wit->second.id);\n\t\tif (fit == m_filters.end())\n\t\t\treturn ret;\n\t\tf = fit->second.filter;\n\t}\n\tReadGuard l(x_messages);\n\tfor (auto const& m: m_messages)\n\t\tif (f.matches(m.second))\n\t\t\tret.push_back(m.first);\n\treturn ret;\n}\n\nvoid WhisperHost::uninstallWatch(unsigned _i)\n{\n\tcwatshh << \"XXX\" << _i;\n\n\tGuard l(m_filterLock);\n\n\tauto it = m_watches.find(_i);\n\tif (it == m_watches.end())\n\t\treturn;\n\tauto id = it->second.id;\n\tm_watches.erase(it);\n\n\tauto fit = m_filters.find(id);\n\tif (fit != m_filters.end())\n\t\tif (!--fit->second.refCount)\n\t\t\tm_filters.erase(fit);\n}\n\nvoid WhisperHost::cleanup()\n{\n\t\/\/ remove old messages.\n\t\/\/ should be called every now and again.\n\tauto now = time(0);\n\tWriteGuard l(x_messages);\n\tfor (auto it = m_expiryQueue.begin(); it != m_expiryQueue.end() && it->first <= now; it = m_expiryQueue.erase(it))\n\t\tm_messages.erase(it->second);\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"otbImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingMinMaxImageFilter.h\"\n\n#include \"otbImageFunctionAdapter.h\"\n\n#include \"otbFourierMellinDescriptorsImageFunction.h\"\n#include \"otbRealMomentsImageFunction.h\"\n#include \"otbComplexMomentsImageFunction.h\"\n#include \"otbFlusserMomentsImageFunction.h\"\n#include \"otbHuMomentsImageFunction.h\"\n#include \"otbRadiometricMomentsImageFunction.h\"\n#include \"otbLocalHistogramImageFunction.h\"\n\n\nint otbImageFunctionAdapterNew(int argc, char * argv[])\n{\n typedef double InputPixelType;\n const unsigned int Dimension = 2;\n\n typedef otb::Image InputImageType;\n \n typedef otb::FourierMellinDescriptorsImageFunction FMDFunctionType;\n typedef otb::RealMomentsImageFunction RMFunctionType;\n typedef otb::ComplexMomentsImageFunction CMFunctionType;\n typedef otb::FlusserMomentsImageFunction FMFunctionType;\n typedef otb::HuMomentsImageFunction HMFunctionType;\n typedef otb::RadiometricMomentsImageFunction RaMFunctionType;\n typedef otb::LocalHistogramImageFunction LHFunctionType;\n\n typedef otb::ImageFunctionAdapter FMDImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter RMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter CMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter FMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter HMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter RaMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter LHImageFunctionAdapterType;\n\n \/\/ Instantiating objects\n FMDImageFunctionAdapterType::Pointer FMDadaptedFunction = FMDImageFunctionAdapterType::New();\n std::cout << FMDadaptedFunction << std::endl;\n RMImageFunctionAdapterType::Pointer RMadaptedFunction = RMImageFunctionAdapterType::New();\n std::cout << RMadaptedFunction << std::endl;\n CMImageFunctionAdapterType::Pointer CMadaptedFunction = CMImageFunctionAdapterType::New();\n std::cout << CMadaptedFunction << std::endl;\n FMImageFunctionAdapterType::Pointer FMadaptedFunction = FMImageFunctionAdapterType::New();\n std::cout << FMadaptedFunction << std::endl;\n HMImageFunctionAdapterType::Pointer HMadaptedFunction = HMImageFunctionAdapterType::New();\n std::cout << HMadaptedFunction << std::endl;\n RaMImageFunctionAdapterType::Pointer RaMadaptedFunction = RaMImageFunctionAdapterType::New();\n std::cout << RaMadaptedFunction << std::endl;\n LHImageFunctionAdapterType::Pointer LHadaptedFunction = LHImageFunctionAdapterType::New();\n std::cout << LHadaptedFunction << std::endl;\n \n return EXIT_SUCCESS;\n}\n\nint otbImageFunctionAdapter(int argc, char * argv[])\n{\n const char * inputFilename = argv[1];\n \n typedef double InputPixelType;\n const unsigned int Dimension = 2;\n unsigned int rsltIdx = 0;\n\n typedef otb::Image InputImageType;\n typedef otb::ImageFileReader ReaderType;\n typedef otb::StreamingMinMaxImageFilter MinMaxFilterType;\n \n typedef otb::FourierMellinDescriptorsImageFunction FMDFunctionType;\n typedef otb::RealMomentsImageFunction RMFunctionType;\n typedef otb::ComplexMomentsImageFunction CMFunctionType;\n typedef otb::FlusserMomentsImageFunction FMFunctionType;\n typedef otb::HuMomentsImageFunction HMFunctionType;\n typedef otb::RadiometricMomentsImageFunction RaMFunctionType;\n typedef otb::LocalHistogramImageFunction LHFunctionType;\n\n typedef otb::ImageFunctionAdapter FMDImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter RMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter CMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter FMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter HMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter RaMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter LHImageFunctionAdapterType;\n\n \/\/ Instantiating objects\n ReaderType::Pointer reader = ReaderType::New();\n MinMaxFilterType::Pointer filter = MinMaxFilterType::New();\n \n FMDFunctionType::Pointer FMDFunction = FMDFunctionType::New();\n RMFunctionType::Pointer RMFunction = RMFunctionType::New();\n CMFunctionType::Pointer CMFunction = CMFunctionType::New();\n FMFunctionType::Pointer FMFunction = FMFunctionType::New();\n HMFunctionType::Pointer HMFunction = HMFunctionType::New();\n RaMFunctionType::Pointer RaMFunction = RaMFunctionType::New();\n LHFunctionType::Pointer LHFunction = LHFunctionType::New();\n\n FMDImageFunctionAdapterType::Pointer FMDadaptedFunction = FMDImageFunctionAdapterType::New();\n RMImageFunctionAdapterType::Pointer RMadaptedFunction = RMImageFunctionAdapterType::New();\n CMImageFunctionAdapterType::Pointer CMadaptedFunction = CMImageFunctionAdapterType::New();\n FMImageFunctionAdapterType::Pointer FMadaptedFunction = FMImageFunctionAdapterType::New();\n HMImageFunctionAdapterType::Pointer HMadaptedFunction = HMImageFunctionAdapterType::New();\n RaMImageFunctionAdapterType::Pointer RaMadaptedFunction = RaMImageFunctionAdapterType::New();\n LHImageFunctionAdapterType::Pointer LHadaptedFunction = LHImageFunctionAdapterType::New();\n \n reader->SetFileName(inputFilename);\n filter->SetInput(reader->GetOutput());\n filter->Update();\n\n InputImageType::IndexType index;\n index[0] = 100;\n index[1] = 100;\n \n \/\/ Content testing \n double error = 0.0;\n\n FMDFunction->SetInputImage(reader->GetOutput());\n FMDFunction->SetNeighborhoodRadius(5);\n FMDFunction->SetPmax(5);\n FMDFunction->SetQmax(5);\n FMDFunctionType::OutputType resultFMD = FMDFunction->EvaluateAtIndex(index);\n\n FMDadaptedFunction->SetInputImage(reader->GetOutput());\n FMDadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n FMDadaptedFunction->GetImageFunction()->SetPmax(5);\n FMDadaptedFunction->GetImageFunction()->SetQmax(5);\n FMDImageFunctionAdapterType::OutputType resultAdaptedFMD = FMDadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<=5; i++)\n {\n for (unsigned int j=0; j<=5; j++)\n {\n error += vcl_pow(vcl_abs(resultAdaptedFMD[rsltIdx] - resultFMD.at(i).at(j)), 2);\n \n std::cout << \"resultAdaptedFMD : \" << resultAdaptedFMD[rsltIdx] \n << \"\\t - resultFMD : \" << resultFMD.at(i).at(j) << std::endl;\n rsltIdx ++;\n }\n }\n\n RMFunction->SetInputImage(reader->GetOutput());\n RMFunction->SetNeighborhoodRadius(5);\n RMFunction->SetPmax(5);\n RMFunction->SetQmax(5);\n RMFunctionType::OutputType resultRM = RMFunction->EvaluateAtIndex(index);\n\n RMadaptedFunction->SetInputImage(reader->GetOutput());\n RMadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n RMadaptedFunction->GetImageFunction()->SetPmax(5);\n RMadaptedFunction->GetImageFunction()->SetQmax(5);\n RMImageFunctionAdapterType::OutputType resultAdaptedRM = RMadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<=5; i++)\n {\n for (unsigned int j=0; j<=5; j++)\n {\n error += vcl_pow(vcl_abs(resultAdaptedRM[rsltIdx] - resultRM.at(i).at(j)), 2);\n\n std::cout << \"resultAdaptedRM : \" << resultAdaptedRM[rsltIdx] \n << \"\\t - resultRM : \" << resultRM.at(i).at(j) << std::endl;\n rsltIdx ++;\n }\n }\n\n CMFunction->SetInputImage(reader->GetOutput());\n CMFunction->SetNeighborhoodRadius(5);\n CMFunction->SetPmax(5);\n CMFunction->SetQmax(5);\n CMFunctionType::OutputType resultCM = CMFunction->EvaluateAtIndex(index);\n\n CMadaptedFunction->SetInputImage(reader->GetOutput());\n CMadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n CMadaptedFunction->GetImageFunction()->SetPmax(5);\n CMadaptedFunction->GetImageFunction()->SetQmax(5);\n CMImageFunctionAdapterType::OutputType resultAdaptedCM = CMadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<=5; i++)\n {\n for (unsigned int j=0; j<=5; j++)\n {\n error += vcl_pow(vcl_abs(resultAdaptedCM[rsltIdx] - resultCM.at(i).at(j).real()), 2);\n std::cout << \"resultAdaptedCM : (\" << resultAdaptedCM[rsltIdx]\n << \",\" << resultAdaptedCM[rsltIdx+1] << \")\"\n << \"\\t - resultCM : \" << resultCM.at(i).at(j) << std::endl;\n rsltIdx ++;\n error += vcl_pow(vcl_abs(resultAdaptedCM[rsltIdx] - resultCM.at(i).at(j).imag()), 2);\n rsltIdx ++;\n }\n }\n\n FMFunction->SetInputImage(reader->GetOutput());\n FMFunction->SetNeighborhoodRadius(5);\n FMFunctionType::OutputType resultFM = FMFunction->EvaluateAtIndex(index);\n\n FMadaptedFunction->SetInputImage(reader->GetOutput());\n FMadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n FMImageFunctionAdapterType::OutputType resultAdaptedFM = FMadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<11; i++)\n {\n error += vcl_pow(vcl_abs(resultAdaptedFM[rsltIdx] - resultFM[i]), 2);\n\n std::cout << \"resultAdaptedFM : \" << resultAdaptedFM[rsltIdx] \n << \"\\t - resultFM : \" << resultFM[i] << std::endl;\n rsltIdx ++;\n }\n\n HMFunction->SetInputImage(reader->GetOutput());\n HMFunction->SetNeighborhoodRadius(5);\n HMFunctionType::OutputType resultHM = HMFunction->EvaluateAtIndex(index);\n\n HMadaptedFunction->SetInputImage(reader->GetOutput());\n HMadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n HMImageFunctionAdapterType::OutputType resultAdaptedHM = HMadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<=7; i++)\n {\n error += vcl_pow(vcl_abs(resultAdaptedHM[rsltIdx] - resultHM[i]), 2);\n\n std::cout << \"resultAdaptedHM : \" << resultAdaptedHM[rsltIdx] \n << \"\\t - resultHM : \" << resultHM[i] << std::endl;\n rsltIdx ++;\n }\n\n RaMFunction->SetInputImage(reader->GetOutput());\n RaMFunction->SetNeighborhoodRadius(5);\n RaMFunctionType::OutputType resultRaM = RaMFunction->EvaluateAtIndex(index);\n \n RaMadaptedFunction->SetInputImage(reader->GetOutput());\n RaMadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n RaMImageFunctionAdapterType::OutputType resultAdaptedRaM = RaMadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<4; i++)\n { \n error += vcl_pow(vcl_abs(resultAdaptedRaM[rsltIdx] - resultRaM[i]), 2);\n\n std::cout << \"resultAdaptedRaM : \" << resultAdaptedRaM[rsltIdx] \n << \"\\t - resultRaM : \" << resultRaM[i] << std::endl;\n rsltIdx ++;\n }\n\n LHFunction->SetInputImage(reader->GetOutput());\n LHFunction->SetNeighborhoodRadius(5);\n LHFunction->SetNumberOfHistogramBins(64);\n LHFunction->SetHistogramMin(filter->GetMinimum());\n LHFunction->SetHistogramMax(filter->GetMaximum());\n LHFunctionType::OutputType resultLH = LHFunction->EvaluateAtIndex(index);\n\n LHadaptedFunction->SetInputImage(reader->GetOutput());\n LHadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n LHadaptedFunction->GetImageFunction()->SetNumberOfHistogramBins(64);\n LHadaptedFunction->GetImageFunction()->SetHistogramMin(filter->GetMinimum());\n LHadaptedFunction->GetImageFunction()->SetHistogramMax(filter->GetMaximum());\n LHImageFunctionAdapterType::OutputType resultAdaptedLH = LHadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<64; i++)\n {\n error += vcl_pow(vcl_abs( resultAdaptedLH[rsltIdx] - resultLH->GetFrequency(i)), 2);\n\n std::cout << \"resultAdaptedLH : \" << resultAdaptedLH[rsltIdx]\n << \"\\t - resultLH : \" << resultLH->GetFrequency(i) << std::endl;\n rsltIdx ++;\n }\n \n error = vcl_sqrt(error);\n std::cout << std::endl << \"Error : \" << error << std::endl\n << std::endl;\n\n if (error > 1E-3)\n {\n itkGenericExceptionMacro( << \"Error = \" << error\n << \" > 1E-9 -> TEST FAILLED\" << std::endl );\n }\n\n return EXIT_SUCCESS;\n}\nTEST: corrected ImageFunctionAdapter test\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"otbImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingMinMaxImageFilter.h\"\n\n#include \"otbImageFunctionAdapter.h\"\n\n#include \"otbFourierMellinDescriptorsImageFunction.h\"\n#include \"otbRealMomentsImageFunction.h\"\n#include \"otbComplexMomentsImageFunction.h\"\n#include \"otbFlusserMomentsImageFunction.h\"\n#include \"otbHuMomentsImageFunction.h\"\n#include \"otbRadiometricMomentsImageFunction.h\"\n#include \"otbLocalHistogramImageFunction.h\"\n\n\nint otbImageFunctionAdapterNew(int argc, char * argv[])\n{\n typedef double InputPixelType;\n const unsigned int Dimension = 2;\n\n typedef otb::Image InputImageType;\n \n typedef otb::FourierMellinDescriptorsImageFunction FMDFunctionType;\n typedef otb::RealMomentsImageFunction RMFunctionType;\n typedef otb::ComplexMomentsImageFunction CMFunctionType;\n typedef otb::FlusserMomentsImageFunction FMFunctionType;\n typedef otb::HuMomentsImageFunction HMFunctionType;\n typedef otb::RadiometricMomentsImageFunction RaMFunctionType;\n typedef otb::LocalHistogramImageFunction LHFunctionType;\n\n typedef otb::ImageFunctionAdapter FMDImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter RMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter CMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter FMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter HMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter RaMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter LHImageFunctionAdapterType;\n\n \/\/ Instantiating objects\n FMDImageFunctionAdapterType::Pointer FMDadaptedFunction = FMDImageFunctionAdapterType::New();\n std::cout << FMDadaptedFunction << std::endl;\n RMImageFunctionAdapterType::Pointer RMadaptedFunction = RMImageFunctionAdapterType::New();\n std::cout << RMadaptedFunction << std::endl;\n CMImageFunctionAdapterType::Pointer CMadaptedFunction = CMImageFunctionAdapterType::New();\n std::cout << CMadaptedFunction << std::endl;\n FMImageFunctionAdapterType::Pointer FMadaptedFunction = FMImageFunctionAdapterType::New();\n std::cout << FMadaptedFunction << std::endl;\n HMImageFunctionAdapterType::Pointer HMadaptedFunction = HMImageFunctionAdapterType::New();\n std::cout << HMadaptedFunction << std::endl;\n RaMImageFunctionAdapterType::Pointer RaMadaptedFunction = RaMImageFunctionAdapterType::New();\n std::cout << RaMadaptedFunction << std::endl;\n LHImageFunctionAdapterType::Pointer LHadaptedFunction = LHImageFunctionAdapterType::New();\n std::cout << LHadaptedFunction << std::endl;\n \n return EXIT_SUCCESS;\n}\n\nint otbImageFunctionAdapter(int argc, char * argv[])\n{\n const char * inputFilename = argv[1];\n \n typedef double InputPixelType;\n const unsigned int Dimension = 2;\n unsigned int rsltIdx = 0;\n\n typedef otb::Image InputImageType;\n typedef otb::ImageFileReader ReaderType;\n typedef otb::StreamingMinMaxImageFilter MinMaxFilterType;\n \n typedef otb::FourierMellinDescriptorsImageFunction FMDFunctionType;\n typedef otb::RealMomentsImageFunction RMFunctionType;\n typedef otb::ComplexMomentsImageFunction CMFunctionType;\n typedef otb::FlusserMomentsImageFunction FMFunctionType;\n typedef otb::HuMomentsImageFunction HMFunctionType;\n typedef otb::RadiometricMomentsImageFunction RaMFunctionType;\n typedef otb::LocalHistogramImageFunction LHFunctionType;\n\n typedef otb::ImageFunctionAdapter FMDImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter RMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter CMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter FMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter HMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter RaMImageFunctionAdapterType;\n typedef otb::ImageFunctionAdapter LHImageFunctionAdapterType;\n\n \/\/ Instantiating objects\n ReaderType::Pointer reader = ReaderType::New();\n MinMaxFilterType::Pointer filter = MinMaxFilterType::New();\n \n FMDFunctionType::Pointer FMDFunction = FMDFunctionType::New();\n RMFunctionType::Pointer RMFunction = RMFunctionType::New();\n CMFunctionType::Pointer CMFunction = CMFunctionType::New();\n FMFunctionType::Pointer FMFunction = FMFunctionType::New();\n HMFunctionType::Pointer HMFunction = HMFunctionType::New();\n RaMFunctionType::Pointer RaMFunction = RaMFunctionType::New();\n LHFunctionType::Pointer LHFunction = LHFunctionType::New();\n\n FMDImageFunctionAdapterType::Pointer FMDadaptedFunction = FMDImageFunctionAdapterType::New();\n RMImageFunctionAdapterType::Pointer RMadaptedFunction = RMImageFunctionAdapterType::New();\n CMImageFunctionAdapterType::Pointer CMadaptedFunction = CMImageFunctionAdapterType::New();\n FMImageFunctionAdapterType::Pointer FMadaptedFunction = FMImageFunctionAdapterType::New();\n HMImageFunctionAdapterType::Pointer HMadaptedFunction = HMImageFunctionAdapterType::New();\n RaMImageFunctionAdapterType::Pointer RaMadaptedFunction = RaMImageFunctionAdapterType::New();\n LHImageFunctionAdapterType::Pointer LHadaptedFunction = LHImageFunctionAdapterType::New();\n \n reader->SetFileName(inputFilename);\n filter->SetInput(reader->GetOutput());\n filter->Update();\n\n InputImageType::IndexType index;\n index[0] = 100;\n index[1] = 100;\n \n \/\/ Content testing \n double error = 0.0;\n\n FMDFunction->SetInputImage(reader->GetOutput());\n FMDFunction->SetNeighborhoodRadius(5);\n FMDFunction->SetPmax(5);\n FMDFunction->SetQmax(5);\n FMDFunctionType::OutputType resultFMD = FMDFunction->EvaluateAtIndex(index);\n\n FMDadaptedFunction->SetInputImage(reader->GetOutput());\n FMDadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n FMDadaptedFunction->GetImageFunction()->SetPmax(5);\n FMDadaptedFunction->GetImageFunction()->SetQmax(5);\n FMDImageFunctionAdapterType::OutputType resultAdaptedFMD = FMDadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<=5; i++)\n {\n for (unsigned int j=0; j<=5; j++)\n {\n error += vcl_pow(vcl_abs(resultAdaptedFMD[rsltIdx] - resultFMD.at(i).at(j)), 2);\n \n std::cout << \"resultAdaptedFMD : \" << resultAdaptedFMD[rsltIdx] \n << \"\\t - resultFMD : \" << resultFMD.at(i).at(j) << std::endl;\n rsltIdx ++;\n }\n }\n\n RMFunction->SetInputImage(reader->GetOutput());\n RMFunction->SetNeighborhoodRadius(5);\n RMFunction->SetPmax(5);\n RMFunction->SetQmax(5);\n RMFunctionType::OutputType resultRM = RMFunction->EvaluateAtIndex(index);\n\n RMadaptedFunction->SetInputImage(reader->GetOutput());\n RMadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n RMadaptedFunction->GetImageFunction()->SetPmax(5);\n RMadaptedFunction->GetImageFunction()->SetQmax(5);\n RMImageFunctionAdapterType::OutputType resultAdaptedRM = RMadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<=5; i++)\n {\n for (unsigned int j=0; j<=5; j++)\n {\n error += vcl_pow(vcl_abs(resultAdaptedRM[rsltIdx] - resultRM.at(i).at(j)), 2);\n\n std::cout << \"resultAdaptedRM : \" << resultAdaptedRM[rsltIdx] \n << \"\\t - resultRM : \" << resultRM.at(i).at(j) << std::endl;\n rsltIdx ++;\n }\n }\n\n CMFunction->SetInputImage(reader->GetOutput());\n CMFunction->SetNeighborhoodRadius(5);\n CMFunction->SetPmax(5);\n CMFunction->SetQmax(5);\n CMFunctionType::OutputType resultCM = CMFunction->EvaluateAtIndex(index);\n\n CMadaptedFunction->SetInputImage(reader->GetOutput());\n CMadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n CMadaptedFunction->GetImageFunction()->SetPmax(5);\n CMadaptedFunction->GetImageFunction()->SetQmax(5);\n CMImageFunctionAdapterType::OutputType resultAdaptedCM = CMadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<=5; i++)\n {\n for (unsigned int j=0; j<=5; j++)\n {\n error += vcl_pow(vcl_abs(resultAdaptedCM[rsltIdx] - resultCM.at(i).at(j).real()), 2);\n std::cout << \"resultAdaptedCM : (\" << resultAdaptedCM[rsltIdx]\n << \",\" << resultAdaptedCM[rsltIdx+1] << \")\"\n << \"\\t - resultCM : \" << resultCM.at(i).at(j) << std::endl;\n rsltIdx ++;\n error += vcl_pow(vcl_abs(resultAdaptedCM[rsltIdx] - resultCM.at(i).at(j).imag()), 2);\n rsltIdx ++;\n }\n }\n\n FMFunction->SetInputImage(reader->GetOutput());\n FMFunction->SetNeighborhoodRadius(5);\n FMFunctionType::OutputType resultFM = FMFunction->EvaluateAtIndex(index);\n\n FMadaptedFunction->SetInputImage(reader->GetOutput());\n FMadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n FMImageFunctionAdapterType::OutputType resultAdaptedFM = FMadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<11; i++)\n {\n error += vcl_pow(vcl_abs(resultAdaptedFM[rsltIdx] - resultFM[i]), 2);\n\n std::cout << \"resultAdaptedFM : \" << resultAdaptedFM[rsltIdx] \n << \"\\t - resultFM : \" << resultFM[i] << std::endl;\n rsltIdx ++;\n }\n\n HMFunction->SetInputImage(reader->GetOutput());\n HMFunction->SetNeighborhoodRadius(5);\n HMFunctionType::OutputType resultHM = HMFunction->EvaluateAtIndex(index);\n\n HMadaptedFunction->SetInputImage(reader->GetOutput());\n HMadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n HMImageFunctionAdapterType::OutputType resultAdaptedHM = HMadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<7; i++)\n {\n error += vcl_pow(vcl_abs(resultAdaptedHM[rsltIdx] - resultHM[i]), 2);\n\n std::cout << \"resultAdaptedHM : \" << resultAdaptedHM[rsltIdx] \n << \"\\t - resultHM : \" << resultHM[i] << std::endl;\n rsltIdx ++;\n }\n\n RaMFunction->SetInputImage(reader->GetOutput());\n RaMFunction->SetNeighborhoodRadius(5);\n RaMFunctionType::OutputType resultRaM = RaMFunction->EvaluateAtIndex(index);\n \n RaMadaptedFunction->SetInputImage(reader->GetOutput());\n RaMadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n RaMImageFunctionAdapterType::OutputType resultAdaptedRaM = RaMadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<4; i++)\n { \n error += vcl_pow(vcl_abs(resultAdaptedRaM[rsltIdx] - resultRaM[i]), 2);\n\n std::cout << \"resultAdaptedRaM : \" << resultAdaptedRaM[rsltIdx] \n << \"\\t - resultRaM : \" << resultRaM[i] << std::endl;\n rsltIdx ++;\n }\n\n LHFunction->SetInputImage(reader->GetOutput());\n LHFunction->SetNeighborhoodRadius(5);\n LHFunction->SetNumberOfHistogramBins(64);\n LHFunction->SetHistogramMin(filter->GetMinimum());\n LHFunction->SetHistogramMax(filter->GetMaximum());\n LHFunctionType::OutputType resultLH = LHFunction->EvaluateAtIndex(index);\n\n LHadaptedFunction->SetInputImage(reader->GetOutput());\n LHadaptedFunction->GetImageFunction()->SetNeighborhoodRadius(5);\n LHadaptedFunction->GetImageFunction()->SetNumberOfHistogramBins(64);\n LHadaptedFunction->GetImageFunction()->SetHistogramMin(filter->GetMinimum());\n LHadaptedFunction->GetImageFunction()->SetHistogramMax(filter->GetMaximum());\n LHImageFunctionAdapterType::OutputType resultAdaptedLH = LHadaptedFunction->EvaluateAtIndex(index);\n \n rsltIdx = 0;\n for (unsigned int i=0; i<64; i++)\n {\n error += vcl_pow(vcl_abs( resultAdaptedLH[rsltIdx] - resultLH->GetFrequency(i)), 2);\n\n std::cout << \"resultAdaptedLH : \" << resultAdaptedLH[rsltIdx]\n << \"\\t - resultLH : \" << resultLH->GetFrequency(i) << std::endl;\n rsltIdx ++;\n }\n \n error = vcl_sqrt(error);\n std::cout << std::endl << \"Error : \" << error << std::endl\n << std::endl;\n\n if (error > 1E-3)\n {\n itkGenericExceptionMacro( << \"Error = \" << error\n << \" > 1E-9 -> TEST FAILLED\" << std::endl );\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/**\n * @file cnn_pooling_connection.hpp\n * @author Shangtong Zhang\n *\n * Implementation of the pooling connection between input layer\n * and output layer for CNN.\n *\/\n#ifndef __MLPACK_METHODS_ANN_CONNECTIONS_POOLING_CONNECTION_HPP\n#define __MLPACK_METHODS_ANN_CONNECTIONS_POOLING_CONNECTION_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace mlpack{\nnamespace ann \/** Artificial Neural Network. *\/ {\n\n\/**\n * Implementation of the pooling connection class for CNN.\n * The pooling connection connects\n * input layer with the output layer by pooling.\n * output = factor * pooling_value + bias\n *\n * @tparam InputLayerType Type of the connected input layer.\n * @tparam OutputLayerType Type of the connected output layer.\n * @tparam OptimizerType Type of the optimizer used to update the weights.\n * @tparam PoolingRule Type of pooling strategy.\n * @tparam MatType Type of data (arma::mat or arma::sp_mat).\n *\/\ntemplate<\n typename InputLayerType,\n typename OutputLayerType,\n typename OptimizerType,\n typename PoolingRule = MaxPooling,\n typename MatType = arma::mat\n>\nclass PoolingConnection\n{\n public:\n \/**\n * Create the PoolingConnection object using the specified input layer, output\n * layer, optimizer, factor, bias and pooling strategy.\n * The factor and bias is stored in @weights.\n *\n * @param InputLayerType The input layer which is connected with the output\n * layer.\n * @param OutputLayerType The output layer which is connected with the input\n * layer.\n * @param OptimizerType The optimizer used to update the weight matrix.\n * @param PoolingRule The strategy of pooling.\n *\/\n PoolingConnection(InputLayerType& inputLayer,\n OutputLayerType& outputLayer,\n OptimizerType& optimizer,\n double factor = 1.0,\n double bias = 0,\n PoolingRule pooling = PoolingRule()) :\n inputLayer(inputLayer), outputLayer(outputLayer), optimizer(optimizer),\n weights(2), pooling(pooling),\n rawOutput(outputLayer.InputActivation().n_rows,\n outputLayer.InputActivation().n_cols)\n {\n delta = arma::zeros(inputLayer.InputActivation().n_rows,\n inputLayer.InputActivation().n_cols);\n gradient = arma::zeros(2);\n weights(0) = factor;\n weights(1) = bias;\n }\n \n \/**\n * Ordinary feed forward pass of a neural network, \n * apply pooling to the neurons in the input layer.\n *\n * @param input Input data used for pooling.\n *\/\n void FeedForward(const MatType& input)\n {\n size_t r_step = input.n_rows \/ outputLayer.InputActivation().n_rows;\n size_t c_step = input.n_cols \/ outputLayer.InputActivation().n_cols;\n for (size_t j = 0; j < input.n_cols; j += c_step)\n {\n for (size_t i = 0; i < input.n_rows; i += r_step)\n {\n double value = 0;\n pooling.pooling(input(arma::span(i, i + r_step -1),\n arma::span(j, j + c_step - 1)), value);\n rawOutput(i \/ r_step, j \/ c_step) = value;\n }\n }\n outputLayer.InputActivation() += rawOutput * weights(0) + weights(1);\n }\n \n \/**\n * Ordinary feed backward pass of a neural network.\n * Apply unsampling to the error in output layer to \n * pass the error to input layer.\n * @param error The backpropagated error.\n *\/\n void FeedBackward(const MatType& error)\n {\n gradient(1) = arma::sum(arma::sum(error));\n gradient(0) = arma::sum(arma::sum(rawOutput % error));\n MatType weightedError = error * weights(0);\n size_t r_step = inputLayer.InputActivation().n_rows \/ error.n_rows;\n size_t c_step = inputLayer.InputActivation().n_cols \/ error.n_cols;\n const MatType& input = inputLayer.InputActivation();\n MatType newError;\n for (size_t j = 0; j < input.n_cols; j += c_step)\n {\n for (size_t i = 0; i < input.n_rows; i += r_step)\n {\n const MatType& inputArea = input(arma::span(i, i + r_step -1),\n arma::span(j, j + c_step - 1));\n pooling.unpooling(inputArea,\n weightedError(i \/ r_step, j \/ c_step),\n newError);\n delta(arma::span(i, i + r_step -1),\n arma::span(j, j + c_step - 1)) = newError;\n }\n }\n inputLayer.Delta() += delta;\n }\n \n \/\/! Get the weights.\n MatType& Weights() const { return weights; }\n \/\/! Modify the weights.\n MatType& Weights() { return weights; }\n \n \/\/! Get the input layer.\n InputLayerType& InputLayer() const { return inputLayer; }\n \/\/! Modify the input layer.\n InputLayerType& InputLayer() { return inputLayer; }\n \n \/\/! Get the output layer.\n OutputLayerType& OutputLayer() const { return outputLayer; }\n \/\/! Modify the output layer.\n OutputLayerType& OutputLayer() { return outputLayer; }\n \n \/\/! Get the optimizer.\n OptimizerType& Optimzer() const { return optimizer; }\n \/\/! Modify the optimzer.\n OptimizerType& Optimzer() { return optimizer; }\n \n \/\/! Get the passed error in backward propagation.\n MatType& Delta() const { return delta; }\n \/\/! Modify the passed error in backward propagation.\n MatType& Delta() { return delta; }\n \n \/\/! Get the gradient of weights.\n MatType& Gradient() const { return gradient; }\n \/\/! Modify the delta of weights.\n MatType& Gradient() { return gradient; }\n \n \/\/! Get the pooling strategy.\n PoolingRule& Pooling() const { return pooling; }\n \/\/! Modify the pooling strategy.\n PoolingRule& Pooling() { return pooling; }\n \n private:\n \/\/! Locally-stored input layer.\n InputLayerType& inputLayer;\n \n \/\/! Locally-stored output layer.\n OutputLayerType& outputLayer;\n \n \/\/! Locally-stored optimizer.\n OptimizerType& optimizer;\n \n \/\/! Locally-stored weights, only two value, factor and bias.\n arma::colvec weights;\n \n \/\/! Locally-stored passed error in backward propagation.\n MatType delta;\n \n \/\/! Locally-stored pooling strategy.\n PoolingRule pooling;\n \n \/\/! Locally-stored gradient of weights.\n MatType gradient;\n \n \/**\n * Locally-stored raw result of pooling,\n * before multiplied by factor and added by bias.\n * Cache it to speed up when performing backward propagation.\n *\/\n MatType rawOutput;\n};\n \n}; \/\/ namespace ann\n}; \/\/ namespace mlpack\n\n#endifRefactor pooling connection to support 3rd order tensors.\/**\n * @file cnn_pooling_connection.hpp\n * @author Shangtong Zhang\n * @author Marcus Edel\n *\n * Implementation of the pooling connection between input layer and output layer\n * for the convolutional neural network.\n *\/\n#ifndef __MLPACK_METHODS_ANN_CONNECTIONS_POOLING_CONNECTION_HPP\n#define __MLPACK_METHODS_ANN_CONNECTIONS_POOLING_CONNECTION_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace mlpack{\nnamespace ann \/** Artificial Neural Network. *\/ {\n\n\/**\n * Implementation of the pooling connection class for the convolutional neural\n * network. The pooling connection connects input layer with the output layer\n * using the specified pooling rule.\n *\n * @tparam InputLayerType Type of the connected input layer.\n * @tparam OutputLayerType Type of the connected output layer.\n * @tparam PoolingRule Type of the pooling strategy.\n * @tparam OptimizerType Type of the optimizer used to update the weights.\n * @tparam DataType Type of data (arma::mat, arma::sp_mat or arma::cube).\n *\/\ntemplate<\n typename InputLayerType,\n typename OutputLayerType,\n typename PoolingRule = MaxPooling,\n template class OptimizerType = SteepestDescent,\n typename DataType = arma::cube\n>\nclass PoolingConnection\n{\n public:\n \/**\n * Create the PoolingConnection object using the specified input layer, output\n * layer, optimizer and pooling strategy.\n * The factor and bias is stored in @weights.\n *\n * @param InputLayerType The input layer which is connected with the output\n * layer.\n * @param OutputLayerType The output layer which is connected with the input\n * layer.\n * @param OptimizerType The optimizer used to update the weight matrix.\n * @param PoolingRule The strategy of pooling.\n *\/\n PoolingConnection(InputLayerType& inputLayer,\n OutputLayerType& outputLayer,\n PoolingRule pooling = PoolingRule()) :\n inputLayer(inputLayer),\n outputLayer(outputLayer),\n optimizer(0),\n weights(0),\n pooling(pooling),\n delta(inputLayer.Delta().n_rows, inputLayer.Delta().n_cols,\n inputLayer.Delta().n_slices)\n {\n \/\/ Nothing to do here.\n }\n\n \/**\n * Ordinary feed forward pass of a neural network, apply pooling to the\n * neurons (dense matrix) in the input layer.\n *\n * @param input Input data used for pooling.\n *\/\n template\n void FeedForward(const arma::Mat& input)\n {\n Pooling(input, outputLayer.InputActivation());\n }\n\n \/**\n * Ordinary feed forward pass of a neural network, apply pooling to the\n * neurons (3rd order tensor) in the input layer.\n *\n * @param input Input data used for pooling.\n *\/\n template\n void FeedForward(const arma::Cube& input)\n {\n for (size_t s = 0; s < input.n_slices; s++)\n Pooling(input.slice(s), outputLayer.InputActivation().slice(s));\n }\n\n \/**\n * Ordinary feed backward pass of a neural network. Apply unsampling to the\n * error in output layer (dense matrix) to pass the error to input layer.\n *\n * @param error The backpropagated error.\n *\/\n template\n void FeedBackward(const arma::Mat& error)\n {\n Unpooling(inputLayer.InputActivation(), error, inputLayer.Delta());\n }\n\n \/**\n * Ordinary feed backward pass of a neural network. Apply unsampling to the\n * error in output layer (3rd order tensor) to pass the error to input layer.\n *\n * @param error The backpropagated error.\n *\/\n template\n void FeedBackward(const arma::Cube& error)\n {\n for (size_t s = 0; s < error.n_slices; s++)\n {\n Unpooling(inputLayer.InputActivation().slice(s), error.slice(s),\n delta.slice(s));\n }\n }\n\n \/*\n * Calculate the gradient using the output delta and the input activation.\n *\n * @param gradient The calculated gradient.\n *\/\n template\n void Gradient(GradientType& \/* unused *\/)\n {\n \/\/ Nothing to do here.\n }\n\n \/\/! Get the weights.\n DataType& Weights() const { return *weights; }\n \/\/! Modify the weights.\n DataType& Weights() { return *weights; }\n\n \/\/! Get the input layer.\n InputLayerType& InputLayer() const { return inputLayer; }\n \/\/! Modify the input layer.\n InputLayerType& InputLayer() { return inputLayer; }\n\n \/\/! Get the output layer.\n OutputLayerType& OutputLayer() const { return outputLayer; }\n \/\/! Modify the output layer.\n OutputLayerType& OutputLayer() { return outputLayer; }\n\n \/\/! Get the optimizer.\n OptimizerType& Optimzer() const { return *optimizer; }\n \/\/! Modify the optimzer.\n OptimizerType& Optimzer() { return *optimizer; }\n\n \/\/! Get the passed error in backward propagation.\n DataType& Delta() const { return delta; }\n \/\/! Modify the passed error in backward propagation.\n DataType& Delta() { return delta; }\n\n \/\/! Get the pooling strategy.\n PoolingRule& Pooling() const { return pooling; }\n \/\/! Modify the pooling strategy.\n PoolingRule& Pooling() { return pooling; }\n\n private:\n \/**\n * Apply pooling to the input and store the results.\n *\n * @param input The input to be apply the pooling rule.\n * @param output The pooled result.\n *\/\n template\n void Pooling(const arma::Mat& input, arma::Mat& output)\n {\n const size_t rStep = input.n_rows \/ outputLayer.LayerRows();\n const size_t cStep = input.n_cols \/ outputLayer.LayerCols();\n\n for (size_t j = 0; j < input.n_cols; j += cStep)\n {\n for (size_t i = 0; i < input.n_rows; i += rStep)\n {\n output(i \/ rStep, j \/ cStep) += pooling.Pooling(\n input(arma::span(i, i + rStep -1), arma::span(j, j + cStep - 1)));\n }\n }\n }\n\n \/**\n * Apply unpooling to the input and store the results.\n *\n * @param input The input to be apply the unpooling rule.\n * @param output The pooled result.\n *\/\n template\n void Unpooling(const arma::Mat& input,\n const arma::Mat& error,\n arma::Mat& output)\n {\n const size_t rStep = input.n_rows \/ error.n_rows;\n const size_t cStep = input.n_cols \/ error.n_cols;\n\n arma::Mat unpooledError;\n for (size_t j = 0; j < input.n_cols; j += cStep)\n {\n for (size_t i = 0; i < input.n_rows; i += rStep)\n {\n const arma::Mat& inputArea = input(arma::span(i, i + rStep -1),\n arma::span(j, j + cStep - 1));\n\n pooling.Unpooling(inputArea, error(i \/ rStep, j \/ cStep),\n unpooledError);\n\n output(arma::span(i, i + rStep - 1),\n arma::span(j, j + cStep - 1)) += unpooledError;\n }\n }\n }\n\n \/\/! Locally-stored input layer.\n InputLayerType& inputLayer;\n\n \/\/! Locally-stored output layer.\n OutputLayerType& outputLayer;\n\n \/\/! Locally-stored optimizer.\n OptimizerType* optimizer;\n\n \/\/! Locally-stored weight object.\n DataType* weights;\n\n \/\/! Locally-stored pooling strategy.\n PoolingRule pooling;\n\n \/\/! Locally-stored passed error in backward propagation.\n DataType delta;\n}; \/\/ PoolingConnection class.\n\n\/\/! Connection traits for the pooling connection.\ntemplate<\n typename InputLayerType,\n typename OutputLayerType,\n typename PoolingRule,\n template class OptimizerType,\n typename DataType\n>\nclass ConnectionTraits<\n PoolingConnection >\n{\n public:\n static const bool IsSelfConnection = false;\n static const bool IsFullselfConnection = false;\n static const bool IsPoolingConnection = true;\n};\n\n}; \/\/ namespace ann\n}; \/\/ namespace mlpack\n\n#endif<|endoftext|>"} {"text":"\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ Editor find\/replace widget\n\/\/==============================================================================\n\n#include \"editorfindreplacewidget.h\"\n#include \"guiutils.h\"\n#include \"i18ninterface.h\"\n\n\/\/==============================================================================\n\n#include \"ui_editorfindreplacewidget.h\"\n\n\/\/==============================================================================\n\n#include \n\n\/\/==============================================================================\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace Editor {\n\n\/\/==============================================================================\n\nEditorFindReplaceWidget::EditorFindReplaceWidget(QWidget *pParent) :\n Core::Widget(pParent),\n mGui(new Ui::EditorFindReplaceWidget),\n mActive(false)\n{\n \/\/ Set up the GUI\n\n mGui->setupUi(this);\n\n#ifdef Q_OS_MAC\n mGui->findEdit->setAttribute(Qt::WA_MacShowFocusRect, false);\n mGui->replaceEdit->setAttribute(Qt::WA_MacShowFocusRect, false);\n \/\/ Note: the above remove the focus border since it messes up the look of\n \/\/ our edit widgets...\n#endif\n\n \/\/ Create and handle our drop-down menu action\n\n mDropDownAction = new QAction(this);\n\n mCaseSensitiveAction = Core::newAction(true, this);\n mWholeWordsOnlyAction = Core::newAction(true, this);\n mRegularExpressionAction = Core::newAction(true, this);\n\n QMenu *dropDownMenu = new QMenu(this);\n\n dropDownMenu->addAction(mCaseSensitiveAction);\n dropDownMenu->addAction(mWholeWordsOnlyAction);\n dropDownMenu->addAction(mRegularExpressionAction);\n\n mDropDownAction->setMenu(dropDownMenu);\n\n mGui->findEdit->addAction(mDropDownAction, QLineEdit::LeadingPosition);\n\n connect(mCaseSensitiveAction, SIGNAL(toggled(bool)),\n this, SLOT(searchOptionChanged()));\n connect(mWholeWordsOnlyAction, SIGNAL(toggled(bool)),\n this, SLOT(searchOptionChanged()));\n connect(mRegularExpressionAction, SIGNAL(toggled(bool)),\n this, SLOT(searchOptionChanged()));\n\n \/\/ Create and handle our clear find and replace text actions\n\n mClearFindTextAction = Core::newAction(QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/images\/editclear.png\"), this);\n mClearReplaceTextAction = Core::newAction(QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/images\/editclear.png\"), this);\n\n connect(mClearFindTextAction, SIGNAL(triggered()),\n mGui->findEdit, SLOT(clear()));\n\n connect(mClearReplaceTextAction, SIGNAL(triggered()),\n mGui->replaceEdit, SLOT(clear()));\n\n \/\/ Make our find edit widget our focus proxy\n\n setFocusProxy(mGui->findEdit);\n\n \/\/ Some connections for our find-related widgets\n\n connect(mGui->findEdit, SIGNAL(textChanged(const QString &)),\n this, SLOT(updateClearFindTextAction(const QString &)));\n\n connect(this, SIGNAL(canFindReplace(const bool &)),\n mGui->findPreviousButton, SLOT(setEnabled(bool)));\n connect(this, SIGNAL(canFindReplace(const bool &)),\n mGui->findNextButton, SLOT(setEnabled(bool)));\n\n connect(this, SIGNAL(canFindReplace(const bool &)),\n mGui->replaceButton, SLOT(setEnabled(bool)));\n connect(this, SIGNAL(canFindReplace(const bool &)),\n mGui->replaceAndFindButton, SLOT(setEnabled(bool)));\n connect(this, SIGNAL(canFindReplace(const bool &)),\n mGui->replaceAllButton, SLOT(setEnabled(bool)));\n\n \/\/ A connection for our replace widget\n\n connect(mGui->replaceEdit, SIGNAL(textChanged(const QString &)),\n this, SLOT(updateClearReplaceTextAction(const QString &)));\n\n \/\/ A few more things , so that we are properly initialised\n\n retranslateUi();\n\n searchOptionChanged();\n\n setActive(true);\n\n updateStyleSheet();\n updateHeight();\n \/\/ Note: just to be safe, we update our height after updating our style\n \/\/ sheet since we change the size of our tool buttons...\n\n mGui->findPreviousButton->setEnabled(false);\n mGui->findNextButton->setEnabled(false);\n\n mGui->replaceButton->setEnabled(false);\n mGui->replaceAndFindButton->setEnabled(false);\n mGui->replaceAllButton->setEnabled(false);\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::retranslateUi()\n{\n \/\/ Retranslate our GUI\n\n mGui->retranslateUi(this);\n\n \/\/ Retranslate our actions\n\n I18nInterface::retranslateAction(mCaseSensitiveAction, tr(\"Case Sensitive\"),\n tr(\"The search is case sensitive\"));\n I18nInterface::retranslateAction(mWholeWordsOnlyAction, tr(\"Whole Words Only\"),\n tr(\"The search is done on whole words only\"));\n I18nInterface::retranslateAction(mRegularExpressionAction, tr(\"Regular Expression\"),\n tr(\"The search uses a regular expression\"));\n\n I18nInterface::retranslateAction(mClearFindTextAction, tr(\"Clear Text\"),\n tr(\"Clear the text\"));\n I18nInterface::retranslateAction(mClearReplaceTextAction, tr(\"Clear Text\"),\n tr(\"Clear the text\"));\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::isCaseSensitive() const\n{\n \/\/ Return whether the search is to be case sensitive\n\n return mCaseSensitiveAction->isChecked();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::searchWholeWordsOnly() const\n{\n \/\/ Return whether we search whole words only\n\n return mWholeWordsOnlyAction->isChecked();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::useRegularExpression() const\n{\n \/\/ Return whether we use a regular expression\n\n return mRegularExpressionAction->isChecked();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::setReadOnly(const bool &pReadOnly)\n{\n \/\/ Show\/hide our replace-related widgets based on whether we are in\n \/\/ read-only mode\n\n Core::showEnableWidget(mGui->replaceLabel, !pReadOnly);\n Core::showEnableWidget(mGui->replaceEdit, !pReadOnly);\n Core::showEnableWidget(mGui->replaceButton, !pReadOnly);\n Core::showEnableWidget(mGui->replaceAndFindButton, !pReadOnly);\n Core::showEnableWidget(mGui->replaceAllButton, !pReadOnly);\n\n \/\/ Enable\/disable our find spacer\n\n mGui->findLayout->setStretch(2, !pReadOnly);\n\n \/\/ Disable our replace-related buttons, if needed\n\n if (findText().isEmpty()) {\n mGui->replaceButton->setEnabled(false);\n mGui->replaceAndFindButton->setEnabled(false);\n mGui->replaceAllButton->setEnabled(false);\n }\n\n \/\/ Update our height\n\n updateHeight();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::isFindPreviousNextAvailable() const\n{\n \/\/ Return whether the find previous\/next actions are available\n\n return !findText().isEmpty();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::selectFindText() const\n{\n \/\/ Select our find text\n\n mGui->findEdit->selectAll();\n}\n\n\/\/==============================================================================\n\nQString EditorFindReplaceWidget::findText() const\n{\n \/\/ Return our find text\n\n return mGui->findEdit->text();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::setFindText(const QString &pFindText)\n{\n \/\/ Set our find text and select it\n\n mGui->findEdit->setText(pFindText);\n\n selectFindText();\n}\n\n\/\/==============================================================================\n\nQString EditorFindReplaceWidget::replaceText() const\n{\n \/\/ Return our replace text\n\n return mGui->replaceEdit->text();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::findEditHasFocus() const\n{\n \/\/ Return whether our find edit has the focus\n\n return mGui->findEdit->hasFocus();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::replaceEditHasFocus() const\n{\n \/\/ Return whether our replace edit has the focus\n\n return mGui->replaceEdit->hasFocus();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::isActive() const\n{\n \/\/ Return whether we are active\n\n return mActive;\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::setActive(const bool &pActive)\n{\n if (pActive == mActive)\n return;\n\n \/\/ Set our active state\n\n mActive = pActive;\n\n if (pActive)\n connect(mGui->findEdit, SIGNAL(textChanged(const QString &)),\n this, SIGNAL(findTextChanged(const QString &)));\n else\n disconnect(mGui->findEdit, SIGNAL(textChanged(const QString &)),\n this, SIGNAL(findTextChanged(const QString &)));\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::updateFrom(EditorFindReplaceWidget *pFindReplace)\n{\n \/\/ Update our find and replace texts from the given find\/replace widget\n\n mGui->findEdit->setText(pFindReplace->findText());\n mGui->replaceEdit->setText(pFindReplace->replaceText());\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::updateHeight()\n{\n \/\/ Update our layout\n \/\/ Note: we shouldn't have to do this, but if the user opens a read-only and\n \/\/ shows ourselves, then the find-related widgets will be too 'low'.\n \/\/ This is because the replace-related widgets get hidden\/disabled as\n \/\/ expected, but the layout doesn't get updated before we fix our\n \/\/ height, so we update our layout here and in all cases...\n\n mGui->layout->update();\n\n \/\/ Update our height\n\n setFixedHeight(mGui->layout->sizeHint().height());\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::updateStyleSheet()\n{\n \/\/ Change the style of our tool buttons\n\n QColor shadowColor = Core::shadowColor();\n\n setStyleSheet(QString(\"QToolButton {\"\n \" border: 0px;\"\n \" border-radius: 3px;\"\n \" padding: 1px;\"\n \"}\"\n \"\"\n \"QToolButton:focus {\"\n \" background: rgba(%1, %2, %3, 0.13);\"\n \" border: 1px solid rgba(%1, %2, %3, 0.39);\"\n \"}\"\n \"\"\n \"QToolButton:hover {\"\n \" background: rgba(%1, %2, %3, 0.39);\"\n \"}\"\n \"\"\n \"QToolButton:pressed {\"\n \" background: rgba(%1, %2, %3, 0.79);\"\n \"}\").arg(QString::number(shadowColor.red()),\n QString::number(shadowColor.green()),\n QString::number(shadowColor.blue())));\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::changeEvent(QEvent *pEvent)\n{\n \/\/ Check whether the palette has changed and if so then update our style\n \/\/ sheet\n\n if (pEvent->type() == QEvent::PaletteChange)\n updateStyleSheet();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::keyPressEvent(QKeyEvent *pEvent)\n{\n \/\/ Let people know that a key has been pressed\n\n bool handled = false;\n\n emit keyPressed(pEvent, handled);\n\n \/\/ Carry on as normal, if the event wasn't handled\n\n if (handled)\n \/\/ Accept the event\n\n pEvent->accept();\n else\n \/\/ Default handling of the event\n\n Core::Widget::keyPressEvent(pEvent);\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::resizeEvent(QResizeEvent *pEvent)\n{\n \/\/ Default handling of the event\n\n Core::Widget::resizeEvent(pEvent);\n\n \/\/ Update our height\n\n updateHeight();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::on_findPreviousButton_clicked()\n{\n \/\/ Let people know that we want to find the previous occurrence of the text\n\n emit findPreviousRequested();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::on_findNextButton_clicked()\n{\n \/\/ Let people know that we want to find the next occurrence of the text\n\n emit findNextRequested();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::on_replaceButton_clicked()\n{\n \/\/ Let people know that we want to replace the current text\n\n emit replaceRequested();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::on_replaceAndFindButton_clicked()\n{\n \/\/ Let people know that we want to replace the current text and the find the\n \/\/ next occurence of the text\n\n emit replaceAndFindRequested();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::on_replaceAllButton_clicked()\n{\n \/\/ Let people know that we want to replace all the occurences of the text\n\n emit replaceAllRequested();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::searchOptionChanged()\n{\n \/\/ Update the icon used for the leading position of our find widget\n\n int nbOfOptions = mCaseSensitiveAction->isChecked()\n +mWholeWordsOnlyAction->isChecked()\n +mRegularExpressionAction->isChecked();\n\n if (nbOfOptions) {\n static QIcon caseSensitiveIcon = QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/find\/images\/casesensitively.png\");\n static QIcon wholeWordsOnlyIcon = QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/find\/images\/wholewords.png\");\n static QIcon regularExpressionIcon = QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/find\/images\/regexp.png\");\n\n static int IconSize = 16;\n static int IconWidth = 6;\n\n QPixmap dropDownPixmap = QPixmap(nbOfOptions*IconWidth-mRegularExpressionAction->isChecked()-1,\n IconSize);\n \/\/ Note: IconWidth-1, because regularExpressionIcon is effectively one\n \/\/ pixel narrower than caseSensitiveIcon and wholeWordsOnlyIcon...\n\n dropDownPixmap.fill(Qt::transparent);\n\n QPainter dropDownPixmapPainter(&dropDownPixmap);\n\n int left = -IconWidth;\n\n if (mCaseSensitiveAction->isChecked()) {\n caseSensitiveIcon.paint(&dropDownPixmapPainter, left, 0, IconSize, IconSize);\n\n left += IconWidth;\n }\n\n if (mWholeWordsOnlyAction->isChecked()) {\n wholeWordsOnlyIcon.paint(&dropDownPixmapPainter, left, 0, IconSize, IconSize);\n\n left += IconWidth;\n }\n\n if (mRegularExpressionAction->isChecked())\n regularExpressionIcon.paint(&dropDownPixmapPainter, left-1, 0, IconSize, IconSize);\n\n mDropDownAction->setIcon(dropDownPixmap);\n } else {\n \/\/ No options are set, so use our default icon\n\n static QIcon defaultIcon = QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/images\/magnifier.png\");\n\n mDropDownAction->setIcon(defaultIcon);\n }\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::updateClearFindTextAction(const QString &pText)\n{\n \/\/ Show\/hide our clear text action, based on whether our find widget\n \/\/ contains some text\n\n if (pText.isEmpty())\n mGui->findEdit->removeAction(mClearFindTextAction);\n else\n mGui->findEdit->addAction(mClearFindTextAction, QLineEdit::TrailingPosition);\n\n \/\/ Let people know whether we can find\/replace\n\n emit canFindReplace(!findText().isEmpty());\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::updateClearReplaceTextAction(const QString &pText)\n{\n \/\/ Show\/hide our clear text action, based on whether our replace widget\n \/\/ contains some text\n\n if (pText.isEmpty())\n mGui->replaceEdit->removeAction(mClearReplaceTextAction);\n else\n mGui->replaceEdit->addAction(mClearReplaceTextAction, QLineEdit::TrailingPosition);\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace Editor\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\nMinor fix our Editor widget [ci skip].\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ Editor find\/replace widget\n\/\/==============================================================================\n\n#include \"editorfindreplacewidget.h\"\n#include \"guiutils.h\"\n#include \"i18ninterface.h\"\n\n\/\/==============================================================================\n\n#include \"ui_editorfindreplacewidget.h\"\n\n\/\/==============================================================================\n\n#include \n\n\/\/==============================================================================\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace Editor {\n\n\/\/==============================================================================\n\nEditorFindReplaceWidget::EditorFindReplaceWidget(QWidget *pParent) :\n Core::Widget(pParent),\n mGui(new Ui::EditorFindReplaceWidget),\n mActive(false)\n{\n \/\/ Set up the GUI\n\n mGui->setupUi(this);\n\n#ifdef Q_OS_MAC\n mGui->findEdit->setAttribute(Qt::WA_MacShowFocusRect, false);\n mGui->replaceEdit->setAttribute(Qt::WA_MacShowFocusRect, false);\n \/\/ Note: the above remove the focus border since it messes up the look of\n \/\/ our edit widgets...\n#endif\n\n \/\/ Create and handle our drop-down menu action\n\n mDropDownAction = new QAction(this);\n\n mCaseSensitiveAction = Core::newAction(true, this);\n mWholeWordsOnlyAction = Core::newAction(true, this);\n mRegularExpressionAction = Core::newAction(true, this);\n\n QMenu *dropDownMenu = new QMenu(this);\n\n dropDownMenu->addAction(mCaseSensitiveAction);\n dropDownMenu->addAction(mWholeWordsOnlyAction);\n dropDownMenu->addAction(mRegularExpressionAction);\n\n mDropDownAction->setMenu(dropDownMenu);\n\n mGui->findEdit->addAction(mDropDownAction, QLineEdit::LeadingPosition);\n\n connect(mCaseSensitiveAction, SIGNAL(toggled(bool)),\n this, SLOT(searchOptionChanged()));\n connect(mWholeWordsOnlyAction, SIGNAL(toggled(bool)),\n this, SLOT(searchOptionChanged()));\n connect(mRegularExpressionAction, SIGNAL(toggled(bool)),\n this, SLOT(searchOptionChanged()));\n\n \/\/ Create and handle our clear find and replace text actions\n\n mClearFindTextAction = Core::newAction(QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/images\/editclear.png\"), this);\n mClearReplaceTextAction = Core::newAction(QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/images\/editclear.png\"), this);\n\n connect(mClearFindTextAction, SIGNAL(triggered()),\n mGui->findEdit, SLOT(clear()));\n\n connect(mClearReplaceTextAction, SIGNAL(triggered()),\n mGui->replaceEdit, SLOT(clear()));\n\n \/\/ Make our find edit widget our focus proxy\n\n setFocusProxy(mGui->findEdit);\n\n \/\/ Some connections for our find-related widgets\n\n connect(mGui->findEdit, SIGNAL(textChanged(const QString &)),\n this, SLOT(updateClearFindTextAction(const QString &)));\n\n connect(this, SIGNAL(canFindReplace(const bool &)),\n mGui->findPreviousButton, SLOT(setEnabled(bool)));\n connect(this, SIGNAL(canFindReplace(const bool &)),\n mGui->findNextButton, SLOT(setEnabled(bool)));\n\n connect(this, SIGNAL(canFindReplace(const bool &)),\n mGui->replaceButton, SLOT(setEnabled(bool)));\n connect(this, SIGNAL(canFindReplace(const bool &)),\n mGui->replaceAndFindButton, SLOT(setEnabled(bool)));\n connect(this, SIGNAL(canFindReplace(const bool &)),\n mGui->replaceAllButton, SLOT(setEnabled(bool)));\n\n \/\/ A connection for our replace widget\n\n connect(mGui->replaceEdit, SIGNAL(textChanged(const QString &)),\n this, SLOT(updateClearReplaceTextAction(const QString &)));\n\n \/\/ A few more things , so that we are properly initialised\n\n retranslateUi();\n\n searchOptionChanged();\n\n setActive(true);\n\n updateStyleSheet();\n updateHeight();\n \/\/ Note: just to be safe, we update our height after updating our style\n \/\/ sheet since we change the size of our tool buttons...\n\n mGui->findPreviousButton->setEnabled(false);\n mGui->findNextButton->setEnabled(false);\n\n mGui->replaceButton->setEnabled(false);\n mGui->replaceAndFindButton->setEnabled(false);\n mGui->replaceAllButton->setEnabled(false);\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::retranslateUi()\n{\n \/\/ Retranslate our GUI\n\n mGui->retranslateUi(this);\n\n \/\/ Retranslate our actions\n\n I18nInterface::retranslateAction(mCaseSensitiveAction, tr(\"Case Sensitive\"),\n tr(\"The search is case sensitive\"));\n I18nInterface::retranslateAction(mWholeWordsOnlyAction, tr(\"Whole Words Only\"),\n tr(\"The search is done on whole words only\"));\n I18nInterface::retranslateAction(mRegularExpressionAction, tr(\"Regular Expression\"),\n tr(\"The search uses a regular expression\"));\n\n I18nInterface::retranslateAction(mClearFindTextAction, tr(\"Clear Text\"),\n tr(\"Clear the text\"));\n I18nInterface::retranslateAction(mClearReplaceTextAction, tr(\"Clear Text\"),\n tr(\"Clear the text\"));\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::isCaseSensitive() const\n{\n \/\/ Return whether the search is to be case sensitive\n\n return mCaseSensitiveAction->isChecked();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::searchWholeWordsOnly() const\n{\n \/\/ Return whether we search whole words only\n\n return mWholeWordsOnlyAction->isChecked();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::useRegularExpression() const\n{\n \/\/ Return whether we use a regular expression\n\n return mRegularExpressionAction->isChecked();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::setReadOnly(const bool &pReadOnly)\n{\n \/\/ Show\/hide our replace-related widgets based on whether we are in\n \/\/ read-only mode\n\n Core::showEnableWidget(mGui->replaceLabel, !pReadOnly);\n Core::showEnableWidget(mGui->replaceEdit, !pReadOnly);\n Core::showEnableWidget(mGui->replaceButton, !pReadOnly);\n Core::showEnableWidget(mGui->replaceAndFindButton, !pReadOnly);\n Core::showEnableWidget(mGui->replaceAllButton, !pReadOnly);\n\n \/\/ Enable\/disable our find spacer\n\n mGui->findLayout->setStretch(2, !pReadOnly);\n\n \/\/ Disable our replace-related buttons, if needed\n\n if (findText().isEmpty()) {\n mGui->replaceButton->setEnabled(false);\n mGui->replaceAndFindButton->setEnabled(false);\n mGui->replaceAllButton->setEnabled(false);\n }\n\n \/\/ Update our height\n\n updateHeight();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::isFindPreviousNextAvailable() const\n{\n \/\/ Return whether the find previous\/next actions are available\n\n return !findText().isEmpty();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::selectFindText() const\n{\n \/\/ Select our find text\n\n mGui->findEdit->selectAll();\n}\n\n\/\/==============================================================================\n\nQString EditorFindReplaceWidget::findText() const\n{\n \/\/ Return our find text\n\n return mGui->findEdit->text();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::setFindText(const QString &pFindText)\n{\n \/\/ Set our find text and select it\n\n mGui->findEdit->setText(pFindText);\n\n selectFindText();\n}\n\n\/\/==============================================================================\n\nQString EditorFindReplaceWidget::replaceText() const\n{\n \/\/ Return our replace text\n\n return mGui->replaceEdit->text();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::findEditHasFocus() const\n{\n \/\/ Return whether our find edit has the focus\n\n return mGui->findEdit->hasFocus();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::replaceEditHasFocus() const\n{\n \/\/ Return whether our replace edit has the focus\n\n return mGui->replaceEdit->hasFocus();\n}\n\n\/\/==============================================================================\n\nbool EditorFindReplaceWidget::isActive() const\n{\n \/\/ Return whether we are active\n\n return mActive;\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::setActive(const bool &pActive)\n{\n if (pActive == mActive)\n return;\n\n \/\/ Set our active state\n\n mActive = pActive;\n\n if (pActive)\n connect(mGui->findEdit, SIGNAL(textChanged(const QString &)),\n this, SIGNAL(findTextChanged(const QString &)));\n else\n disconnect(mGui->findEdit, SIGNAL(textChanged(const QString &)),\n this, SIGNAL(findTextChanged(const QString &)));\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::updateFrom(EditorFindReplaceWidget *pFindReplace)\n{\n \/\/ Update our find and replace texts from the given find\/replace widget\n\n mGui->findEdit->setText(pFindReplace->findText());\n mGui->replaceEdit->setText(pFindReplace->replaceText());\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::updateHeight()\n{\n \/\/ Update our layout\n \/\/ Note: we shouldn't have to do this, but if the user opens a read-only and\n \/\/ shows ourselves, then the find-related widgets will be too 'low'.\n \/\/ This is because the replace-related widgets get hidden\/disabled as\n \/\/ expected, but the layout doesn't get updated before we fix our\n \/\/ height, so we update our layout here and in all cases...\n\n mGui->layout->update();\n\n \/\/ Update our height\n\n setFixedHeight(mGui->layout->sizeHint().height());\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::updateStyleSheet()\n{\n \/\/ Change the style of our tool buttons\n\n QColor shadowColor = Core::shadowColor();\n\n setStyleSheet(QString(\"QToolButton {\"\n \" border: 0px;\"\n \" border-radius: 3px;\"\n \" padding: 1px;\"\n \"}\"\n \"\"\n \"QToolButton:focus {\"\n \" background: rgba(%1, %2, %3, 0.13);\"\n \" border: 1px solid rgba(%1, %2, %3, 0.39);\"\n \"}\"\n \"\"\n \"QToolButton:hover {\"\n \" background: rgba(%1, %2, %3, 0.39);\"\n \"}\"\n \"\"\n \"QToolButton:pressed {\"\n \" background: rgba(%1, %2, %3, 0.79);\"\n \"}\").arg(QString::number(shadowColor.red()),\n QString::number(shadowColor.green()),\n QString::number(shadowColor.blue())));\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::changeEvent(QEvent *pEvent)\n{\n \/\/ Check whether the palette has changed and if so then update our style\n \/\/ sheet\n\n if (pEvent->type() == QEvent::PaletteChange)\n updateStyleSheet();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::keyPressEvent(QKeyEvent *pEvent)\n{\n \/\/ Let people know that a key has been pressed\n\n bool handled = false;\n\n emit keyPressed(pEvent, handled);\n\n \/\/ Carry on as normal, if the event wasn't handled\n\n if (handled)\n \/\/ Accept the event\n\n pEvent->accept();\n else\n \/\/ Default handling of the event\n\n Core::Widget::keyPressEvent(pEvent);\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::resizeEvent(QResizeEvent *pEvent)\n{\n \/\/ Default handling of the event\n\n Core::Widget::resizeEvent(pEvent);\n\n \/\/ Update our height\n\n updateHeight();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::on_findPreviousButton_clicked()\n{\n \/\/ Let people know that we want to find the previous occurrence of the text\n\n emit findPreviousRequested();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::on_findNextButton_clicked()\n{\n \/\/ Let people know that we want to find the next occurrence of the text\n\n emit findNextRequested();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::on_replaceButton_clicked()\n{\n \/\/ Let people know that we want to replace the current text\n\n emit replaceRequested();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::on_replaceAndFindButton_clicked()\n{\n \/\/ Let people know that we want to replace the current text and the find the\n \/\/ next occurence of the text\n\n emit replaceAndFindRequested();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::on_replaceAllButton_clicked()\n{\n \/\/ Let people know that we want to replace all the occurences of the text\n\n emit replaceAllRequested();\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::searchOptionChanged()\n{\n \/\/ Update the icon used for the leading position of our find widget\n\n int nbOfOptions = mCaseSensitiveAction->isChecked()\n +mWholeWordsOnlyAction->isChecked()\n +mRegularExpressionAction->isChecked();\n\n if (nbOfOptions) {\n static QIcon caseSensitiveIcon = QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/find\/images\/casesensitively.png\");\n static QIcon wholeWordsOnlyIcon = QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/find\/images\/wholewords.png\");\n static QIcon regularExpressionIcon = QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/find\/images\/regexp.png\");\n\n static int IconSize = 16;\n static int IconWidth = 6;\n\n QPixmap dropDownPixmap = QPixmap(nbOfOptions*IconWidth-mRegularExpressionAction->isChecked(),\n IconSize);\n \/\/ Note: -mRegularExpressionAction->isChecked(), because\n \/\/ regularExpressionIcon is effectively one pixel narrower than\n \/\/ caseSensitiveIcon and wholeWordsOnlyIcon...\n\n dropDownPixmap.fill(Qt::transparent);\n\n QPainter dropDownPixmapPainter(&dropDownPixmap);\n\n int left = -IconWidth;\n\n if (mCaseSensitiveAction->isChecked()) {\n caseSensitiveIcon.paint(&dropDownPixmapPainter, left, 0, IconSize, IconSize);\n\n left += IconWidth;\n }\n\n if (mWholeWordsOnlyAction->isChecked()) {\n wholeWordsOnlyIcon.paint(&dropDownPixmapPainter, left, 0, IconSize, IconSize);\n\n left += IconWidth;\n }\n\n if (mRegularExpressionAction->isChecked())\n regularExpressionIcon.paint(&dropDownPixmapPainter, left-1, 0, IconSize, IconSize);\n\n mDropDownAction->setIcon(dropDownPixmap);\n } else {\n \/\/ No options are set, so use our default icon\n\n static QIcon defaultIcon = QIcon(\":\/qtCreator\/src\/plugins\/coreplugin\/images\/magnifier.png\");\n\n mDropDownAction->setIcon(defaultIcon);\n }\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::updateClearFindTextAction(const QString &pText)\n{\n \/\/ Show\/hide our clear text action, based on whether our find widget\n \/\/ contains some text\n\n if (pText.isEmpty())\n mGui->findEdit->removeAction(mClearFindTextAction);\n else\n mGui->findEdit->addAction(mClearFindTextAction, QLineEdit::TrailingPosition);\n\n \/\/ Let people know whether we can find\/replace\n\n emit canFindReplace(!findText().isEmpty());\n}\n\n\/\/==============================================================================\n\nvoid EditorFindReplaceWidget::updateClearReplaceTextAction(const QString &pText)\n{\n \/\/ Show\/hide our clear text action, based on whether our replace widget\n \/\/ contains some text\n\n if (pText.isEmpty())\n mGui->replaceEdit->removeAction(mClearReplaceTextAction);\n else\n mGui->replaceEdit->addAction(mClearReplaceTextAction, QLineEdit::TrailingPosition);\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace Editor\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Sergey Lisitsyn\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include \n#ifdef HAVE_LAPACK\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace shogun;\n\nCHessianLocallyLinearEmbedding::CHessianLocallyLinearEmbedding() :\n\t\tCLocallyLinearEmbedding()\n{\n}\n\nCHessianLocallyLinearEmbedding::~CHessianLocallyLinearEmbedding()\n{\n}\n\nbool CHessianLocallyLinearEmbedding::init(CFeatures* features)\n{\n\treturn true;\n}\n\nvoid CHessianLocallyLinearEmbedding::cleanup()\n{\n}\n\nSGMatrix CHessianLocallyLinearEmbedding::apply_to_feature_matrix(CFeatures* features)\n{\n\t\/\/ shorthand for simplefeatures\n\tCSimpleFeatures* simple_features = (CSimpleFeatures*) features;\n\tASSERT(simple_features);\n\n\t\/\/ get dimensionality and number of vectors of data\n\tint32_t dim = simple_features->get_num_features();\n\tASSERT(m_target_dim<=dim);\n\tint32_t N = simple_features->get_num_vectors();\n\tASSERT(m_k=(1+m_target_dim+dp));\n\n\t\/\/ compute distance matrix\n\tCDistance* distance = new CEuclidianDistance(simple_features,simple_features);\n\tSGMatrix neighborhood_matrix = get_neighborhood_matrix(distance);\n\n\t\/\/ init W (weight) matrix\n\tfloat64_t* W_matrix = SG_MALLOC(float64_t, N*N);\n\tfor (i=0; i feature_matrix = simple_features->get_feature_matrix();\n\n\tfor (i=0; i W_sgmatrix = SGMatrix(W_matrix,N,N);\n\tsimple_features->set_feature_matrix(find_null_space(W_sgmatrix,m_target_dim,false));\n\tW_sgmatrix.destroy_matrix();\n\n\treturn simple_features->get_feature_matrix();\n}\n\nSGVector CHessianLocallyLinearEmbedding::apply_to_feature_vector(SGVector vector)\n{\n\tSG_NOTIMPLEMENTED;\n\treturn vector;\n}\n\n#endif \/* HAVE_LAPACK *\/\nFixed memleak in HLLE\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Sergey Lisitsyn\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include \n#ifdef HAVE_LAPACK\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace shogun;\n\nCHessianLocallyLinearEmbedding::CHessianLocallyLinearEmbedding() :\n\t\tCLocallyLinearEmbedding()\n{\n}\n\nCHessianLocallyLinearEmbedding::~CHessianLocallyLinearEmbedding()\n{\n}\n\nbool CHessianLocallyLinearEmbedding::init(CFeatures* features)\n{\n\treturn true;\n}\n\nvoid CHessianLocallyLinearEmbedding::cleanup()\n{\n}\n\nSGMatrix CHessianLocallyLinearEmbedding::apply_to_feature_matrix(CFeatures* features)\n{\n\t\/\/ shorthand for simplefeatures\n\tCSimpleFeatures* simple_features = (CSimpleFeatures*) features;\n\tASSERT(simple_features);\n\n\t\/\/ get dimensionality and number of vectors of data\n\tint32_t dim = simple_features->get_num_features();\n\tASSERT(m_target_dim<=dim);\n\tint32_t N = simple_features->get_num_vectors();\n\tASSERT(m_k=(1+m_target_dim+dp));\n\n\t\/\/ compute distance matrix\n\tCDistance* distance = new CEuclidianDistance(simple_features,simple_features);\n\tSGMatrix neighborhood_matrix = get_neighborhood_matrix(distance);\n\n\t\/\/ init W (weight) matrix\n\tfloat64_t* W_matrix = SG_MALLOC(float64_t, N*N);\n\tfor (i=0; i feature_matrix = simple_features->get_feature_matrix();\n\n\tfor (i=0; i W_sgmatrix = SGMatrix(W_matrix,N,N);\n\tsimple_features->set_feature_matrix(find_null_space(W_sgmatrix,m_target_dim,false));\n\tW_sgmatrix.destroy_matrix();\n\n\treturn simple_features->get_feature_matrix();\n}\n\nSGVector CHessianLocallyLinearEmbedding::apply_to_feature_vector(SGVector vector)\n{\n\tSG_NOTIMPLEMENTED;\n\treturn vector;\n}\n\n#endif \/* HAVE_LAPACK *\/\n<|endoftext|>"} {"text":"#include \"apps\/HelloTensorflowFreeRTOS\/hello_world_model.h\"\n#include \"libs\/nxp\/rt1176-sdk\/board.h\"\n#include \"libs\/nxp\/rt1176-sdk\/peripherals.h\"\n#include \"libs\/nxp\/rt1176-sdk\/pin_mux.h\"\n#include \"third_party\/freertos_kernel\/include\/FreeRTOS.h\"\n#include \"third_party\/freertos_kernel\/include\/task.h\"\n#include \"third_party\/tflite-micro\/tensorflow\/lite\/micro\/all_ops_resolver.h\"\n#include \"third_party\/tflite-micro\/tensorflow\/lite\/micro\/micro_error_reporter.h\"\n#include \"third_party\/tflite-micro\/tensorflow\/lite\/micro\/micro_interpreter.h\"\n\n#include \n\nextern \"C\" void vApplicationStackOverflowHook(TaskHandle_t xTask, char *pcTaskName) {\n printf(\"Stack overflow in %s\\r\\n\", pcTaskName);\n}\n\nnamespace {\ntflite::ErrorReporter *error_reporter = nullptr;\nconst tflite::Model *model = nullptr;\ntflite::MicroInterpreter *interpreter = nullptr;\nTfLiteTensor *input = nullptr;\nTfLiteTensor *output = nullptr;\n\nint inference_count = 0;\nconst int kInferencesPerCycle = 1000;\nconst float kXrange = 2.f * 3.14159265359f;\n\nconst int kModelArenaSize = 4096;\nconst int kExtraArenaSize = 4096;\nconst int kTensorArenaSize = kModelArenaSize + kExtraArenaSize;\nuint8_t tensor_arena[kTensorArenaSize] __attribute__((aligned(16)));\n} \/\/ namespace\n\nstatic void loop() {\n float position = static_cast(inference_count) \/\n static_cast(kInferencesPerCycle);\n float x_val = position * kXrange;\n\n input->data.f[0] = x_val;\n\n TfLiteStatus invoke_status = interpreter->Invoke();\n if (invoke_status != kTfLiteOk) {\n TF_LITE_REPORT_ERROR(error_reporter, \"Invoke failed on x_val: %f\",\n static_cast(x_val));\n return;\n }\n\n float y_val = output->data.f[0];\n\n TF_LITE_REPORT_ERROR(error_reporter, \"x_val: %f y_val: %f\",\n static_cast(x_val),\n static_cast(y_val));\n\n ++inference_count;\n if (inference_count >= kInferencesPerCycle) {\n inference_count = 0;\n }\n}\nstatic void hello_task(void *param) {\n printf(\"Starting inference task...\\r\\n\");\n while (true) {\n loop();\n taskYIELD();\n }\n}\n\nextern \"C\" void app_main(void *param) {\n static tflite::MicroErrorReporter micro_error_reporter;\n error_reporter = µ_error_reporter;\n TF_LITE_REPORT_ERROR(error_reporter, \"HelloTensorflowFreeRTOS!\");\n\n model = tflite::GetModel(g_model);\n if (model->version() != TFLITE_SCHEMA_VERSION) {\n TF_LITE_REPORT_ERROR(error_reporter,\n \"Model schema version is %d, supported is %d\",\n model->version(), TFLITE_SCHEMA_VERSION);\n vTaskSuspend(nullptr);\n }\n\n static tflite::MicroMutableOpResolver<3> resolver(error_reporter);\n resolver.AddQuantize();\n resolver.AddDequantize();\n resolver.AddFullyConnected();\n static tflite::MicroInterpreter static_interpreter(\n model, resolver, tensor_arena, kTensorArenaSize, error_reporter);\n interpreter = &static_interpreter;\n\n TfLiteStatus allocate_status = interpreter->AllocateTensors();\n if (allocate_status != kTfLiteOk) {\n TF_LITE_REPORT_ERROR(error_reporter, \"AllocateTensors failed.\");\n vTaskSuspend(nullptr);\n }\n\n input = interpreter->input(0);\n output = interpreter->output(0);\n\n int ret;\n \/\/ High water mark testing showed that this task consumes about 218 words.\n \/\/ Set our stack size sufficiently large to accomodate.\n ret = xTaskCreate(hello_task, \"HelloTask\", configMINIMAL_STACK_SIZE * 3, nullptr, configMAX_PRIORITIES - 1, nullptr);\n if (ret != pdPASS) {\n printf(\"Failed to start HelloTask\\r\\n\");\n }\n while (true) {\n taskYIELD();\n }\n}\nFormat HelloTensorflowFreeRTOS app#include \n\n#include \"apps\/HelloTensorflowFreeRTOS\/hello_world_model.h\"\n#include \"libs\/nxp\/rt1176-sdk\/board.h\"\n#include \"libs\/nxp\/rt1176-sdk\/peripherals.h\"\n#include \"libs\/nxp\/rt1176-sdk\/pin_mux.h\"\n#include \"third_party\/freertos_kernel\/include\/FreeRTOS.h\"\n#include \"third_party\/freertos_kernel\/include\/task.h\"\n#include \"third_party\/tflite-micro\/tensorflow\/lite\/micro\/all_ops_resolver.h\"\n#include \"third_party\/tflite-micro\/tensorflow\/lite\/micro\/micro_error_reporter.h\"\n#include \"third_party\/tflite-micro\/tensorflow\/lite\/micro\/micro_interpreter.h\"\n\nextern \"C\" void vApplicationStackOverflowHook(TaskHandle_t xTask,\n char* pcTaskName) {\n printf(\"Stack overflow in %s\\r\\n\", pcTaskName);\n}\n\nnamespace {\ntflite::ErrorReporter* error_reporter = nullptr;\nconst tflite::Model* model = nullptr;\ntflite::MicroInterpreter* interpreter = nullptr;\nTfLiteTensor* input = nullptr;\nTfLiteTensor* output = nullptr;\n\nint inference_count = 0;\nconst int kInferencesPerCycle = 1000;\nconst float kXrange = 2.f * 3.14159265359f;\n\nconst int kModelArenaSize = 4096;\nconst int kExtraArenaSize = 4096;\nconst int kTensorArenaSize = kModelArenaSize + kExtraArenaSize;\nuint8_t tensor_arena[kTensorArenaSize] __attribute__((aligned(16)));\n} \/\/ namespace\n\nstatic void loop() {\n float position = static_cast(inference_count) \/\n static_cast(kInferencesPerCycle);\n float x_val = position * kXrange;\n\n input->data.f[0] = x_val;\n\n TfLiteStatus invoke_status = interpreter->Invoke();\n if (invoke_status != kTfLiteOk) {\n TF_LITE_REPORT_ERROR(error_reporter, \"Invoke failed on x_val: %f\",\n static_cast(x_val));\n return;\n }\n\n float y_val = output->data.f[0];\n\n TF_LITE_REPORT_ERROR(error_reporter, \"x_val: %f y_val: %f\",\n static_cast(x_val),\n static_cast(y_val));\n\n ++inference_count;\n if (inference_count >= kInferencesPerCycle) {\n inference_count = 0;\n }\n}\nstatic void hello_task(void* param) {\n printf(\"Starting inference task...\\r\\n\");\n while (true) {\n loop();\n taskYIELD();\n }\n}\n\nextern \"C\" void app_main(void* param) {\n static tflite::MicroErrorReporter micro_error_reporter;\n error_reporter = µ_error_reporter;\n TF_LITE_REPORT_ERROR(error_reporter, \"HelloTensorflowFreeRTOS!\");\n\n model = tflite::GetModel(g_model);\n if (model->version() != TFLITE_SCHEMA_VERSION) {\n TF_LITE_REPORT_ERROR(error_reporter,\n \"Model schema version is %d, supported is %d\",\n model->version(), TFLITE_SCHEMA_VERSION);\n vTaskSuspend(nullptr);\n }\n\n static tflite::MicroMutableOpResolver<3> resolver(error_reporter);\n resolver.AddQuantize();\n resolver.AddDequantize();\n resolver.AddFullyConnected();\n static tflite::MicroInterpreter static_interpreter(\n model, resolver, tensor_arena, kTensorArenaSize, error_reporter);\n interpreter = &static_interpreter;\n\n TfLiteStatus allocate_status = interpreter->AllocateTensors();\n if (allocate_status != kTfLiteOk) {\n TF_LITE_REPORT_ERROR(error_reporter, \"AllocateTensors failed.\");\n vTaskSuspend(nullptr);\n }\n\n input = interpreter->input(0);\n output = interpreter->output(0);\n\n int ret;\n \/\/ High water mark testing showed that this task consumes about 218 words.\n \/\/ Set our stack size sufficiently large to accomodate.\n ret = xTaskCreate(hello_task, \"HelloTask\", configMINIMAL_STACK_SIZE * 3,\n nullptr, configMAX_PRIORITIES - 1, nullptr);\n if (ret != pdPASS) {\n printf(\"Failed to start HelloTask\\r\\n\");\n }\n while (true) {\n taskYIELD();\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 1993-2010 NVIDIA Corporation. All rights reserved.\n *\n * Please refer to the NVIDIA end user license agreement (EULA) associated\n * with this source code for terms and conditions that govern your use of\n * this software. Any use, reproduction, disclosure, or distribution of\n * this software and related documentation outside the terms of the EULA\n * is strictly prohibited.\n *\n *\/\n \n \/*\n * This sample implements a separable convolution filter \n * of a 2D image with an arbitrary kernel.\n *\/\n\n\/\/ Utilities and system includes\n#include \n#include \n#include \n\n#include \"convolutionSeparable_common.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Reference CPU convolution\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nextern \"C\" void convolutionRowCPU(\n float *h_Result,\n float *h_Data,\n float *h_Kernel,\n int imageW,\n int imageH,\n int kernelR\n);\n\nextern \"C\" void convolutionColumnCPU(\n float *h_Result,\n float *h_Data,\n float *h_Kernel,\n int imageW,\n int imageH,\n int kernelR\n);\n\n\nvoid ParseArguments(int argc, char** argv, int& sizeW, int& sizeH)\n{\n for (int i = 0; i < argc; ++i) {\n if (strcmp(argv[i], \"--size\") == 0 ||\n strcmp(argv[i], \"-size\") == 0) \n {\n sizeW = atoi(argv[i+1]);\n sizeH = sizeW;\n }\n if (strcmp(argv[i], \"--sizeW\") == 0 ||\n strcmp(argv[i], \"-sizeW\") == 0) \n {\n sizeW = atoi(argv[i+1]);\n }\n if (strcmp(argv[i], \"--sizeH\") == 0 ||\n strcmp(argv[i], \"-sizeH\") == 0) \n {\n sizeH = atoi(argv[i+1]);\n }\n }\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Main program\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main(int argc, char **argv)\n{\n shrQAStart(argc, argv);\n\n \/\/ start logs\n shrSetLogFileName (\"convolutionSeparable.txt\");\n shrLog(\"%s Starting...\\n\\n\", argv[0]); \n\n float\n *h_Kernel,\n *h_Input,\n *h_Buffer,\n *h_OutputCPU,\n *h_OutputGPU;\n\n float\n *d_Input,\n *d_Output,\n *d_Buffer;\n\n\n int sizeW = 3072\/8;\n int sizeH = 3072\/16;\n ParseArguments(argc,argv,sizeW,sizeH);\n\n const int imageW = sizeW;\n const int imageH = sizeH;\n const int iterations = 1;\n\n unsigned int hTimer;\n\n \/\/Use command-line specified CUDA device, otherwise use device with highest Gflops\/s\n if ( shrCheckCmdLineFlag(argc, (const char **)argv, \"device\") )\n cutilDeviceInit(argc, argv);\n else\n cudaSetDevice( cutGetMaxGflopsDeviceId() );\n\n cutilCheckError(cutCreateTimer(&hTimer));\n\n shrLog(\"Image Width x Height = %i x %i\\n\\n\", imageW, imageH);\n shrLog(\"Allocating and initializing host arrays...\\n\");\n h_Kernel = (float *)malloc(KERNEL_LENGTH * sizeof(float));\n h_Input = (float *)malloc(imageW * imageH * sizeof(float));\n h_Buffer = (float *)malloc(imageW * imageH * sizeof(float));\n h_OutputCPU = (float *)malloc(imageW * imageH * sizeof(float));\n h_OutputGPU = (float *)malloc(imageW * imageH * sizeof(float));\n srand(200);\n for(unsigned int i = 0; i < KERNEL_LENGTH; i++)\n h_Kernel[i] = (float)(rand() % 16);\n for(unsigned i = 0; i < imageW * imageH; i++)\n h_Input[i] = (float)(rand() % 16);\n\n shrLog(\"Allocating and initializing CUDA arrays...\\n\");\n cutilSafeCall( cudaMalloc((void **)&d_Input, imageW * imageH * sizeof(float)) );\n cutilSafeCall( cudaMalloc((void **)&d_Output, imageW * imageH * sizeof(float)) );\n cutilSafeCall( cudaMalloc((void **)&d_Buffer , imageW * imageH * sizeof(float)) );\n\n setConvolutionKernel(h_Kernel);\n cutilSafeCall( cudaMemcpy(d_Input, h_Input, imageW * imageH * sizeof(float), cudaMemcpyHostToDevice) );\n\n shrLog(\"Running GPU convolution (%u identical iterations)...\\n\\n\", iterations);\n for(int i = -1; i < iterations; i++){\n \/\/i == -1 -- warmup iteration\n if(i == 0){\n cutilSafeCall( cutilDeviceSynchronize() );\n cutilCheckError( cutResetTimer(hTimer) );\n cutilCheckError( cutStartTimer(hTimer) );\n }\n\n convolutionRowsGPU(\n d_Buffer,\n d_Input,\n imageW,\n imageH\n );\n\n convolutionColumnsGPU(\n d_Output,\n d_Buffer,\n imageW,\n imageH\n );\n }\n cutilSafeCall( cutilDeviceSynchronize() );\n cutilCheckError(cutStopTimer(hTimer));\n double gpuTime = 0.001 * cutGetTimerValue(hTimer) \/ (double)iterations;\n shrLogEx(LOGBOTH | MASTER, 0, \"convolutionSeparable, Throughput = %.4f MPixels\/sec, Time = %.5f s, Size = %u Pixels, NumDevsUsed = %i, Workgroup = %u\\n\", \n (1.0e-6 * (double)(imageW * imageH)\/ gpuTime), gpuTime, (imageW * imageH), 1, 0);\n\n shrLog(\"\\nReading back GPU results...\\n\\n\");\n cutilSafeCall( cudaMemcpy(h_OutputGPU, d_Output, imageW * imageH * sizeof(float), cudaMemcpyDeviceToHost) );\n\n shrLog(\"Checking the results...\\n\");\n shrLog(\" ...running convolutionRowCPU()\\n\");\n convolutionRowCPU(\n h_Buffer,\n h_Input,\n h_Kernel,\n imageW,\n imageH,\n KERNEL_RADIUS\n );\n\n shrLog(\" ...running convolutionColumnCPU()\\n\");\n convolutionColumnCPU(\n h_OutputCPU,\n h_Buffer,\n h_Kernel,\n imageW,\n imageH,\n KERNEL_RADIUS\n );\n\n shrLog(\" ...comparing the results\\n\");\n double sum = 0, delta = 0;\n for(unsigned i = 0; i < imageW * imageH; i++){\n delta += (h_OutputGPU[i] - h_OutputCPU[i]) * (h_OutputGPU[i] - h_OutputCPU[i]);\n sum += h_OutputCPU[i] * h_OutputCPU[i];\n }\n double L2norm = sqrt(delta \/ sum);\n shrLog(\" ...Relative L2 norm: %E\\n\\n\", L2norm);\n shrLog((L2norm < 1e-6) ? \"PASSED\\n\\n\" : \"FAILED\\n\\n\");\n\n shrLog(\"Shutting down...\\n\");\n cutilSafeCall( cudaFree(d_Buffer ) );\n cutilSafeCall( cudaFree(d_Output) );\n cutilSafeCall( cudaFree(d_Input) );\n free(h_OutputGPU);\n free(h_OutputCPU);\n free(h_Buffer);\n free(h_Input);\n free(h_Kernel);\n\n cutilCheckError(cutDeleteTimer(hTimer));\n\n cutilDeviceReset();\n\n shrQAFinishExit(argc, (const char **)argv, ((L2norm < 1e-6) ? QA_PASSED : QA_FAILED) );\n}\nmaking convolution seperabel identical\/*\n * Copyright 1993-2010 NVIDIA Corporation. All rights reserved.\n *\n * Please refer to the NVIDIA end user license agreement (EULA) associated\n * with this source code for terms and conditions that govern your use of\n * this software. Any use, reproduction, disclosure, or distribution of\n * this software and related documentation outside the terms of the EULA\n * is strictly prohibited.\n *\n *\/\n \n \/*\n * This sample implements a separable convolution filter \n * of a 2D image with an arbitrary kernel.\n *\/\n\n\/\/ Utilities and system includes\n#include \n#include \n#include \n\n#include \"convolutionSeparable_common.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Reference CPU convolution\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nextern \"C\" void convolutionRowCPU(\n float *h_Result,\n float *h_Data,\n float *h_Kernel,\n int imageW,\n int imageH,\n int kernelR\n);\n\nextern \"C\" void convolutionColumnCPU(\n float *h_Result,\n float *h_Data,\n float *h_Kernel,\n int imageW,\n int imageH,\n int kernelR\n);\n\n\nvoid ParseArguments(int argc, char** argv, int& sizeW, int& sizeH)\n{\n for (int i = 0; i < argc; ++i) {\n if (strcmp(argv[i], \"--size\") == 0 ||\n strcmp(argv[i], \"-size\") == 0) \n {\n sizeW = atoi(argv[i+1]);\n sizeH = sizeW;\n }\n if (strcmp(argv[i], \"--sizeW\") == 0 ||\n strcmp(argv[i], \"-sizeW\") == 0) \n {\n sizeW = atoi(argv[i+1]);\n }\n if (strcmp(argv[i], \"--sizeH\") == 0 ||\n strcmp(argv[i], \"-sizeH\") == 0) \n {\n sizeH = atoi(argv[i+1]);\n }\n }\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Main program\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main(int argc, char **argv)\n{\n shrQAStart(argc, argv);\n\n \/\/ start logs\n shrSetLogFileName (\"convolutionSeparable.txt\");\n shrLog(\"%s Starting...\\n\\n\", argv[0]); \n\n float\n *h_Kernel,\n *h_Input,\n *h_Buffer,\n *h_OutputCPU,\n *h_OutputGPU;\n\n float\n *d_Input,\n *d_Output,\n *d_Buffer;\n\n\n int sizeW = 3072\/8;\n int sizeH = 3072\/16;\n ParseArguments(argc,argv,sizeW,sizeH);\n\n const int imageW = sizeW;\n const int imageH = sizeH;\n const int iterations = 1;\n\n unsigned int hTimer;\n\n \/\/Use command-line specified CUDA device, otherwise use device with highest Gflops\/s\n if ( shrCheckCmdLineFlag(argc, (const char **)argv, \"device\") )\n cutilDeviceInit(argc, argv);\n else\n cudaSetDevice( cutGetMaxGflopsDeviceId() );\n\n cutilCheckError(cutCreateTimer(&hTimer));\n\n shrLog(\"Image Width x Height = %i x %i\\n\\n\", imageW, imageH);\n shrLog(\"Allocating and initializing host arrays...\\n\");\n h_Kernel = (float *)malloc(KERNEL_LENGTH * sizeof(float));\n h_Input = (float *)malloc(imageW * imageH * sizeof(float));\n h_Buffer = (float *)malloc(imageW * imageH * sizeof(float));\n h_OutputCPU = (float *)malloc(imageW * imageH * sizeof(float));\n h_OutputGPU = (float *)malloc(imageW * imageH * sizeof(float));\n srand(200);\n for(unsigned int i = 0; i < KERNEL_LENGTH; i++)\n h_Kernel[i] = (float)(rand() % 16);\n for(unsigned i = 0; i < imageW * imageH; i++)\n h_Input[i] = (float)(rand() % 16);\n\n shrLog(\"Allocating and initializing CUDA arrays...\\n\");\n cutilSafeCall( cudaMalloc((void **)&d_Input, imageW * imageH * sizeof(float)) );\n cutilSafeCall( cudaMalloc((void **)&d_Output, imageW * imageH * sizeof(float)) );\n cutilSafeCall( cudaMalloc((void **)&d_Buffer , imageW * imageH * sizeof(float)) );\n\n setConvolutionKernel(h_Kernel);\n cutilSafeCall( cudaMemcpy(d_Input, h_Input, imageW * imageH * sizeof(float), cudaMemcpyHostToDevice) );\n\n shrLog(\"Running GPU convolution (%u identical iterations)...\\n\\n\", iterations);\n for(int i = 0; i < iterations; i++){\n \/\/i == -1 -- warmup iteration\n if(i == 0){\n cutilSafeCall( cutilDeviceSynchronize() );\n cutilCheckError( cutResetTimer(hTimer) );\n cutilCheckError( cutStartTimer(hTimer) );\n }\n\n convolutionRowsGPU(\n d_Buffer,\n d_Input,\n imageW,\n imageH\n );\n\n convolutionColumnsGPU(\n d_Output,\n d_Buffer,\n imageW,\n imageH\n );\n }\n cutilSafeCall( cutilDeviceSynchronize() );\n cutilCheckError(cutStopTimer(hTimer));\n double gpuTime = 0.001 * cutGetTimerValue(hTimer) \/ (double)iterations;\n shrLogEx(LOGBOTH | MASTER, 0, \"convolutionSeparable, Throughput = %.4f MPixels\/sec, Time = %.5f s, Size = %u Pixels, NumDevsUsed = %i, Workgroup = %u\\n\", \n (1.0e-6 * (double)(imageW * imageH)\/ gpuTime), gpuTime, (imageW * imageH), 1, 0);\n\n shrLog(\"\\nReading back GPU results...\\n\\n\");\n cutilSafeCall( cudaMemcpy(h_OutputGPU, d_Output, imageW * imageH * sizeof(float), cudaMemcpyDeviceToHost) );\n\n shrLog(\"Checking the results...\\n\");\n shrLog(\" ...running convolutionRowCPU()\\n\");\n convolutionRowCPU(\n h_Buffer,\n h_Input,\n h_Kernel,\n imageW,\n imageH,\n KERNEL_RADIUS\n );\n\n shrLog(\" ...running convolutionColumnCPU()\\n\");\n convolutionColumnCPU(\n h_OutputCPU,\n h_Buffer,\n h_Kernel,\n imageW,\n imageH,\n KERNEL_RADIUS\n );\n\n shrLog(\" ...comparing the results\\n\");\n double sum = 0, delta = 0;\n for(unsigned i = 0; i < imageW * imageH; i++){\n delta += (h_OutputGPU[i] - h_OutputCPU[i]) * (h_OutputGPU[i] - h_OutputCPU[i]);\n sum += h_OutputCPU[i] * h_OutputCPU[i];\n }\n double L2norm = sqrt(delta \/ sum);\n shrLog(\" ...Relative L2 norm: %E\\n\\n\", L2norm);\n shrLog((L2norm < 1e-6) ? \"PASSED\\n\\n\" : \"FAILED\\n\\n\");\n\n shrLog(\"Shutting down...\\n\");\n cutilSafeCall( cudaFree(d_Buffer ) );\n cutilSafeCall( cudaFree(d_Output) );\n cutilSafeCall( cudaFree(d_Input) );\n free(h_OutputGPU);\n free(h_OutputCPU);\n free(h_Buffer);\n free(h_Input);\n free(h_Kernel);\n\n cutilCheckError(cutDeleteTimer(hTimer));\n\n cutilDeviceReset();\n\n shrQAFinishExit(argc, (const char **)argv, ((L2norm < 1e-6) ? QA_PASSED : QA_FAILED) );\n}\n<|endoftext|>"} {"text":"#include \"processhelper.h\"\n#include \n\nconst char ProcessHelper::Stamp = '%';\nbool ProcessHelper::allGreen = true;\n\nProcessHelper::ProcessHelper(QObject *parent) :\n\tQObject(parent),\n\tprocess(new QProcess(this)),\n\texitCode(EXIT_SUCCESS)\n{\n\tprocess->setProgram(QStringLiteral(OUTDIR) + QStringLiteral(\"..\/..\/..\/..\/examples\/backgroundprocess\/DemoApp\/DemoApp\"));\n\n\tconnect(process, &QProcess::errorOccurred,\n\t\t\tthis, &ProcessHelper::errorOccurred);\n\tconnect(process, QOverload::of(&QProcess::finished),\n\t\t\tthis, &ProcessHelper::finished);\n}\n\nvoid ProcessHelper::setExitCode(int code)\n{\n\texitCode = code;\n}\n\nvoid ProcessHelper::start(const QByteArrayList &commands, bool logpath, int timeout)\n{\n\tQStringList s;\n\tforeach(auto c, commands)\n\t\ts.append(QString::fromUtf8(c));\n\tif(logpath)\n\t\ts.append({QStringLiteral(\"--logpath\"), logPath()});\n\tprocess->setArguments(s);\n\tprocess->start();\n\tQVERIFY2(process->waitForStarted(5000), qUtf8Printable(process->errorString()));\n\tQThread::msleep(timeout);\n}\n\nvoid ProcessHelper::waitForFinished()\n{\n\tif(!process->waitForFinished(5000)) {\n\t\tprocess->terminate();\n\t\tQFAIL(\"Process did not stop by itself\");\n\t}\n}\n\nvoid ProcessHelper::verifyLog(const QByteArrayList &log, bool isError)\n{\n\tallGreen = false;\n\n\tif(isError) {\n\t\tauto err = process->readAllStandardError();\n\t\tQBuffer buffer(&err);\n\t\tbuffer.open(QIODevice::ReadOnly | QIODevice::Text);\n\t\ttestLog(log, &buffer);\n\t\tbuffer.close();\n\t} else {\n\t\tauto out = process->readAllStandardOutput();\n\t\tQBuffer buffer(&out);\n\t\tbuffer.open(QIODevice::ReadOnly | QIODevice::Text);\n\t\ttestLog(log, &buffer);\n\t\tbuffer.close();\n\t}\n\n\tif(!allGreen)\n\t\tqDebug() << \"on arguments:\" << process->arguments();\n}\n\nvoid ProcessHelper::verifyLogEmpty(bool isError)\n{\n\tverifyLog(QByteArrayList(), isError);\n}\n\nvoid ProcessHelper::waitForFinished(const QList &helpers)\n{\n\tforeach (auto h, helpers)\n\t\th->waitForFinished();\n}\n\nvoid ProcessHelper::clearLog()\n{\n\tauto logFile = logPath();\n\tif(QFile::exists(logFile))\n\t\tQVERIFY(QFile::remove(logFile));\n}\n\nvoid ProcessHelper::verifyMasterLog(const QByteArrayList &log)\n{\n\tauto logFile = logPath();\n\tQFile file(logFile);\n\tQVERIFY(file.exists());\n\tQVERIFY2(file.open(QIODevice::ReadOnly | QIODevice::Text), qUtf8Printable(file.errorString()));\n\n\tallGreen = false;\n\ttestLog(log, &file);\n\tif(!allGreen)\n\t\tqDebug() << \"on master log\";\n\n\tfile.close();\n\tQVERIFY(file.remove());\n\n}\n\nvoid ProcessHelper::errorOccurred(QProcess::ProcessError error)\n{\n\tQ_UNUSED(error)\n\tQFAIL(qUtf8Printable(process->errorString()));\n}\n\nvoid ProcessHelper::finished(int exitCode, QProcess::ExitStatus exitStatus)\n{\n\tQCOMPARE(exitStatus, QProcess::NormalExit);\n\tQCOMPARE(exitCode, this->exitCode);\n}\n\nQString ProcessHelper::logPath()\n{\n\treturn QDir::current().absoluteFilePath(QStringLiteral(\"MasterTest.log\"));\n}\n\nvoid ProcessHelper::testLog(const QByteArrayList &log, QIODevice *device)\n{\n\tauto index = 0;\n\twhile(!device->atEnd()) {\n\t\tauto logStr = device->readLine().trimmed();\n\t\tif(logStr.isEmpty())\n\t\t\tcontinue;\n\n\t\tQVERIFY2(index < log.size(), logStr.constData());\n\t\tauto testStr = log[index++];\n\n\t\tauto testSplit = testStr.split(Stamp);\n\t\tif(testSplit.size() == 2) {\n\t\t\tQVERIFY2(logStr.startsWith(testSplit[0]), logStr.constData());\n\t\t\tQVERIFY2(logStr.endsWith(testSplit[1]), logStr.constData());\n\t\t} else\n\t\t\tQCOMPARE(logStr, testStr);\n\t}\n\tQCOMPARE(index, log.size());\n\tallGreen = true;\n}\nRevert \"try different method\"#include \"processhelper.h\"\n#include \n\nconst char ProcessHelper::Stamp = '%';\nbool ProcessHelper::allGreen = true;\n\nProcessHelper::ProcessHelper(QObject *parent) :\n\tQObject(parent),\n\tprocess(new QProcess(this)),\n\texitCode(EXIT_SUCCESS)\n{\n\tprocess->setProgram(QStringLiteral(OUTDIR) + QStringLiteral(\"..\/..\/..\/..\/examples\/backgroundprocess\/DemoApp\/DemoApp\"));\n\n\tconnect(process, &QProcess::errorOccurred,\n\t\t\tthis, &ProcessHelper::errorOccurred);\n\tconnect(process, QOverload::of(&QProcess::finished),\n\t\t\tthis, &ProcessHelper::finished);\n}\n\nvoid ProcessHelper::setExitCode(int code)\n{\n\texitCode = code;\n}\n\nvoid ProcessHelper::start(const QByteArrayList &commands, bool logpath, int timeout)\n{\n\tQStringList s;\n\tforeach(auto c, commands)\n\t\ts.append(QString::fromUtf8(c));\n\tif(logpath)\n\t\ts.append({QStringLiteral(\"--logpath\"), logPath()});\n\tprocess->setArguments(s);\n\tprocess->start();\n\tQVERIFY2(process->waitForStarted(5000), qUtf8Printable(process->errorString()));\n\tQThread::msleep(timeout);\n}\n\nvoid ProcessHelper::waitForFinished()\n{\n\tif(!process->waitForFinished(5000)) {\n\t\tprocess->terminate();\n\t\tQFAIL(\"Process did not stop by itself\");\n\t}\n}\n\nvoid ProcessHelper::verifyLog(const QByteArrayList &log, bool isError)\n{\n\tallGreen = false;\n\n\tif(isError) {\n\t\tauto err = process->readAllStandardError();\n\t\tQBuffer buffer(&err);\n\t\tbuffer.open(QIODevice::ReadOnly | QIODevice::Text);\n\t\ttestLog(log, &buffer);\n\t\tbuffer.close();\n\t} else\n\t\ttestLog(log, process);\n\n\tif(!allGreen)\n\t\tqDebug() << \"on arguments:\" << process->arguments();\n}\n\nvoid ProcessHelper::verifyLogEmpty(bool isError)\n{\n\tverifyLog(QByteArrayList(), isError);\n}\n\nvoid ProcessHelper::waitForFinished(const QList &helpers)\n{\n\tforeach (auto h, helpers)\n\t\th->waitForFinished();\n}\n\nvoid ProcessHelper::clearLog()\n{\n\tauto logFile = logPath();\n\tif(QFile::exists(logFile))\n\t\tQVERIFY(QFile::remove(logFile));\n}\n\nvoid ProcessHelper::verifyMasterLog(const QByteArrayList &log)\n{\n\tauto logFile = logPath();\n\tQFile file(logFile);\n\tQVERIFY(file.exists());\n\tQVERIFY2(file.open(QIODevice::ReadOnly | QIODevice::Text), qUtf8Printable(file.errorString()));\n\n\tallGreen = false;\n\ttestLog(log, &file);\n\tif(!allGreen)\n\t\tqDebug() << \"on master log\";\n\n\tfile.close();\n\tQVERIFY(file.remove());\n\n}\n\nvoid ProcessHelper::errorOccurred(QProcess::ProcessError error)\n{\n\tQ_UNUSED(error)\n\tQFAIL(qUtf8Printable(process->errorString()));\n}\n\nvoid ProcessHelper::finished(int exitCode, QProcess::ExitStatus exitStatus)\n{\n\tQCOMPARE(exitStatus, QProcess::NormalExit);\n\tQCOMPARE(exitCode, this->exitCode);\n}\n\nQString ProcessHelper::logPath()\n{\n\treturn QDir::current().absoluteFilePath(QStringLiteral(\"MasterTest.log\"));\n}\n\nvoid ProcessHelper::testLog(const QByteArrayList &log, QIODevice *device)\n{\n\tauto index = 0;\n\twhile(!device->atEnd()) {\n\t\tauto logStr = device->readLine().trimmed();\n\t\tif(logStr.isEmpty())\n\t\t\tcontinue;\n\n\t\tQVERIFY2(index < log.size(), logStr.constData());\n\t\tauto testStr = log[index++];\n\n\t\tauto testSplit = testStr.split(Stamp);\n\t\tif(testSplit.size() == 2) {\n\t\t\tQVERIFY2(logStr.startsWith(testSplit[0]), logStr.constData());\n\t\t\tQVERIFY2(logStr.endsWith(testSplit[1]), logStr.constData());\n\t\t} else\n\t\t\tQCOMPARE(logStr, testStr);\n\t}\n\tQCOMPARE(index, log.size());\n\tallGreen = true;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#if defined(OS_MACOSX)\n#include \"base\/mac\/mac_util.h\"\n#endif\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/extensions\/tab_helper.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome\/common\/extensions\/feature_switch.h\"\n#include \"chrome\/common\/extensions\/features\/base_feature_provider.h\"\n#include \"chrome\/common\/extensions\/features\/complex_feature.h\"\n#include \"chrome\/common\/extensions\/features\/feature.h\"\n#include \"chrome\/common\/extensions\/features\/simple_feature.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/common\/content_switches.h\"\n\nnamespace chrome {\n\nnamespace {\n\nconst char kExtensionId[] = \"ddchlicdkolnonkihahngkmmmjnjlkkf\";\n\nclass TabCaptureApiTest : public ExtensionApiTest {\n public:\n TabCaptureApiTest() {}\n\n void AddExtensionToCommandLineWhitelist() {\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kWhitelistedExtensionID, kExtensionId);\n }\n};\n\n} \/\/ namespace\n\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTests) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n\n#if defined(OS_WIN)\n \/\/ TODO(justinlin): Disabled for WinXP due to timeout issues.\n if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n return;\n }\n#endif\n\n AddExtensionToCommandLineWhitelist();\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"api_tests.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTestsAudio) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n\n#if defined(OS_WIN)\n \/\/ TODO(justinlin): Disabled for WinXP due to timeout issues.\n if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n return;\n }\n#endif\n\n AddExtensionToCommandLineWhitelist();\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"api_tests_audio.html\")) << message_;\n}\n\n\/\/ http:\/\/crbug.com\/177163\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_EndToEnd DISABLED_EndToEnd\n#else\n#define MAYBE_EndToEnd EndToEnd\n#endif\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_EndToEnd) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n\n#if defined(OS_WIN)\n \/\/ TODO(justinlin): Disabled for WinXP due to timeout issues.\n if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n return;\n }\n#endif\n#if defined(OS_MACOSX)\n \/\/ TODO(miu): Disabled for Mac OS X 10.6 due to timeout issues.\n \/\/ http:\/\/crbug.com\/174640\n if (base::mac::IsOSSnowLeopard())\n return;\n#endif\n\n AddExtensionToCommandLineWhitelist();\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"end_to_end.html\")) << message_;\n}\n\n\/\/ http:\/\/crbug.com\/177163\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_GetUserMediaTest DISABLED_GetUserMediaTest\n#else\n#define MAYBE_GetUserMediaTest GetUserMediaTest\n#endif\n\/\/ Test that we can't get tabCapture streams using GetUserMedia directly.\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GetUserMediaTest) {\n ExtensionTestMessageListener listener(\"ready\", true);\n\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"get_user_media_test.html\")) << message_;\n\n EXPECT_TRUE(listener.WaitUntilSatisfied());\n\n content::OpenURLParams params(GURL(\"about:blank\"), content::Referrer(),\n NEW_FOREGROUND_TAB,\n content::PAGE_TRANSITION_LINK, false);\n content::WebContents* web_contents = browser()->OpenURL(params);\n\n content::RenderViewHost* const rvh = web_contents->GetRenderViewHost();\n int render_process_id = rvh->GetProcess()->GetID();\n int routing_id = rvh->GetRoutingID();\n\n listener.Reply(base::StringPrintf(\"%i:%i\", render_process_id, routing_id));\n\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ http:\/\/crbug.com\/177163\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_ActiveTabPermission DISABLED_ActiveTabPermission\n#else\n#define MAYBE_ActiveTabPermission ActiveTabPermission\n#endif\n\/\/ Make sure tabCapture.capture only works if the tab has been granted\n\/\/ permission via an extension icon click or the extension is whitelisted.\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ActiveTabPermission) {\n ExtensionTestMessageListener before_open_tab(\"ready1\", true);\n ExtensionTestMessageListener before_grant_permission(\"ready2\", true);\n ExtensionTestMessageListener before_open_new_tab(\"ready3\", true);\n ExtensionTestMessageListener before_whitelist_extension(\"ready4\", true);\n\n ASSERT_TRUE(RunExtensionSubtest(\n \"tab_capture\/experimental\", \"active_tab_permission_test.html\"))\n << message_;\n\n \/\/ Open a new tab and make sure capture is denied.\n EXPECT_TRUE(before_open_tab.WaitUntilSatisfied());\n content::OpenURLParams params(GURL(\"http:\/\/google.com\"), content::Referrer(),\n NEW_FOREGROUND_TAB,\n content::PAGE_TRANSITION_LINK, false);\n content::WebContents* web_contents = browser()->OpenURL(params);\n before_open_tab.Reply(\"\");\n\n \/\/ Grant permission and make sure capture succeeds.\n EXPECT_TRUE(before_grant_permission.WaitUntilSatisfied());\n ExtensionService* extension_service =\n Profile::FromBrowserContext(web_contents->GetBrowserContext())\n ->GetExtensionService();\n const extensions::Extension* extension =\n extension_service->GetExtensionById(kExtensionId, false);\n extensions::TabHelper::FromWebContents(web_contents)\n ->active_tab_permission_granter()->GrantIfRequested(extension);\n before_grant_permission.Reply(\"\");\n\n \/\/ Open a new tab and make sure capture is denied.\n EXPECT_TRUE(before_open_new_tab.WaitUntilSatisfied());\n browser()->OpenURL(params);\n before_open_new_tab.Reply(\"\");\n\n \/\/ Add extension to whitelist and make sure capture succeeds.\n EXPECT_TRUE(before_whitelist_extension.WaitUntilSatisfied());\n AddExtensionToCommandLineWhitelist();\n before_whitelist_extension.Reply(\"\");\n\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n} \/\/ namespace chrome\nDisable TabCaptureApiTest.EndToEnd for Linux (non-Aura) debug builds.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#if defined(OS_MACOSX)\n#include \"base\/mac\/mac_util.h\"\n#endif\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/extensions\/tab_helper.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome\/common\/extensions\/feature_switch.h\"\n#include \"chrome\/common\/extensions\/features\/base_feature_provider.h\"\n#include \"chrome\/common\/extensions\/features\/complex_feature.h\"\n#include \"chrome\/common\/extensions\/features\/feature.h\"\n#include \"chrome\/common\/extensions\/features\/simple_feature.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/common\/content_switches.h\"\n\nnamespace chrome {\n\nnamespace {\n\nconst char kExtensionId[] = \"ddchlicdkolnonkihahngkmmmjnjlkkf\";\n\nclass TabCaptureApiTest : public ExtensionApiTest {\n public:\n TabCaptureApiTest() {}\n\n void AddExtensionToCommandLineWhitelist() {\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kWhitelistedExtensionID, kExtensionId);\n }\n};\n\n} \/\/ namespace\n\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTests) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n\n#if defined(OS_WIN)\n \/\/ TODO(justinlin): Disabled for WinXP due to timeout issues.\n if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n return;\n }\n#endif\n\n AddExtensionToCommandLineWhitelist();\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"api_tests.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTestsAudio) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n\n#if defined(OS_WIN)\n \/\/ TODO(justinlin): Disabled for WinXP due to timeout issues.\n if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n return;\n }\n#endif\n\n AddExtensionToCommandLineWhitelist();\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"api_tests_audio.html\")) << message_;\n}\n\n\/\/ http:\/\/crbug.com\/177163 -- for OS_WIN debug build flakiness\n\/\/ http:\/\/crbug.com\/251863 -- for OS_LINUX (non-Aura) debug build flakiness\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_EndToEnd DISABLED_EndToEnd\n#elif defined(OS_LINUX) && !defined(USE_AURA) && !defined(NDEBUG)\n#define MAYBE_EndToEnd DISABLED_EndToEnd\n#else\n#define MAYBE_EndToEnd EndToEnd\n#endif\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_EndToEnd) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n\n#if defined(OS_WIN)\n \/\/ TODO(justinlin): Disabled for WinXP due to timeout issues.\n if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n return;\n }\n#endif\n#if defined(OS_MACOSX)\n \/\/ TODO(miu): Disabled for Mac OS X 10.6 due to timeout issues.\n \/\/ http:\/\/crbug.com\/174640\n if (base::mac::IsOSSnowLeopard())\n return;\n#endif\n\n AddExtensionToCommandLineWhitelist();\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"end_to_end.html\")) << message_;\n}\n\n\/\/ http:\/\/crbug.com\/177163\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_GetUserMediaTest DISABLED_GetUserMediaTest\n#else\n#define MAYBE_GetUserMediaTest GetUserMediaTest\n#endif\n\/\/ Test that we can't get tabCapture streams using GetUserMedia directly.\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GetUserMediaTest) {\n ExtensionTestMessageListener listener(\"ready\", true);\n\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"get_user_media_test.html\")) << message_;\n\n EXPECT_TRUE(listener.WaitUntilSatisfied());\n\n content::OpenURLParams params(GURL(\"about:blank\"), content::Referrer(),\n NEW_FOREGROUND_TAB,\n content::PAGE_TRANSITION_LINK, false);\n content::WebContents* web_contents = browser()->OpenURL(params);\n\n content::RenderViewHost* const rvh = web_contents->GetRenderViewHost();\n int render_process_id = rvh->GetProcess()->GetID();\n int routing_id = rvh->GetRoutingID();\n\n listener.Reply(base::StringPrintf(\"%i:%i\", render_process_id, routing_id));\n\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ http:\/\/crbug.com\/177163\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_ActiveTabPermission DISABLED_ActiveTabPermission\n#else\n#define MAYBE_ActiveTabPermission ActiveTabPermission\n#endif\n\/\/ Make sure tabCapture.capture only works if the tab has been granted\n\/\/ permission via an extension icon click or the extension is whitelisted.\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ActiveTabPermission) {\n ExtensionTestMessageListener before_open_tab(\"ready1\", true);\n ExtensionTestMessageListener before_grant_permission(\"ready2\", true);\n ExtensionTestMessageListener before_open_new_tab(\"ready3\", true);\n ExtensionTestMessageListener before_whitelist_extension(\"ready4\", true);\n\n ASSERT_TRUE(RunExtensionSubtest(\n \"tab_capture\/experimental\", \"active_tab_permission_test.html\"))\n << message_;\n\n \/\/ Open a new tab and make sure capture is denied.\n EXPECT_TRUE(before_open_tab.WaitUntilSatisfied());\n content::OpenURLParams params(GURL(\"http:\/\/google.com\"), content::Referrer(),\n NEW_FOREGROUND_TAB,\n content::PAGE_TRANSITION_LINK, false);\n content::WebContents* web_contents = browser()->OpenURL(params);\n before_open_tab.Reply(\"\");\n\n \/\/ Grant permission and make sure capture succeeds.\n EXPECT_TRUE(before_grant_permission.WaitUntilSatisfied());\n ExtensionService* extension_service =\n Profile::FromBrowserContext(web_contents->GetBrowserContext())\n ->GetExtensionService();\n const extensions::Extension* extension =\n extension_service->GetExtensionById(kExtensionId, false);\n extensions::TabHelper::FromWebContents(web_contents)\n ->active_tab_permission_granter()->GrantIfRequested(extension);\n before_grant_permission.Reply(\"\");\n\n \/\/ Open a new tab and make sure capture is denied.\n EXPECT_TRUE(before_open_new_tab.WaitUntilSatisfied());\n browser()->OpenURL(params);\n before_open_new_tab.Reply(\"\");\n\n \/\/ Add extension to whitelist and make sure capture succeeds.\n EXPECT_TRUE(before_whitelist_extension.WaitUntilSatisfied());\n AddExtensionToCommandLineWhitelist();\n before_whitelist_extension.Reply(\"\");\n\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n} \/\/ namespace chrome\n<|endoftext|>"} {"text":"\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"valuesFactory.h\"\n\n#include \n\n#include \n#include \n#include \n\nusing namespace twoDModel::constraints::details;\n\nconst QString typeOfNull = \"undefined\";\n\nValuesFactory::ValuesFactory(Variables &variables, const Objects &objects, StatusReporter &status)\n\t: mVariables(variables)\n\t, mObjects(objects)\n\t, mStatus(status)\n{\n}\n\nValue ValuesFactory::invalidValue() const\n{\n\treturn []() { return QVariant(); };\n}\n\nValue ValuesFactory::boolValue(bool value) const\n{\n\treturn [value]() { return value; };\n}\n\nValue ValuesFactory::intValue(int value) const\n{\n\treturn [value]() { return value; };\n}\n\nValue ValuesFactory::doubleValue(qreal value) const\n{\n\treturn [value]() { return value; };\n}\n\nValue ValuesFactory::stringValue(const QString &value) const\n{\n\treturn [value]() { return value; };\n}\n\nValue ValuesFactory::variableValue(const QString &name) const\n{\n\treturn [this, name]() {\n\t\tconst QStringList parts = name.split('.');\n\t\tif (parts.isEmpty()) {\n\t\t\treportError(QObject::tr(\"Requesting variable value with empty name\"));\n\t\t\treturn QVariant();\n\t\t}\n\n\t\tif (!mVariables.contains(parts.first())) {\n\t\t\t\/\/ We do not mind the situation when trying to read non-declared varible\n\t\t\t\/\/ because really can`t manage the order in which Qt will call event checking,\n\t\t\t\/\/ so some variables (for example counters) can be checked before setted.\n\t\t\treturn QVariant();\n\t\t}\n\n\t\treturn propertyChain(mVariables[parts.first()], parts.mid(1), parts.first());\n\t};\n}\n\nValue ValuesFactory::typeOf(const QString &objectId) const\n{\n\treturn [this, objectId]() {\n\t\tif (!mObjects.contains(objectId)) {\n\t\t\treturn typeOfNull;\n\t\t}\n\n\t\tQObject const *object = mObjects[objectId];\n\t\treturn object == nullptr ? typeOfNull : object->metaObject()->className();\n\t};\n}\n\nValue ValuesFactory::objectState(const QString &path) const\n{\n\treturn [this, path]() {\n\t\tconst QStringList parts = path.split('.', QString::SkipEmptyParts);\n\t\tif (parts.isEmpty()) {\n\t\t\treportError(QObject::tr(\"Object path is empty!\"));\n\t\t\treturn QVariant();\n\t\t}\n\n\t\tQString objectId = parts.first();\n\t\tif (!mObjects.contains(objectId)) {\n\t\t\treportError(QObject::tr(\"No such object: %1\").arg(objectId));\n\t\t\treturn QVariant();\n\t\t}\n\n\t\tint lastObjectPart = 1;\n\t\twhile (lastObjectPart < parts.count() && mObjects.contains(objectId + \".\" + parts[lastObjectPart])) {\n\t\t\tobjectId += \".\" + parts[lastObjectPart];\n\t\t\t++lastObjectPart;\n\t\t}\n\n\t\treturn propertyChain(QVariant::fromValue(mObjects[objectId]), parts.mid(lastObjectPart), objectId);\n\t};\n}\n\nValue ValuesFactory::timestamp(const utils::TimelineInterface &timeline) const\n{\n\treturn [&timeline]() { return timeline.timestamp(); };\n}\n\nValue ValuesFactory::unaryMinus(const Value &value) const\n{\n\treturn [value]() { return -value().toInt(); };\n}\n\nValue ValuesFactory::abs(const Value &value) const\n{\n\treturn [value]() { return qAbs(value().toInt()); };\n}\n\nValue ValuesFactory::sum(const Value &left, const Value &right) const\n{\n\treturn [left, right]() { return left().toInt() + right().toInt(); };\n}\n\nValue ValuesFactory::difference(const Value &left, const Value &right) const\n{\n\treturn [left, right]() { return left().toInt() - right().toInt(); };\n}\n\nValue ValuesFactory::max(const Value &left, const Value &right) const\n{\n\treturn [left, right]() { return qMax(left().toInt(), right().toInt()); };\n}\n\nValue ValuesFactory::min(const Value &left, const Value &right) const\n{\n\treturn [left, right]() { return qMin(left().toInt(), right().toInt()); };\n}\n\nValue ValuesFactory::distance(const Value &point1, const Value &point2) const\n{\n\treturn [point1, point2]() { return mathUtils::Geometry::distance(point1().toPoint(), point2().toPoint()); };\n}\n\nValue ValuesFactory::boundingRect(const Value &items) const\n{\n\treturn [this, items]() {\n\t\tbool empty = true;\n\t\tint xMin = INT_MAX;\n\t\tint yMin = INT_MAX;\n\t\tint xMax = INT_MIN;\n\t\tint yMax = INT_MIN;\n\t\titerate(items(), [this, &xMin, &yMin, &xMax, &yMax, &empty](const QVariant &item) {\n\t\t\tbool hasBoundingRect{};\n\t\t\tconst QRect boundingRect = propertyOf(item, \"boundingRect\", &hasBoundingRect).toRect();\n\t\t\tif (hasBoundingRect) {\n\t\t\t\tempty = false;\n\t\t\t\txMin = qMin(xMin, boundingRect.left());\n\t\t\t\tyMin = qMin(yMin, boundingRect.top());\n\t\t\t\txMax = qMax(xMax, boundingRect.right());\n\t\t\t\tyMax = qMax(yMax, boundingRect.bottom());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tbool hasX{};\n\t\t\tbool hasY{};\n\t\t\tconst int x = propertyOf(item, \"x\", &hasX).toInt();\n\t\t\tconst int y = propertyOf(item, \"y\", &hasY).toInt();\n\t\t\tif (hasX && hasY) {\n\t\t\t\tempty = false;\n\t\t\t\txMin = qMin(xMin, x);\n\t\t\t\tyMin = qMin(yMin, y);\n\t\t\t\txMax = qMax(xMax, x);\n\t\t\t\tyMax = qMax(yMax, y);\n\t\t\t}\n\t\t});\n\n\t\treturn empty ? QRect() : QRect(QPoint(xMin, yMin), QPoint(xMax, yMax));\n\t};\n}\n\nQVariant ValuesFactory::propertyChain(const QVariant &value\n\t\t, const QStringList &propertyChain, const QString &objectAlias) const\n{\n\tQVariant currentValue = value;\n\tQString currentObjectAlias = objectAlias;\n\tfor (const QString &property : propertyChain) {\n\t\tcurrentValue = propertyOf(currentValue, property, currentObjectAlias);\n\t\tcurrentObjectAlias += \".\" + property;\n\t\tif (!currentValue.isValid()) {\n\t\t\treturn QVariant();\n\t\t}\n\t}\n\n\treturn currentValue;\n}\n\nQVariant ValuesFactory::propertyOf(const QVariant &value, const QString &property, const QString &objectAlias) const\n{\n\tbool hasProperty{};\n\tbool unknownType{};\n\tconst QVariant result = propertyOf(value, property, &hasProperty, &unknownType);\n\n\tif (unknownType) {\n\t\treportError(QObject::tr(\"Unknown type of object \\\"%1\\\"\").arg(objectAlias));\n\t\treturn QVariant();\n\t}\n\n\tif (!hasProperty) {\n\t\treportError(QObject::tr(\"Object \\\"%1\\\" has no property \\\"%2\\\"\").arg(objectAlias, property));\n\t\treturn QVariant();\n\t}\n\n\treturn result;\n}\n\nQVariant ValuesFactory::propertyOf(const QVariant &value, const QString &property\n\t\t, bool *hasProperty, bool *unknownType) const\n{\n\tQVariant result;\n\n\t\/\/\/ This code is here just because Dmitry can. And everyone else is lazy enough.\n\thasProperty && (*hasProperty = false);\n\tunknownType && (*unknownType = false);\n\n\t\/\/ Here must be enumerated all types whoose properties we can obtain.\n\tif (value.canConvert()) {\n\t\tresult = propertyOf(value.value(), property, hasProperty);\n\t} else if (value.canConvert()) {\n\t\tresult = propertyOf(value.value(), property, hasProperty);\n\t} else if (value.canConvert()) {\n\t\tresult = propertyOf(value.value(), property, hasProperty);\n\t} else if (value.canConvert()) {\n\t\tresult = propertyOf(value.value(), property, hasProperty);\n\t} else {\n\t\tunknownType && (*unknownType = true);\n\t}\n\n\treturn result;\n}\n\nQVariant ValuesFactory::propertyOf(const QObject *object, const QString &property, bool *ok) const\n{\n\tok && (*ok = true);\n\tif (!object) {\n\t\treturn QVariant();\n\t}\n\n\tconst int index = object->metaObject()->indexOfProperty(qPrintable(property));\n\tif (index < 0) {\n\t\tok && (*ok = false);\n\t\treturn QVariant();\n\t}\n\n\treturn object->property(qPrintable(property));\n}\n\nQVariant ValuesFactory::propertyOf(const QPoint &point, const QString &property, bool *ok) const\n{\n\tok && (*ok = true);\n\tif (property == \"x\") {\n\t\treturn point.x();\n\t}\n\n\tif (property == \"y\") {\n\t\treturn point.y();\n\t}\n\n\tok && (*ok = false);\n\treturn QVariant();\n}\n\nQVariant ValuesFactory::propertyOf(const QRect &rect, const QString &property, bool *ok) const\n{\n\tok && (*ok = true);\n\tif (property == \"x\") {\n\t\treturn rect.x();\n\t}\n\n\tif (property == \"y\") {\n\t\treturn rect.y();\n\t}\n\n\tif (property == \"width\") {\n\t\treturn rect.width();\n\t}\n\n\tif (property == \"height\") {\n\t\treturn rect.height();\n\t}\n\n\tok && (*ok = false);\n\treturn QVariant();\n}\n\nQVariant ValuesFactory::propertyOf(const QVariantList &list, const QString &property, bool *ok) const\n{\n\tok && (*ok = true);\n\tif (property == \"first\") {\n\t\treturn list.first();\n\t}\n\n\tif (property == \"last\") {\n\t\treturn list.last();\n\t}\n\n\tif (property == \"size\") {\n\t\treturn list.size();\n\t}\n\n\tif (property == \"isEmpty\") {\n\t\treturn list.isEmpty();\n\t}\n\n\tok && (*ok = false);\n\treturn QVariant();\n}\n\nvoid ValuesFactory::iterate(const QVariant &collection, const std::function &visitor) const\n{\n\tif (collection.canConvert()) {\n\t\t\/\/ A good iteration, without copying. Object sets are good for large collections.\n\t\tcollection.value()->iterate(visitor);\n\t} else if (collection.canConvert()) {\n\t\t\/\/ Warning: the whole list will be copied here!\n\t\tfor (const QVariant &item : collection.value()) {\n\t\t\tvisitor(item);\n\t\t}\n\t} else {\n\t\t\/\/ Fallback case. This is not very nice situation is we get here, but it still can work.\n\t\tvisitor(collection);\n\t}\n}\n\nvoid ValuesFactory::reportError(const QString &message) const\n{\n\temit mStatus.checkerError(message);\n}\nFixed crash in checker when trying to get member of an empty list\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"valuesFactory.h\"\n\n#include \n\n#include \n#include \n#include \n\nusing namespace twoDModel::constraints::details;\n\nconst QString typeOfNull = \"undefined\";\n\nValuesFactory::ValuesFactory(Variables &variables, const Objects &objects, StatusReporter &status)\n\t: mVariables(variables)\n\t, mObjects(objects)\n\t, mStatus(status)\n{\n}\n\nValue ValuesFactory::invalidValue() const\n{\n\treturn []() { return QVariant(); };\n}\n\nValue ValuesFactory::boolValue(bool value) const\n{\n\treturn [value]() { return value; };\n}\n\nValue ValuesFactory::intValue(int value) const\n{\n\treturn [value]() { return value; };\n}\n\nValue ValuesFactory::doubleValue(qreal value) const\n{\n\treturn [value]() { return value; };\n}\n\nValue ValuesFactory::stringValue(const QString &value) const\n{\n\treturn [value]() { return value; };\n}\n\nValue ValuesFactory::variableValue(const QString &name) const\n{\n\treturn [this, name]() {\n\t\tconst QStringList parts = name.split('.');\n\t\tif (parts.isEmpty()) {\n\t\t\treportError(QObject::tr(\"Requesting variable value with empty name\"));\n\t\t\treturn QVariant();\n\t\t}\n\n\t\tif (!mVariables.contains(parts.first())) {\n\t\t\t\/\/ We do not mind the situation when trying to read non-declared varible\n\t\t\t\/\/ because really can`t manage the order in which Qt will call event checking,\n\t\t\t\/\/ so some variables (for example counters) can be checked before setted.\n\t\t\treturn QVariant();\n\t\t}\n\n\t\treturn propertyChain(mVariables[parts.first()], parts.mid(1), parts.first());\n\t};\n}\n\nValue ValuesFactory::typeOf(const QString &objectId) const\n{\n\treturn [this, objectId]() {\n\t\tif (!mObjects.contains(objectId)) {\n\t\t\treturn typeOfNull;\n\t\t}\n\n\t\tQObject const *object = mObjects[objectId];\n\t\treturn object == nullptr ? typeOfNull : object->metaObject()->className();\n\t};\n}\n\nValue ValuesFactory::objectState(const QString &path) const\n{\n\treturn [this, path]() {\n\t\tconst QStringList parts = path.split('.', QString::SkipEmptyParts);\n\t\tif (parts.isEmpty()) {\n\t\t\treportError(QObject::tr(\"Object path is empty!\"));\n\t\t\treturn QVariant();\n\t\t}\n\n\t\tQString objectId = parts.first();\n\t\tif (!mObjects.contains(objectId)) {\n\t\t\treportError(QObject::tr(\"No such object: %1\").arg(objectId));\n\t\t\treturn QVariant();\n\t\t}\n\n\t\tint lastObjectPart = 1;\n\t\twhile (lastObjectPart < parts.count() && mObjects.contains(objectId + \".\" + parts[lastObjectPart])) {\n\t\t\tobjectId += \".\" + parts[lastObjectPart];\n\t\t\t++lastObjectPart;\n\t\t}\n\n\t\treturn propertyChain(QVariant::fromValue(mObjects[objectId]), parts.mid(lastObjectPart), objectId);\n\t};\n}\n\nValue ValuesFactory::timestamp(const utils::TimelineInterface &timeline) const\n{\n\treturn [&timeline]() { return timeline.timestamp(); };\n}\n\nValue ValuesFactory::unaryMinus(const Value &value) const\n{\n\treturn [value]() { return -value().toInt(); };\n}\n\nValue ValuesFactory::abs(const Value &value) const\n{\n\treturn [value]() { return qAbs(value().toInt()); };\n}\n\nValue ValuesFactory::sum(const Value &left, const Value &right) const\n{\n\treturn [left, right]() { return left().toInt() + right().toInt(); };\n}\n\nValue ValuesFactory::difference(const Value &left, const Value &right) const\n{\n\treturn [left, right]() { return left().toInt() - right().toInt(); };\n}\n\nValue ValuesFactory::max(const Value &left, const Value &right) const\n{\n\treturn [left, right]() { return qMax(left().toInt(), right().toInt()); };\n}\n\nValue ValuesFactory::min(const Value &left, const Value &right) const\n{\n\treturn [left, right]() { return qMin(left().toInt(), right().toInt()); };\n}\n\nValue ValuesFactory::distance(const Value &point1, const Value &point2) const\n{\n\treturn [point1, point2]() { return mathUtils::Geometry::distance(point1().toPoint(), point2().toPoint()); };\n}\n\nValue ValuesFactory::boundingRect(const Value &items) const\n{\n\treturn [this, items]() {\n\t\tbool empty = true;\n\t\tint xMin = INT_MAX;\n\t\tint yMin = INT_MAX;\n\t\tint xMax = INT_MIN;\n\t\tint yMax = INT_MIN;\n\t\titerate(items(), [this, &xMin, &yMin, &xMax, &yMax, &empty](const QVariant &item) {\n\t\t\tbool hasBoundingRect{};\n\t\t\tconst QRect boundingRect = propertyOf(item, \"boundingRect\", &hasBoundingRect).toRect();\n\t\t\tif (hasBoundingRect) {\n\t\t\t\tempty = false;\n\t\t\t\txMin = qMin(xMin, boundingRect.left());\n\t\t\t\tyMin = qMin(yMin, boundingRect.top());\n\t\t\t\txMax = qMax(xMax, boundingRect.right());\n\t\t\t\tyMax = qMax(yMax, boundingRect.bottom());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tbool hasX{};\n\t\t\tbool hasY{};\n\t\t\tconst int x = propertyOf(item, \"x\", &hasX).toInt();\n\t\t\tconst int y = propertyOf(item, \"y\", &hasY).toInt();\n\t\t\tif (hasX && hasY) {\n\t\t\t\tempty = false;\n\t\t\t\txMin = qMin(xMin, x);\n\t\t\t\tyMin = qMin(yMin, y);\n\t\t\t\txMax = qMax(xMax, x);\n\t\t\t\tyMax = qMax(yMax, y);\n\t\t\t}\n\t\t});\n\n\t\treturn empty ? QRect() : QRect(QPoint(xMin, yMin), QPoint(xMax, yMax));\n\t};\n}\n\nQVariant ValuesFactory::propertyChain(const QVariant &value\n\t\t, const QStringList &propertyChain, const QString &objectAlias) const\n{\n\tQVariant currentValue = value;\n\tQString currentObjectAlias = objectAlias;\n\tfor (const QString &property : propertyChain) {\n\t\tcurrentValue = propertyOf(currentValue, property, currentObjectAlias);\n\t\tcurrentObjectAlias += \".\" + property;\n\t\tif (!currentValue.isValid()) {\n\t\t\treturn QVariant();\n\t\t}\n\t}\n\n\treturn currentValue;\n}\n\nQVariant ValuesFactory::propertyOf(const QVariant &value, const QString &property, const QString &objectAlias) const\n{\n\tbool hasProperty{};\n\tbool unknownType{};\n\tconst QVariant result = propertyOf(value, property, &hasProperty, &unknownType);\n\n\tif (unknownType) {\n\t\treportError(QObject::tr(\"Unknown type of object \\\"%1\\\"\").arg(objectAlias));\n\t\treturn QVariant();\n\t}\n\n\tif (!hasProperty) {\n\t\treportError(QObject::tr(\"Object \\\"%1\\\" has no property \\\"%2\\\"\").arg(objectAlias, property));\n\t\treturn QVariant();\n\t}\n\n\treturn result;\n}\n\nQVariant ValuesFactory::propertyOf(const QVariant &value, const QString &property\n\t\t, bool *hasProperty, bool *unknownType) const\n{\n\tQVariant result;\n\n\t\/\/\/ This code is here just because Dmitry can. And everyone else is lazy enough.\n\thasProperty && (*hasProperty = false);\n\tunknownType && (*unknownType = false);\n\n\t\/\/ Here must be enumerated all types whoose properties we can obtain.\n\tif (value.canConvert()) {\n\t\tresult = propertyOf(value.value(), property, hasProperty);\n\t} else if (value.canConvert()) {\n\t\tresult = propertyOf(value.value(), property, hasProperty);\n\t} else if (value.canConvert()) {\n\t\tresult = propertyOf(value.value(), property, hasProperty);\n\t} else if (value.canConvert()) {\n\t\tresult = propertyOf(value.value(), property, hasProperty);\n\t} else {\n\t\tunknownType && (*unknownType = true);\n\t}\n\n\treturn result;\n}\n\nQVariant ValuesFactory::propertyOf(const QObject *object, const QString &property, bool *ok) const\n{\n\tok && (*ok = true);\n\tif (!object) {\n\t\treturn QVariant();\n\t}\n\n\tconst int index = object->metaObject()->indexOfProperty(qPrintable(property));\n\tif (index < 0) {\n\t\tok && (*ok = false);\n\t\treturn QVariant();\n\t}\n\n\treturn object->property(qPrintable(property));\n}\n\nQVariant ValuesFactory::propertyOf(const QPoint &point, const QString &property, bool *ok) const\n{\n\tok && (*ok = true);\n\tif (property == \"x\") {\n\t\treturn point.x();\n\t}\n\n\tif (property == \"y\") {\n\t\treturn point.y();\n\t}\n\n\tok && (*ok = false);\n\treturn QVariant();\n}\n\nQVariant ValuesFactory::propertyOf(const QRect &rect, const QString &property, bool *ok) const\n{\n\tok && (*ok = true);\n\tif (property == \"x\") {\n\t\treturn rect.x();\n\t}\n\n\tif (property == \"y\") {\n\t\treturn rect.y();\n\t}\n\n\tif (property == \"width\") {\n\t\treturn rect.width();\n\t}\n\n\tif (property == \"height\") {\n\t\treturn rect.height();\n\t}\n\n\tok && (*ok = false);\n\treturn QVariant();\n}\n\nQVariant ValuesFactory::propertyOf(const QVariantList &list, const QString &property, bool *ok) const\n{\n\tok && (*ok = true);\n\tif (property == \"first\" && !list.isEmpty()) {\n\t\treturn list.first();\n\t}\n\n\tif (property == \"last\" && !list.isEmpty()) {\n\t\treturn list.last();\n\t}\n\n\tif (property == \"size\") {\n\t\treturn list.size();\n\t}\n\n\tif (property == \"isEmpty\") {\n\t\treturn list.isEmpty();\n\t}\n\n\tok && (*ok = false);\n\treturn QVariant();\n}\n\nvoid ValuesFactory::iterate(const QVariant &collection, const std::function &visitor) const\n{\n\tif (collection.canConvert()) {\n\t\t\/\/ A good iteration, without copying. Object sets are good for large collections.\n\t\tcollection.value()->iterate(visitor);\n\t} else if (collection.canConvert()) {\n\t\t\/\/ Warning: the whole list will be copied here!\n\t\tfor (const QVariant &item : collection.value()) {\n\t\t\tvisitor(item);\n\t\t}\n\t} else {\n\t\t\/\/ Fallback case. This is not very nice situation is we get here, but it still can work.\n\t\tvisitor(collection);\n\t}\n}\n\nvoid ValuesFactory::reportError(const QString &message) const\n{\n\temit mStatus.checkerError(message);\n}\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n *\/\n#ifndef PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_\n#define PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::registration::CorrespondenceRejectorFeatures::getRemainingCorrespondences (\n const pcl::Correspondences& original_correspondences, \n pcl::Correspondences& remaining_correspondences)\n{\n unsigned int number_valid_correspondences = 0;\n remaining_correspondences.resize (original_correspondences.size ());\n \/\/ For each set of features, go over each correspondence from input_correspondences_\n for (size_t i = 0; i < input_correspondences_->size (); ++i)\n {\n \/\/ Go over the map of features\n for (FeaturesMap::const_iterator it = features_map_.begin (); it != features_map_.end (); ++it)\n {\n \/\/ Check if the score in feature space is above the given threshold\n \/\/ (assume that the number of feature correspondenecs is the same as the number of point correspondences)\n if (!it->second->isCorrespondenceValid (i))\n break;\n\n remaining_correspondences[number_valid_correspondences] = original_correspondences[i];\n ++number_valid_correspondences;\n }\n }\n remaining_correspondences.resize (number_valid_correspondences);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void \npcl::registration::CorrespondenceRejectorFeatures::setSourceFeature (\n const typename pcl::PointCloud::ConstPtr &source_feature, const std::string &key)\n{\n if (features_map_.count (key) == 0)\n features_map_[key].reset (new FeatureContainer);\n boost::static_pointer_cast > (features_map_[key])->setSourceFeature (source_feature);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline typename pcl::PointCloud::ConstPtr \npcl::registration::CorrespondenceRejectorFeatures::getSourceFeature (const std::string &key)\n{\n if (features_map_.count (key) == 0)\n return (boost::shared_ptr > ());\n else\n return (boost::static_pointer_cast > (features_map_[key])->getSourceFeature ());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void \npcl::registration::CorrespondenceRejectorFeatures::setTargetFeature (\n const typename pcl::PointCloud::ConstPtr &target_feature, const std::string &key)\n{\n if (features_map_.count (key) == 0)\n features_map_[key].reset (new FeatureContainer);\n boost::static_pointer_cast > (features_map_[key])->setTargetFeature (target_feature);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline typename pcl::PointCloud::ConstPtr \npcl::registration::CorrespondenceRejectorFeatures::getTargetFeature (const std::string &key)\n{\n typedef pcl::PointCloud FeatureCloud;\n typedef typename FeatureCloud::ConstPtr FeatureCloudConstPtr;\n\n if (features_map_.count (key) == 0)\n return (boost::shared_ptr > ());\n else\n return (boost::static_pointer_cast > (features_map_[key])->getTargetFeature ());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void \npcl::registration::CorrespondenceRejectorFeatures::setDistanceThreshold (\n double thresh, const std::string &key)\n{\n if (features_map_.count (key) == 0)\n features_map_[key].reset (new FeatureContainer);\n boost::static_pointer_cast > (features_map_[key])->setDistanceThreshold (thresh);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ninline bool\npcl::registration::CorrespondenceRejectorFeatures::hasValidFeatures ()\n{\n if (features_map_.empty ())\n return (false);\n typename FeaturesMap::const_iterator feature_itr;\n for (feature_itr = features_map_.begin (); feature_itr != features_map_.end (); ++feature_itr)\n if (!feature_itr->second->isValid ())\n return (false);\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void \npcl::registration::CorrespondenceRejectorFeatures::setFeatureRepresentation (\n const typename pcl::PointRepresentation::ConstPtr &fr,\n const std::string &key)\n{\n if (features_map_.count (key) == 0)\n features_map_[key].reset (new FeatureContainer);\n boost::static_pointer_cast > (features_map_[key])->setFeatureRepresentation (fr);\n}\n\n\n#endif \/* PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_ *\/\nfixed a visual studio compilation error\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n *\/\n#ifndef PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_\n#define PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\npcl::registration::CorrespondenceRejectorFeatures::getRemainingCorrespondences (\n const pcl::Correspondences& original_correspondences, \n pcl::Correspondences& remaining_correspondences)\n{\n unsigned int number_valid_correspondences = 0;\n remaining_correspondences.resize (original_correspondences.size ());\n \/\/ For each set of features, go over each correspondence from input_correspondences_\n for (size_t i = 0; i < input_correspondences_->size (); ++i)\n {\n \/\/ Go over the map of features\n for (FeaturesMap::const_iterator it = features_map_.begin (); it != features_map_.end (); ++it)\n {\n \/\/ Check if the score in feature space is above the given threshold\n \/\/ (assume that the number of feature correspondenecs is the same as the number of point correspondences)\n if (!it->second->isCorrespondenceValid (i))\n break;\n\n remaining_correspondences[number_valid_correspondences] = original_correspondences[i];\n ++number_valid_correspondences;\n }\n }\n remaining_correspondences.resize (number_valid_correspondences);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void \npcl::registration::CorrespondenceRejectorFeatures::setSourceFeature (\n const typename pcl::PointCloud::ConstPtr &source_feature, const std::string &key)\n{\n if (features_map_.count (key) == 0)\n features_map_[key].reset (new FeatureContainer);\n boost::static_pointer_cast > (features_map_[key])->setSourceFeature (source_feature);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline typename pcl::PointCloud::ConstPtr \npcl::registration::CorrespondenceRejectorFeatures::getSourceFeature (const std::string &key)\n{\n if (features_map_.count (key) == 0)\n return (boost::shared_ptr > ());\n else\n return (boost::static_pointer_cast > (features_map_[key])->getSourceFeature ());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void \npcl::registration::CorrespondenceRejectorFeatures::setTargetFeature (\n const typename pcl::PointCloud::ConstPtr &target_feature, const std::string &key)\n{\n if (features_map_.count (key) == 0)\n features_map_[key].reset (new FeatureContainer);\n boost::static_pointer_cast > (features_map_[key])->setTargetFeature (target_feature);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline typename pcl::PointCloud::ConstPtr \npcl::registration::CorrespondenceRejectorFeatures::getTargetFeature (const std::string &key)\n{\n typedef pcl::PointCloud FeatureCloud;\n typedef typename FeatureCloud::ConstPtr FeatureCloudConstPtr;\n\n if (features_map_.count (key) == 0)\n return (boost::shared_ptr > ());\n else\n return (boost::static_pointer_cast > (features_map_[key])->getTargetFeature ());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void \npcl::registration::CorrespondenceRejectorFeatures::setDistanceThreshold (\n double thresh, const std::string &key)\n{\n if (features_map_.count (key) == 0)\n features_map_[key].reset (new FeatureContainer);\n boost::static_pointer_cast > (features_map_[key])->setDistanceThreshold (thresh);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ninline bool\npcl::registration::CorrespondenceRejectorFeatures::hasValidFeatures ()\n{\n if (features_map_.empty ())\n return (false);\n FeaturesMap::const_iterator feature_itr;\n for (feature_itr = features_map_.begin (); feature_itr != features_map_.end (); ++feature_itr)\n if (!feature_itr->second->isValid ())\n return (false);\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void \npcl::registration::CorrespondenceRejectorFeatures::setFeatureRepresentation (\n const typename pcl::PointRepresentation::ConstPtr &fr,\n const std::string &key)\n{\n if (features_map_.count (key) == 0)\n features_map_[key].reset (new FeatureContainer);\n boost::static_pointer_cast > (features_map_[key])->setFeatureRepresentation (fr);\n}\n\n\n#endif \/* PCL_REGISTRATION_IMPL_CORRESPONDENCE_REJECTION_FEATURES_HPP_ *\/\n<|endoftext|>"} {"text":"#include \"Stdafx.h\"\n\n#include \"AimpExtension.h\"\n#include \"..\\Utils.h\"\n#include \"ManagedAimpCore.h\"\n\nnamespace AIMP\n{\n namespace SDK\n {\n \/\/template\n \/\/TAimpNativeObject* AimpExtension::MakeObject(REFIID objectId)\n \/\/{\n \/\/ TAimpNativeObject* object = NULL;\n\n \/\/ if (GetCore()->CreateObject(objectId, (void**)&object) == S_OK)\n \/\/ {\n \/\/ return object;\n \/\/ }\n\n \/\/ return NULL;\n \/\/}\n\n IAIMPString* AimpExtension::GetAimpString(String ^value)\n {\n IAIMPString *strObject = MakeObject(IID_IAIMPString);\n pin_ptr strDate = PtrToStringChars(value);\n strObject->SetData((PWCHAR)strDate, value->Length);\n return strObject;\n }\n\n IAIMPImage* AimpExtension::GetImage(System::Drawing::Bitmap^ image)\n {\n System::IO::MemoryStream ^stream;\n IAIMPStream *aimpStream = NULL;\n IAIMPImage *img = NULL;\n\n try\n {\n stream = gcnew System::IO::MemoryStream();\n image->Save(stream, System::Drawing::Imaging::ImageFormat::Png);\n array^ buffer = stream->ToArray();\n\n if (Utils::CheckResult(GetCore()->CreateObject(IID_IAIMPMemoryStream, (void**)&aimpStream)) == AIMP::SDK::AimpActionResult::Ok\n && Utils::CheckResult(GetCore()->CreateObject(IID_IAIMPImage, (void**)&img)) == AIMP::SDK::AimpActionResult::Ok)\n {\n aimpStream->SetSize(stream->Length);\n pin_ptr p = &buffer[0];\n unsigned char* pby = p;\n if (Utils::CheckResult(aimpStream->Write(pby, (int)stream->Length, nullptr)) == AIMP::SDK::AimpActionResult::Ok)\n {\n img->LoadFromStream(aimpStream);\n }\n\n return img;\n }\n }\n finally\n {\n if (stream != nullptr)\n {\n stream->Close();\n }\n aimpStream->Release();\n aimpStream = NULL;\n }\n\n return NULL;\n }\n\n IAIMPCore* AimpExtension::GetCore()\n {\n return AIMP::SDK::ManagedAimpCore::GetAimpCore();\n }\n\n AIMP::SDK::Visuals::AimpVisualData^ AimpExtension::PAIMPVisualDataToManaged(PAIMPVisualData data)\n {\n AIMP::SDK::Visuals::AimpVisualData ^result = gcnew AIMP::SDK::Visuals::AimpVisualData();\n result->Peaks = gcnew array(2);\n result->Spectrum = gcnew array^>(3);\n result->WaveForm = gcnew array^>(2);\n\n result->Peaks[0] = data->Peaks[0];\n result->Peaks[1] = data->Peaks[1];\n\n for (int i = 0; i < 3; i++)\n {\n array ^arr = gcnew array(AIMP_VISUAL_SPECTRUM_MAX);\n for (int j = 0; j < AIMP_VISUAL_SPECTRUM_MAX; j++)\n {\n arr[j] = data->Spectrum[i][j];\n }\n result->Spectrum[i] = arr;\n }\n\n for (int i = 0; i < 2; i++)\n {\n array ^arr = gcnew array(AIMP_VISUAL_WAVEFORM_MAX);\n for (int j = 0; j < AIMP_VISUAL_WAVEFORM_MAX; j++)\n {\n arr[j] = data->WaveForm[i][j];\n }\n result->WaveForm[i] = arr;\n }\n\n return result;\n }\n\n System::Drawing::Bitmap^ AimpExtension::GetBitmap(IAIMPImageContainer* imageContainer)\n {\n IAIMPImage* image = NULL;\n try\n {\n if (Utils::CheckResult(ManagedAimpCore::GetAimpCore()->CreateObject(IID_IAIMPImage, (void**)&image)) == AimpActionResult::Ok)\n {\n return nullptr;\n }\n\n imageContainer->CreateImage(&image);\n\n if (image == NULL)\n {\n return nullptr;\n }\n return GetBitmap(image);\n }\n finally\n {\n image->Release();\n image = NULL;\n }\n\n return nullptr;\n }\n\n System::Drawing::Bitmap^ AimpExtension::GetBitmap(IAIMPImage* image)\n {\n SIZE size;\n if (Utils::CheckResult(image->GetSize(&size)) == AimpActionResult::Ok)\n {\n if (size.cx == 0 || size.cy == 0)\n {\n return nullptr;\n }\n\n System::Drawing::Bitmap^ bmp = gcnew System::Drawing::Bitmap(size.cx, size.cy);\n\n IAIMPStream *stream;\n AIMP::SDK::ManagedAimpCore::GetAimpCore()->CreateObject(IID_IAIMPMemoryStream, (void**)&stream);\n image->SaveToStream(stream, AIMP_IMAGE_FORMAT_PNG);\n if (stream->GetSize() > 0)\n {\n Int64 size = stream->GetSize();\n unsigned char *buf = new unsigned char[(int)size];\n HRESULT r = stream->Seek(0, AIMP_STREAM_SEEKMODE_FROM_BEGINNING);\n r = stream->Read(buf, (int)size);\n\n System::IO::MemoryStream^ strm = gcnew System::IO::MemoryStream();\n try\n {\n for (int i = 0; i < size; i++)\n {\n strm->WriteByte(buf[i]);\n }\n bmp = gcnew System::Drawing::Bitmap(strm);\n }\n finally\n {\n strm->Close();\n strm = nullptr;\n\n delete[] buf;\n stream->Release();\n image->Release();\n stream = NULL;\n image = NULL;\n }\n }\n\n return bmp;\n }\n\n return nullptr;\n }\n\n IAIMPImageContainer* AimpExtension::ToContainer(System::Drawing::Bitmap ^image)\n {\n IAIMPImageContainer *container;\n if (Utils::CheckResult(ManagedAimpCore::GetAimpCore()->CreateObject(IID_IAIMPImageContainer, (void**)&container)) == AimpActionResult::Ok)\n {\n System::IO::Stream ^stream = nullptr;\n try\n {\n stream = gcnew System::IO::MemoryStream();\n image->Save(stream, System::Drawing::Imaging::ImageFormat::Jpeg);\n stream->Seek(0, System::IO::SeekOrigin::Begin);\n if (Utils::CheckResult(container->SetDataSize((DWORD)stream->Length)) != AimpActionResult::Ok)\n {\n return NULL;\n }\n\n byte *b = container->GetData();\n for (int i = 0; i < stream->Length - 1; i++)\n {\n b[i] = stream->ReadByte();\n }\n\n return container;\n }\n finally\n {\n if (stream != nullptr)\n {\n stream->Close();\n }\n }\n }\n\n return NULL;\n }\n\n String^ AimpExtension::GetString(IAIMPString* value)\n {\n return gcnew String(value->GetData());\n }\n\n AimpActionResult PropertyListExtension::SetObject(IAIMPPropertyList* propertyList, int propertyId, IUnknown *value)\n {\n return Utils::CheckResult(propertyList->SetValueAsObject(propertyId, value));\n }\n\n AimpActionResult PropertyListExtension::SetString(IAIMPPropertyList* propertyList, int propertyId, String ^value)\n {\n \/\/ No need to process empty value\n if (String::IsNullOrWhiteSpace(value))\n {\n return AimpActionResult::InvalidArguments;\n }\n\n IAIMPString *str = NULL;\n try\n {\n str = AimpExtension::GetAimpString(value);\n return SetObject(propertyList, propertyId, str);\n }\n finally\n {\n str->Release();\n str = NULL;\n }\n\n return AimpActionResult::Unexpected;\n }\n\n AimpActionResult PropertyListExtension::SetInt32(IAIMPPropertyList* propertyList, int propertyId, int value)\n {\n return Utils::CheckResult(propertyList->SetValueAsInt32(propertyId, value));\n }\n\n AimpActionResult PropertyListExtension::SetInt64(IAIMPPropertyList* propertyList, int propertyId, Int64 value)\n {\n return Utils::CheckResult(propertyList->SetValueAsInt64(propertyId, value));\n }\n\n AimpActionResult PropertyListExtension::SetFloat(IAIMPPropertyList* propertyList, int propertyId, double value)\n {\n return Utils::CheckResult(propertyList->SetValueAsFloat(propertyId, value));\n }\n\n AimpActionResult PropertyListExtension::SetBool(IAIMPPropertyList* propertyList, int propertyId, bool value)\n {\n return SetInt32(propertyList, propertyId, value ? 1 : 0);\n }\n\n AimpActionResult PropertyListExtension::GetString(IAIMPPropertyList* propertyList, int propertyId, String^% value)\n {\n IAIMPString* str = NULL;\n String ^val = String::Empty;\n\n try\n {\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsObject(propertyId, IID_IAIMPString, (void**)&str));\n if (result != AimpActionResult::Ok)\n {\n value = String::Empty;\n return result;\n }\n\n if (str != NULL)\n {\n result = GetString(str, val);\n value = val;\n return result;\n }\n }\n catch (System::Exception ^ex)\n {\n return AimpActionResult::Fail;\n }\n finally\n {\n if (str != NULL)\n {\n str->Release();\n str = NULL;\n }\n }\n\n return AimpActionResult::Unexpected;\n }\n\n AimpActionResult PropertyListExtension::GetString(IAIMPString* aimpString, String^% value)\n {\n value = gcnew String(aimpString->GetData());\n return AimpActionResult::Ok;\n }\n\n AimpActionResult PropertyListExtension::GetObject(IAIMPPropertyList* propertyList, int propertyId, REFIID objectId, void** value)\n {\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsObject(propertyId, objectId, (void**)&value));\n return result;\n }\n\n AimpActionResult PropertyListExtension::GetInt32(IAIMPPropertyList* propertyList, int propertyId, int %value)\n {\n int val = 0;\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsInt32(propertyId, &val));\n value = val;\n return result;\n }\n\n AimpActionResult PropertyListExtension::GetInt64(IAIMPPropertyList* propertyList, int propertyId, Int64 %value)\n {\n Int64 val = 0;\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsInt64(propertyId, &val));\n value = val;\n return result;\n }\n\n AimpActionResult PropertyListExtension::GetFloat(IAIMPPropertyList* propertyList, int propertyId, double %value)\n {\n double val = 0;\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsFloat(propertyId, &val));\n value = val;\n return result;\n }\n\n AimpActionResult PropertyListExtension::GetBool(IAIMPPropertyList* propertyList, int propertyId, bool %value)\n {\n int *val = 0;\n AimpActionResult result = GetInt32(propertyList, propertyId, *val);\n value = val > 0;\n return result;\n }\n\n String^ PropertyListExtension::GetString(IAIMPPropertyList *propertyList, int propertyId)\n {\n String^ val = String::Empty;\n if (GetString(propertyList, propertyId, *&val) == AimpActionResult::Ok)\n {\n return val;\n }\n\n return val;\n }\n\n int PropertyListExtension::GetInt32(IAIMPPropertyList *propertyList, int propertyId)\n {\n int val = 0;\n if (GetInt32(propertyList, propertyId, val) == AimpActionResult::Ok)\n {\n return val;\n }\n\n return 0;\n }\n\n Int64 PropertyListExtension::GetInt64(IAIMPPropertyList *propertyList, int propertyId)\n {\n Int64 val;\n if (GetInt64(propertyList, propertyId, val) == AimpActionResult::Ok)\n {\n return val;\n }\n\n return 0;\n }\n\n double PropertyListExtension::GetFloat(IAIMPPropertyList *propertyList, int propertyId)\n {\n double val;\n if (GetFloat(propertyList, propertyId, val) == AimpActionResult::Ok)\n {\n return val;\n }\n\n return 0;\n }\n\n bool PropertyListExtension::GetBool(IAIMPPropertyList *propertyList, int propertyId)\n {\n bool val;\n if (GetBool(propertyList, propertyId, val) == AimpActionResult::Ok)\n {\n return val;\n }\n\n return false;\n }\n\n AimpActionResult PropertyListExtension::GetVariant(IAIMPPropertyList2 *propertyList, int propertyId, Object^% value)\n {\n VARIANT *val = NULL;\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsVariant(propertyId, val));\n value = AimpExtension::FromVaiant(val);\n \/\/value = AimpExtension::ToManaged(val);\n \/\/value = val->cVal;\n \/\/value = AIMP::SDK::Variant();\n return result;\n }\n\n AimpActionResult PropertyListExtension::SetVariant(IAIMPPropertyList2 *propertyList, int propertyId, Object^% val)\n {\n return AimpActionResult::NotImplemented;\n }\n\n VARIANT AimpExtension::ToVariant(System::Object^ objectValue)\n {\n VARIANT varTag;\n VariantInit(&varTag);\n IntPtr h = IntPtr(&varTag);\n System::Runtime::InteropServices::Marshal::GetNativeVariantForObject(objectValue, h);\n return varTag;\n }\n\n System::Object^ AimpExtension::FromVaiant(VARIANT* variant)\n {\n void *p = variant;\n return System::Runtime::InteropServices::Marshal::GetObjectForNativeVariant(IntPtr(p));\n }\n }\n}\nFix GetObject at PropertyList#include \"Stdafx.h\"\n\n#include \"AimpExtension.h\"\n#include \"..\\Utils.h\"\n#include \"ManagedAimpCore.h\"\n\nnamespace AIMP\n{\n namespace SDK\n {\n \/\/template\n \/\/TAimpNativeObject* AimpExtension::MakeObject(REFIID objectId)\n \/\/{\n \/\/ TAimpNativeObject* object = NULL;\n\n \/\/ if (GetCore()->CreateObject(objectId, (void**)&object) == S_OK)\n \/\/ {\n \/\/ return object;\n \/\/ }\n\n \/\/ return NULL;\n \/\/}\n\n IAIMPString* AimpExtension::GetAimpString(String ^value)\n {\n IAIMPString *strObject = MakeObject(IID_IAIMPString);\n pin_ptr strDate = PtrToStringChars(value);\n strObject->SetData((PWCHAR)strDate, value->Length);\n return strObject;\n }\n\n IAIMPImage* AimpExtension::GetImage(System::Drawing::Bitmap^ image)\n {\n System::IO::MemoryStream ^stream;\n IAIMPStream *aimpStream = NULL;\n IAIMPImage *img = NULL;\n\n try\n {\n stream = gcnew System::IO::MemoryStream();\n image->Save(stream, System::Drawing::Imaging::ImageFormat::Png);\n array^ buffer = stream->ToArray();\n\n if (Utils::CheckResult(GetCore()->CreateObject(IID_IAIMPMemoryStream, (void**)&aimpStream)) == AIMP::SDK::AimpActionResult::Ok\n && Utils::CheckResult(GetCore()->CreateObject(IID_IAIMPImage, (void**)&img)) == AIMP::SDK::AimpActionResult::Ok)\n {\n aimpStream->SetSize(stream->Length);\n pin_ptr p = &buffer[0];\n unsigned char* pby = p;\n if (Utils::CheckResult(aimpStream->Write(pby, (int)stream->Length, nullptr)) == AIMP::SDK::AimpActionResult::Ok)\n {\n img->LoadFromStream(aimpStream);\n }\n\n return img;\n }\n }\n finally\n {\n if (stream != nullptr)\n {\n stream->Close();\n }\n aimpStream->Release();\n aimpStream = NULL;\n }\n\n return NULL;\n }\n\n IAIMPCore* AimpExtension::GetCore()\n {\n return AIMP::SDK::ManagedAimpCore::GetAimpCore();\n }\n\n AIMP::SDK::Visuals::AimpVisualData^ AimpExtension::PAIMPVisualDataToManaged(PAIMPVisualData data)\n {\n AIMP::SDK::Visuals::AimpVisualData ^result = gcnew AIMP::SDK::Visuals::AimpVisualData();\n result->Peaks = gcnew array(2);\n result->Spectrum = gcnew array^>(3);\n result->WaveForm = gcnew array^>(2);\n\n result->Peaks[0] = data->Peaks[0];\n result->Peaks[1] = data->Peaks[1];\n\n for (int i = 0; i < 3; i++)\n {\n array ^arr = gcnew array(AIMP_VISUAL_SPECTRUM_MAX);\n for (int j = 0; j < AIMP_VISUAL_SPECTRUM_MAX; j++)\n {\n arr[j] = data->Spectrum[i][j];\n }\n result->Spectrum[i] = arr;\n }\n\n for (int i = 0; i < 2; i++)\n {\n array ^arr = gcnew array(AIMP_VISUAL_WAVEFORM_MAX);\n for (int j = 0; j < AIMP_VISUAL_WAVEFORM_MAX; j++)\n {\n arr[j] = data->WaveForm[i][j];\n }\n result->WaveForm[i] = arr;\n }\n\n return result;\n }\n\n System::Drawing::Bitmap^ AimpExtension::GetBitmap(IAIMPImageContainer* imageContainer)\n {\n IAIMPImage* image = NULL;\n try\n {\n if (Utils::CheckResult(ManagedAimpCore::GetAimpCore()->CreateObject(IID_IAIMPImage, (void**)&image)) == AimpActionResult::Ok)\n {\n return nullptr;\n }\n\n imageContainer->CreateImage(&image);\n\n if (image == NULL)\n {\n return nullptr;\n }\n return GetBitmap(image);\n }\n finally\n {\n image->Release();\n image = NULL;\n }\n\n return nullptr;\n }\n\n System::Drawing::Bitmap^ AimpExtension::GetBitmap(IAIMPImage* image)\n {\n SIZE size;\n if (Utils::CheckResult(image->GetSize(&size)) == AimpActionResult::Ok)\n {\n if (size.cx == 0 || size.cy == 0)\n {\n return nullptr;\n }\n\n System::Drawing::Bitmap^ bmp = gcnew System::Drawing::Bitmap(size.cx, size.cy);\n\n IAIMPStream *stream;\n AIMP::SDK::ManagedAimpCore::GetAimpCore()->CreateObject(IID_IAIMPMemoryStream, (void**)&stream);\n image->SaveToStream(stream, AIMP_IMAGE_FORMAT_PNG);\n if (stream->GetSize() > 0)\n {\n Int64 size = stream->GetSize();\n unsigned char *buf = new unsigned char[(int)size];\n HRESULT r = stream->Seek(0, AIMP_STREAM_SEEKMODE_FROM_BEGINNING);\n r = stream->Read(buf, (int)size);\n\n System::IO::MemoryStream^ strm = gcnew System::IO::MemoryStream();\n try\n {\n for (int i = 0; i < size; i++)\n {\n strm->WriteByte(buf[i]);\n }\n bmp = gcnew System::Drawing::Bitmap(strm);\n }\n finally\n {\n strm->Close();\n strm = nullptr;\n\n delete[] buf;\n stream->Release();\n image->Release();\n stream = NULL;\n image = NULL;\n }\n }\n\n return bmp;\n }\n\n return nullptr;\n }\n\n IAIMPImageContainer* AimpExtension::ToContainer(System::Drawing::Bitmap ^image)\n {\n IAIMPImageContainer *container;\n if (Utils::CheckResult(ManagedAimpCore::GetAimpCore()->CreateObject(IID_IAIMPImageContainer, (void**)&container)) == AimpActionResult::Ok)\n {\n System::IO::Stream ^stream = nullptr;\n try\n {\n stream = gcnew System::IO::MemoryStream();\n image->Save(stream, System::Drawing::Imaging::ImageFormat::Jpeg);\n stream->Seek(0, System::IO::SeekOrigin::Begin);\n if (Utils::CheckResult(container->SetDataSize((DWORD)stream->Length)) != AimpActionResult::Ok)\n {\n return NULL;\n }\n\n byte *b = container->GetData();\n for (int i = 0; i < stream->Length - 1; i++)\n {\n b[i] = stream->ReadByte();\n }\n\n return container;\n }\n finally\n {\n if (stream != nullptr)\n {\n stream->Close();\n }\n }\n }\n\n return NULL;\n }\n\n String^ AimpExtension::GetString(IAIMPString* value)\n {\n return gcnew String(value->GetData());\n }\n\n AimpActionResult PropertyListExtension::SetObject(IAIMPPropertyList* propertyList, int propertyId, IUnknown *value)\n {\n return Utils::CheckResult(propertyList->SetValueAsObject(propertyId, value));\n }\n\n AimpActionResult PropertyListExtension::SetString(IAIMPPropertyList* propertyList, int propertyId, String ^value)\n {\n \/\/ No need to process empty value\n if (String::IsNullOrWhiteSpace(value))\n {\n return AimpActionResult::InvalidArguments;\n }\n\n IAIMPString *str = NULL;\n try\n {\n str = AimpExtension::GetAimpString(value);\n return SetObject(propertyList, propertyId, str);\n }\n finally\n {\n str->Release();\n str = NULL;\n }\n\n return AimpActionResult::Unexpected;\n }\n\n AimpActionResult PropertyListExtension::SetInt32(IAIMPPropertyList* propertyList, int propertyId, int value)\n {\n return Utils::CheckResult(propertyList->SetValueAsInt32(propertyId, value));\n }\n\n AimpActionResult PropertyListExtension::SetInt64(IAIMPPropertyList* propertyList, int propertyId, Int64 value)\n {\n return Utils::CheckResult(propertyList->SetValueAsInt64(propertyId, value));\n }\n\n AimpActionResult PropertyListExtension::SetFloat(IAIMPPropertyList* propertyList, int propertyId, double value)\n {\n return Utils::CheckResult(propertyList->SetValueAsFloat(propertyId, value));\n }\n\n AimpActionResult PropertyListExtension::SetBool(IAIMPPropertyList* propertyList, int propertyId, bool value)\n {\n return SetInt32(propertyList, propertyId, value ? 1 : 0);\n }\n\n AimpActionResult PropertyListExtension::GetString(IAIMPPropertyList* propertyList, int propertyId, String^% value)\n {\n IAIMPString* str = NULL;\n String ^val = String::Empty;\n\n try\n {\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsObject(propertyId, IID_IAIMPString, (void**)&str));\n if (result != AimpActionResult::Ok)\n {\n value = String::Empty;\n return result;\n }\n\n if (str != NULL)\n {\n result = GetString(str, val);\n value = val;\n return result;\n }\n }\n catch (System::Exception ^ex)\n {\n return AimpActionResult::Fail;\n }\n finally\n {\n if (str != NULL)\n {\n str->Release();\n str = NULL;\n }\n }\n\n return AimpActionResult::Unexpected;\n }\n\n AimpActionResult PropertyListExtension::GetString(IAIMPString* aimpString, String^% value)\n {\n value = gcnew String(aimpString->GetData());\n return AimpActionResult::Ok;\n }\n\n AimpActionResult PropertyListExtension::GetObject(IAIMPPropertyList* propertyList, int propertyId, REFIID objectId, void** value)\n {\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsObject(propertyId, objectId, value));\n return result;\n }\n\n AimpActionResult PropertyListExtension::GetInt32(IAIMPPropertyList* propertyList, int propertyId, int %value)\n {\n int val = 0;\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsInt32(propertyId, &val));\n value = val;\n return result;\n }\n\n AimpActionResult PropertyListExtension::GetInt64(IAIMPPropertyList* propertyList, int propertyId, Int64 %value)\n {\n Int64 val = 0;\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsInt64(propertyId, &val));\n value = val;\n return result;\n }\n\n AimpActionResult PropertyListExtension::GetFloat(IAIMPPropertyList* propertyList, int propertyId, double %value)\n {\n double val = 0;\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsFloat(propertyId, &val));\n value = val;\n return result;\n }\n\n AimpActionResult PropertyListExtension::GetBool(IAIMPPropertyList* propertyList, int propertyId, bool %value)\n {\n int *val = 0;\n AimpActionResult result = GetInt32(propertyList, propertyId, *val);\n value = val > 0;\n return result;\n }\n\n String^ PropertyListExtension::GetString(IAIMPPropertyList *propertyList, int propertyId)\n {\n String^ val = String::Empty;\n if (GetString(propertyList, propertyId, *&val) == AimpActionResult::Ok)\n {\n return val;\n }\n\n return val;\n }\n\n int PropertyListExtension::GetInt32(IAIMPPropertyList *propertyList, int propertyId)\n {\n int val = 0;\n if (GetInt32(propertyList, propertyId, val) == AimpActionResult::Ok)\n {\n return val;\n }\n\n return 0;\n }\n\n Int64 PropertyListExtension::GetInt64(IAIMPPropertyList *propertyList, int propertyId)\n {\n Int64 val;\n if (GetInt64(propertyList, propertyId, val) == AimpActionResult::Ok)\n {\n return val;\n }\n\n return 0;\n }\n\n double PropertyListExtension::GetFloat(IAIMPPropertyList *propertyList, int propertyId)\n {\n double val;\n if (GetFloat(propertyList, propertyId, val) == AimpActionResult::Ok)\n {\n return val;\n }\n\n return 0;\n }\n\n bool PropertyListExtension::GetBool(IAIMPPropertyList *propertyList, int propertyId)\n {\n bool val;\n if (GetBool(propertyList, propertyId, val) == AimpActionResult::Ok)\n {\n return val;\n }\n\n return false;\n }\n\n AimpActionResult PropertyListExtension::GetVariant(IAIMPPropertyList2 *propertyList, int propertyId, Object^% value)\n {\n VARIANT *val = NULL;\n AimpActionResult result = Utils::CheckResult(propertyList->GetValueAsVariant(propertyId, val));\n value = AimpExtension::FromVaiant(val);\n \/\/value = AimpExtension::ToManaged(val);\n \/\/value = val->cVal;\n \/\/value = AIMP::SDK::Variant();\n return result;\n }\n\n AimpActionResult PropertyListExtension::SetVariant(IAIMPPropertyList2 *propertyList, int propertyId, Object^% val)\n {\n return AimpActionResult::NotImplemented;\n }\n\n VARIANT AimpExtension::ToVariant(System::Object^ objectValue)\n {\n VARIANT varTag;\n VariantInit(&varTag);\n IntPtr h = IntPtr(&varTag);\n System::Runtime::InteropServices::Marshal::GetNativeVariantForObject(objectValue, h);\n return varTag;\n }\n\n System::Object^ AimpExtension::FromVaiant(VARIANT* variant)\n {\n void *p = variant;\n return System::Runtime::InteropServices::Marshal::GetObjectForNativeVariant(IntPtr(p));\n }\n }\n}\n<|endoftext|>"} {"text":"\/**\n * @file ncl.cpp\n *\n * Template for future plugins.\n *\n * @date Apr 10, 2013\n * @author peramaki\n *\/\n\n#include \"ncl.h\"\n#include \"plugin_factory.h\"\n#include \"logger_factory.h\"\n#include \n#include \n\n#define HIMAN_AUXILIARY_INCLUDE\n\n#include \"fetcher.h\"\n#include \"writer.h\"\n#include \"neons.h\"\n#include \"pcuda.h\"\n\n#undef HIMAN_AUXILIARY_INCLUDE\n\n#ifdef DEBUG\n#include \"timer_factory.h\"\n#endif\n\nusing namespace std;\nusing namespace himan::plugin;\n\n#include \"cuda_extern.h\"\n\nconst string itsName(\"ncl\");\n\nncl::ncl() : itsUseCuda(false)\n{\n\titsLogger = unique_ptr (logger_factory::Instance()->GetLog(itsName));\n\n}\n\nvoid ncl::Process(std::shared_ptr conf)\n{\n\n\tshared_ptr c = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"pcuda\"));\n\n\tif (c->HaveCuda())\n\t{\n\t\tstring msg = \"I possess the powers of CUDA\";\n\n\t\tif (!conf->UseCuda())\n\t\t{\n\t\t\tmsg += \", but I won't use them\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmsg += \", and I'm not afraid to use them\";\n\t\t\titsUseCuda = true;\n\t\t}\n\n\t\titsLogger->Info(msg);\n\n\t\titsCudaDeviceCount = c->DeviceCount();\n\t\t\n\t}\n\n\t\/\/ Get number of threads to use\n\n\tunsigned short threadCount = ThreadCount(conf->ThreadCount());\n\n\tif (conf->StatisticsEnabled())\n\t{\n\t\tconf->Statistics()->UsedThreadCount(threadCount);\n\t\tconf->Statistics()->UsedGPUCount(itsCudaDeviceCount);\n\t}\n\n\tboost::thread_group g;\n\n\tshared_ptr targetInfo = conf->Info();\n\n\t\/*\n\t * Set target parameter to potential temperature\n\t * - name PARM_NAME\n\t * - univ_id UNIV_ID\n\t * - grib2 descriptor X'Y'Z\n\t *\n\t * We need to specify grib and querydata parameter information\n\t * since we don't know which one will be the output format.\n\t *\n\t *\/\n\n\tvector theParams;\n\t\n\t\/\/ GRIB 2\n\t\n\tparam theRequestedParam;\n\ttheRequestedParam.GribDiscipline(0);\n\ttheRequestedParam.GribCategory(3);\n\ttheRequestedParam.GribParameter(6);\n\n\n\tif (conf->Exists(\"temp\") && conf->GetValue(\"temp\") == \"-20\" )\n\t{\n \ttheRequestedParam.Name(\"HM20C-M\");\n \ttheRequestedParam.UnivId(28);\n \ttargetTemperature = -20;\n }\n\n if (conf->Exists(\"temp\") && conf->GetValue(\"temp\") == \"0\" )\n\t{\n \ttheRequestedParam.Name(\"H0C-M\");\n \ttheRequestedParam.UnivId(270);\n \ttargetTemperature = 0;\n \t\n }\n\n\t\/*\n\t * GRIB 1 parameters go here\n\t *\n\t *\/\n \tif (conf->OutputFileType() == kGRIB1)\n\t{\n\t\tshared_ptr n = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"neons\"));\n\n\t\tlong parm_id = n->NeonsDB().GetGridParameterId(targetInfo->Producer().TableVersion(), theRequestedParam.Name());\n\t\ttheRequestedParam.GribIndicatorOfParameter(parm_id);\n\t\ttheRequestedParam.GribTableVersion(targetInfo->Producer().TableVersion());\n\n\t}\n\n\t\/\/ ----\n\n\ttheParams.push_back(theRequestedParam);\n\n\ttargetInfo->Params(theParams);\n\n\t\/*\n\t * Create data structures.\n\t *\/\n\n\ttargetInfo->Create();\n\n\n\t\/*\n\t * Initialize parent class functions for dimension handling\n\t *\/\n\n\tDimension(conf->LeadingDimension());\n\tFeederInfo(shared_ptr (new info(*targetInfo)));\n\tFeederInfo()->Param(theRequestedParam);\n\n\t\/*\n\t * Each thread will have a copy of the target info.\n\t *\/\n\n\tvector > targetInfos;\n\n\ttargetInfos.resize(threadCount);\n\n\tfor (size_t i = 0; i < threadCount; i++)\n\t{\n\n\t\titsLogger->Info(\"Thread \" + boost::lexical_cast (i + 1) + \" starting\");\n\n\t\ttargetInfos[i] = shared_ptr (new info(*targetInfo));\n\n\t\tboost::thread* t = new boost::thread(&ncl::Run,\n\t\t\t\t\t\t\t\tthis,\n\t\t\t\t\t\t\t\ttargetInfos[i],\n\t\t\t\t\t\t\t\tconf,\n\t\t\t\t\t\t\t\ti + 1);\n\n\t\tg.add_thread(t);\n\n\t}\n\n\tg.join_all();\n\n\tif (conf->FileWriteOption() == kSingleFile)\n\t{\n\n\t\tshared_ptr theWriter = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"writer\"));\n\n\t\tstring theOutputFile = conf->ConfigurationFile();\n\n\t\ttheWriter->ToFile(targetInfo, conf, theOutputFile);\n\n\t}\n}\n\nvoid ncl::Run(shared_ptr myTargetInfo,\n\t\t\t\tshared_ptr conf,\n\t\t\t\tunsigned short threadIndex)\n{\n\n\twhile (AdjustLeadingDimension(myTargetInfo))\n\t{\n\t\tCalculate(myTargetInfo, conf, threadIndex);\n\t}\n}\n\n\/*\n * Calculate()\n *\n * This function does the actual calculation.\n *\/\n\nvoid ncl::Calculate(shared_ptr myTargetInfo, shared_ptr conf, unsigned short threadIndex)\n{\n\n\tshared_ptr theFetcher = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"fetcher\"));\n\n\tparam HParam(\"HL-M\");\n\tparam TParam(\"T-K\");\n\n\tint levelNumber = 65;\n\n\tlevel HLevel(himan::kHybrid, levelNumber, \"HYBRID\");\n\n\tunique_ptr myThreadedLogger = std::unique_ptr (logger_factory::Instance()->GetLog(itsName + \"Thread #\" + boost::lexical_cast (threadIndex)));\n\n\tResetNonLeadingDimension(myTargetInfo);\n\n\tmyTargetInfo->FirstParam();\n\n\twhile (AdjustNonLeadingDimension(myTargetInfo))\n\t{\n\t\tmyThreadedLogger->Debug(\"Calculating time \" + myTargetInfo->Time().ValidDateTime()->String(\"%Y%m%d%H\") +\n\t\t\t\t\t\t\t\t\" level \" + boost::lexical_cast (myTargetInfo->Level().Value()));\n\n\t\tshared_ptr HInfo;\n\t\tshared_ptr TInfo;\n\t\tshared_ptr prevHInfo;\n\t\tshared_ptr prevTInfo;\n\n\t\ttry\n\t\t{\n\n\t\t\tHInfo = theFetcher->Fetch(conf,\n\t\t\t\t\t\t\t\t myTargetInfo->Time(),\n\t\t\t\t\t\t\t\t HLevel,\n\t\t\t\t\t\t\t\t HParam);\n\t\t\t\n\t\t\tTInfo = theFetcher->Fetch(conf,\n\t\t\t\t\t\t\t\t myTargetInfo->Time(),\n\t\t\t\t\t\t\t\t HLevel,\n\t\t\t\t\t\t\t\t TParam);\n\t\t\t\n\t\t}\n\t\tcatch (HPExceptionType e)\n\t\t{\n\t\t\tswitch (e)\n\t\t\t{\n\t\t\t\tcase kFileDataNotFound:\n\t\t\t\t\titsLogger->Warning(\"Skipping step \" + boost::lexical_cast (myTargetInfo->Time().Step()) + \", level \" + boost::lexical_cast (myTargetInfo->Level().Value()));\n\t\t\t\t\tmyTargetInfo->Data()->Fill(kFloatMissing);\n\n\t\t\t\t\tif (conf->StatisticsEnabled())\n\t\t\t\t\t{\n\t\t\t\t\t\tconf->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size());\n\t\t\t\t\t\tconf->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcontinue;\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tthrow runtime_error(ClassName() + \": Unable to proceed\");\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tunique_ptr processTimer = unique_ptr (timer_factory::Instance()->GetTimer());\n\n\t\tif (conf->StatisticsEnabled())\n\t\t{\n\t\t\tprocessTimer->Start();\n\t\t}\n\t\t\n\t\tint missingCount = 0;\n\t\tint count = 0;\n\n\t\t\/*\n\t\t * Converting original grid-data to newbase grid\n\t\t *\n\t\t *\/\n\n\t\tbool firstLevel = true;\n\n\t\tmyTargetInfo->Data()->Fill(0);\n\n\t\t\t\n\t\t\n\t\t\n\t\tHInfo->ResetLocation();\n\t\tTInfo->ResetLocation();\n\n\t\tlevel curLevel = HLevel;\n\t\tlevel prevLevel;\n\t\t\n\t\twhile (--levelNumber > 0)\n\t\t{\n\t\t\tshared_ptr targetGrid(myTargetInfo->Grid()->ToNewbaseGrid());\n\n\n\t\t\ttargetGrid->Reset();\t\t\n\t\t\tmyTargetInfo->ResetLocation();\t\n\t\t\t\n\t\t\t \/\/minneköhän tää pitäis pistää\n\t\t\t\/\/itsLogger->Debug(\"kierros woop \" + boost::lexical_cast (count) );\n\n\t\t\tshared_ptr HGrid(HInfo->Grid()->ToNewbaseGrid());\n\t\t\tshared_ptr TGrid(TInfo->Grid()->ToNewbaseGrid());\n\t\t\tshared_ptr prevHGrid;\n\t\t\tshared_ptr prevTGrid;\n\n\t\t\tif (!firstLevel)\n\t\t\t{\n\t\t\t\tprevHGrid = shared_ptr(prevHInfo->Grid()->ToNewbaseGrid());\n\t\t\t\tprevTGrid = shared_ptr(prevTInfo->Grid()->ToNewbaseGrid());\n\t\t\t}\n\n\n\t\t\tbool equalGrids = (*myTargetInfo->Grid() == *HInfo->Grid() && *myTargetInfo->Grid() == *TInfo->Grid() && ( firstLevel || ( *myTargetInfo->Grid() == *prevHInfo->Grid() && *myTargetInfo->Grid() == *prevTInfo->Grid() ) ) );\n\n\t\t\twhile ( myTargetInfo->NextLocation() && targetGrid->Next() && HGrid->Next() && TGrid->Next() && ( firstLevel || (prevHGrid->Next() && prevTGrid->Next() ) ) )\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t\tstring deviceType;\n\n\t\t\t\tdeviceType = \"CPU\";\n\n\t\t\t\tdouble height = kFloatMissing;\n\t\t\t\tdouble temp = kFloatMissing;\n\t\t\t\tdouble prevHeight = kFloatMissing;\n\t\t\t\tdouble prevTemp = kFloatMissing;\n\n\t\t\t\tdouble targetHeight = myTargetInfo->Value();\n\n\t\t\t\tassert(targetGrid->Size() == myTargetInfo->Data()->Size());\n\n\t\t\t\tInterpolateToPoint(targetGrid, HGrid, equalGrids, height);\n\t\t\t\tInterpolateToPoint(targetGrid, TGrid, equalGrids, temp);\n\n\t\t\t\tif (!firstLevel)\n\t\t\t\t{\n\t\t\t\t\tInterpolateToPoint(targetGrid, prevHGrid, equalGrids, prevHeight);\n\t\t\t\t\tInterpolateToPoint(targetGrid, prevTGrid, equalGrids, prevTemp);\n\t\t\t\t}\n\n\t\t\t\tif (height == kFloatMissing || temp == kFloatMissing || (!firstLevel && ( prevHeight == kFloatMissing || prevTemp == kFloatMissing)))\n\t\t\t\t{\n\t\t\t\t\tmissingCount++;\n\n\t\t\t\t\tmyTargetInfo->Value(kFloatMissing);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\ttemp -= 273.15;\n\t\t\t\tprevTemp -= 273.15;\n\n\t\t\t\tif (targetHeight == 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/itsLogger->Debug(\"level: \" + boost::lexical_cast (height));\n\t\t\t\t\t\n\t\t\t\t\tif (temp < targetTemperature)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!firstLevel)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble p_rel = (targetTemperature - temp) \/ (prevTemp - temp);\n\t\t\t\t\t\t\ttargetHeight = height + (prevHeight - height) * p_rel;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttargetHeight = -99999;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/Inversiotilanteessa pelastetaan vielä pisteitä uudelleen laskentaan\n\t\t\t\telse if (targetHeight != 0 && temp > targetTemperature)\n\t\t\t\t{\n\t\t\t\t\ttargetHeight = 0;\n\t\t\t\t}\n\n\t\t\n\n\t\t\t\tif (!myTargetInfo->Value(targetHeight))\n\t\t\t\t{\n\t\t\t\t\tthrow runtime_error(ClassName() + \": Failed to set value to matrix\");\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tprevLevel = curLevel;\n\t\t\tcurLevel = level(himan::kHybrid, levelNumber, \"HYBRID\");\n\t\t\t\n\t\t\tHInfo = FetchPrevious(conf, myTargetInfo->Time(), curLevel, HParam);\n\t\t\tTInfo = FetchPrevious(conf, myTargetInfo->Time(), curLevel, TParam);\n\t\t\t\n\t\t\tprevHInfo = FetchPrevious(conf, myTargetInfo->Time(), prevLevel, HParam);\n\t\t\tprevTInfo = FetchPrevious(conf, myTargetInfo->Time(), prevLevel, TParam);\n\n\n\t\t\tfirstLevel = false;\n\t\t} \n\n\t\tif (conf->StatisticsEnabled())\n\t\t{\n\t\t\tprocessTimer->Stop();\n\t\t\tconf->Statistics()->AddToProcessingTime(processTimer->GetTime());\n\n#ifdef DEBUG\n\t\t\titsLogger->Debug(\"Calculation took \" + boost::lexical_cast (processTimer->GetTime()) + \" microseconds on \" + deviceType);\n#endif\n\n\t\t\tconf->Statistics()->AddToMissingCount(missingCount);\n\t\t\tconf->Statistics()->AddToValueCount(count);\n\t\t}\t\n\n\n\t\t\/*\n\t\t * Now we are done for this level\n\t\t *\n\t\t * Clone info-instance to writer since it might change our descriptor places\n\t\t * *\/\n\n\t\tmyThreadedLogger->Info(\"Missing values: \" + boost::lexical_cast (missingCount) + \"\/\" + boost::lexical_cast (count));\n\n\t\tif (conf->FileWriteOption() == kNeons || conf->FileWriteOption() == kMultipleFiles)\n\t\t{\n\t\t\tshared_ptr theWriter = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"writer\"));\n\n\t\t\ttheWriter->ToFile(shared_ptr (new info(*myTargetInfo)), conf);\n\t\t}\n\t}\n}\nshared_ptr ncl::FetchPrevious(shared_ptr conf, const forecast_time& wantedTime, const level& wantedLevel, const param& wantedParam)\n{\n\tshared_ptr f = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"fetcher\"));\n\n\ttry\n\t{\n\t\treturn f->Fetch(conf,\n\t\t\t\t\t\twantedTime,\n\t\t\t\t\t\twantedLevel,\n\t\t\t\t\t\twantedParam);\n \t}\n\tcatch (HPExceptionType e)\n\t{\n\t\tthrow e;\n\t}\n\n}logic fix\/**\n * @file ncl.cpp\n *\n * Template for future plugins.\n *\n * @date Apr 10, 2013\n * @author peramaki\n *\/\n\n#include \"ncl.h\"\n#include \"plugin_factory.h\"\n#include \"logger_factory.h\"\n#include \n#include \n\n#define HIMAN_AUXILIARY_INCLUDE\n\n#include \"fetcher.h\"\n#include \"writer.h\"\n#include \"neons.h\"\n#include \"pcuda.h\"\n\n#undef HIMAN_AUXILIARY_INCLUDE\n\n#ifdef DEBUG\n#include \"timer_factory.h\"\n#endif\n\nusing namespace std;\nusing namespace himan::plugin;\n\n#include \"cuda_extern.h\"\n\nconst string itsName(\"ncl\");\n\nncl::ncl() : itsUseCuda(false)\n{\n\titsLogger = unique_ptr (logger_factory::Instance()->GetLog(itsName));\n\n}\n\nvoid ncl::Process(std::shared_ptr conf)\n{\n\n\tshared_ptr c = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"pcuda\"));\n\n\tif (c->HaveCuda())\n\t{\n\t\tstring msg = \"I possess the powers of CUDA\";\n\n\t\tif (!conf->UseCuda())\n\t\t{\n\t\t\tmsg += \", but I won't use them\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmsg += \", and I'm not afraid to use them\";\n\t\t\titsUseCuda = true;\n\t\t}\n\n\t\titsLogger->Info(msg);\n\n\t\titsCudaDeviceCount = c->DeviceCount();\n\t\t\n\t}\n\n\t\/\/ Get number of threads to use\n\n\tunsigned short threadCount = ThreadCount(conf->ThreadCount());\n\n\tif (conf->StatisticsEnabled())\n\t{\n\t\tconf->Statistics()->UsedThreadCount(threadCount);\n\t\tconf->Statistics()->UsedGPUCount(itsCudaDeviceCount);\n\t}\n\n\tboost::thread_group g;\n\n\tshared_ptr targetInfo = conf->Info();\n\n\t\/*\n\t * Set target parameter to potential temperature\n\t * - name PARM_NAME\n\t * - univ_id UNIV_ID\n\t * - grib2 descriptor X'Y'Z\n\t *\n\t * We need to specify grib and querydata parameter information\n\t * since we don't know which one will be the output format.\n\t *\n\t *\/\n\n\tvector theParams;\n\t\n\t\/\/ GRIB 2\n\t\n\tparam theRequestedParam;\n\ttheRequestedParam.GribDiscipline(0);\n\ttheRequestedParam.GribCategory(3);\n\ttheRequestedParam.GribParameter(6);\n\n\n\tif (conf->Exists(\"temp\") && conf->GetValue(\"temp\") == \"-20\" )\n\t{\n \ttheRequestedParam.Name(\"HM20C-M\");\n \ttheRequestedParam.UnivId(28);\n \ttargetTemperature = -20;\n }\n\n if (conf->Exists(\"temp\") && conf->GetValue(\"temp\") == \"0\" )\n\t{\n \ttheRequestedParam.Name(\"H0C-M\");\n \ttheRequestedParam.UnivId(270);\n \ttargetTemperature = 0;\n \t\n }\n\n\t\/*\n\t * GRIB 1 parameters go here\n\t *\n\t *\/\n \tif (conf->OutputFileType() == kGRIB1)\n\t{\n\t\tshared_ptr n = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"neons\"));\n\n\t\tlong parm_id = n->NeonsDB().GetGridParameterId(targetInfo->Producer().TableVersion(), theRequestedParam.Name());\n\t\ttheRequestedParam.GribIndicatorOfParameter(parm_id);\n\t\ttheRequestedParam.GribTableVersion(targetInfo->Producer().TableVersion());\n\n\t}\n\n\t\/\/ ----\n\n\ttheParams.push_back(theRequestedParam);\n\n\ttargetInfo->Params(theParams);\n\n\t\/*\n\t * Create data structures.\n\t *\/\n\n\ttargetInfo->Create();\n\n\n\t\/*\n\t * Initialize parent class functions for dimension handling\n\t *\/\n\n\tDimension(conf->LeadingDimension());\n\tFeederInfo(shared_ptr (new info(*targetInfo)));\n\tFeederInfo()->Param(theRequestedParam);\n\n\t\/*\n\t * Each thread will have a copy of the target info.\n\t *\/\n\n\tvector > targetInfos;\n\n\ttargetInfos.resize(threadCount);\n\n\tfor (size_t i = 0; i < threadCount; i++)\n\t{\n\n\t\titsLogger->Info(\"Thread \" + boost::lexical_cast (i + 1) + \" starting\");\n\n\t\ttargetInfos[i] = shared_ptr (new info(*targetInfo));\n\n\t\tboost::thread* t = new boost::thread(&ncl::Run,\n\t\t\t\t\t\t\t\tthis,\n\t\t\t\t\t\t\t\ttargetInfos[i],\n\t\t\t\t\t\t\t\tconf,\n\t\t\t\t\t\t\t\ti + 1);\n\n\t\tg.add_thread(t);\n\n\t}\n\n\tg.join_all();\n\n\tif (conf->FileWriteOption() == kSingleFile)\n\t{\n\n\t\tshared_ptr theWriter = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"writer\"));\n\n\t\tstring theOutputFile = conf->ConfigurationFile();\n\n\t\ttheWriter->ToFile(targetInfo, conf, theOutputFile);\n\n\t}\n}\n\nvoid ncl::Run(shared_ptr myTargetInfo,\n\t\t\t\tshared_ptr conf,\n\t\t\t\tunsigned short threadIndex)\n{\n\n\twhile (AdjustLeadingDimension(myTargetInfo))\n\t{\n\t\tCalculate(myTargetInfo, conf, threadIndex);\n\t}\n}\n\n\/*\n * Calculate()\n *\n * This function does the actual calculation.\n *\/\n\nvoid ncl::Calculate(shared_ptr myTargetInfo, shared_ptr conf, unsigned short threadIndex)\n{\n\n\tshared_ptr theFetcher = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"fetcher\"));\n\n\tparam HParam(\"HL-M\");\n\tparam TParam(\"T-K\");\n\n\tint levelNumber = 65;\n\n\tlevel HLevel(himan::kHybrid, levelNumber, \"HYBRID\");\n\n\tunique_ptr myThreadedLogger = std::unique_ptr (logger_factory::Instance()->GetLog(itsName + \"Thread #\" + boost::lexical_cast (threadIndex)));\n\n\tResetNonLeadingDimension(myTargetInfo);\n\n\tmyTargetInfo->FirstParam();\n\n\twhile (AdjustNonLeadingDimension(myTargetInfo))\n\t{\n\t\tmyThreadedLogger->Debug(\"Calculating time \" + myTargetInfo->Time().ValidDateTime()->String(\"%Y%m%d%H\") +\n\t\t\t\t\t\t\t\t\" level \" + boost::lexical_cast (myTargetInfo->Level().Value()));\n\n\t\tshared_ptr HInfo;\n\t\tshared_ptr TInfo;\n\t\tshared_ptr prevHInfo;\n\t\tshared_ptr prevTInfo;\n\n\t\ttry\n\t\t{\n\n\t\t\tHInfo = theFetcher->Fetch(conf,\n\t\t\t\t\t\t\t\t myTargetInfo->Time(),\n\t\t\t\t\t\t\t\t HLevel,\n\t\t\t\t\t\t\t\t HParam);\n\t\t\t\n\t\t\tTInfo = theFetcher->Fetch(conf,\n\t\t\t\t\t\t\t\t myTargetInfo->Time(),\n\t\t\t\t\t\t\t\t HLevel,\n\t\t\t\t\t\t\t\t TParam);\n\t\t\t\n\t\t}\n\t\tcatch (HPExceptionType e)\n\t\t{\n\t\t\tswitch (e)\n\t\t\t{\n\t\t\t\tcase kFileDataNotFound:\n\t\t\t\t\titsLogger->Warning(\"Skipping step \" + boost::lexical_cast (myTargetInfo->Time().Step()) + \", level \" + boost::lexical_cast (myTargetInfo->Level().Value()));\n\t\t\t\t\tmyTargetInfo->Data()->Fill(kFloatMissing);\n\n\t\t\t\t\tif (conf->StatisticsEnabled())\n\t\t\t\t\t{\n\t\t\t\t\t\tconf->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size());\n\t\t\t\t\t\tconf->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcontinue;\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tthrow runtime_error(ClassName() + \": Unable to proceed\");\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tunique_ptr processTimer = unique_ptr (timer_factory::Instance()->GetTimer());\n\n\t\tif (conf->StatisticsEnabled())\n\t\t{\n\t\t\tprocessTimer->Start();\n\t\t}\n\t\t\n\t\tint missingCount = 0;\n\t\tint count = 0;\n\n\t\t\/*\n\t\t * Converting original grid-data to newbase grid\n\t\t *\n\t\t *\/\n\n\t\tbool firstLevel = true;\n\n\t\tmyTargetInfo->Data()->Fill(0);\n\n\t\t\t\n\t\t\n\t\t\n\t\tHInfo->ResetLocation();\n\t\tTInfo->ResetLocation();\n\n\t\tlevel curLevel = HLevel;\n\t\tlevel prevLevel;\n\t\t\n\t\tshared_ptr targetGrid(myTargetInfo->Grid()->ToNewbaseGrid());\n\n\t\twhile (--levelNumber > 0)\n\t\t{\n\n\t\t\ttargetGrid->Reset();\t\t\n\t\t\tmyTargetInfo->FirstLocation();\t\n\t\t\t\n\t\t\t \/\/minneköhän tää pitäis pistää\n\t\t\t\/\/itsLogger->Debug(\"kierros woop \" + boost::lexical_cast (count) );\n\n\t\t\tshared_ptr HGrid(HInfo->Grid()->ToNewbaseGrid());\n\t\t\tshared_ptr TGrid(TInfo->Grid()->ToNewbaseGrid());\n\t\t\tshared_ptr prevHGrid;\n\t\t\tshared_ptr prevTGrid;\n\n\t\t\tif (!firstLevel)\n\t\t\t{\n\t\t\t\tprevHGrid = shared_ptr(prevHInfo->Grid()->ToNewbaseGrid());\n\t\t\t\tprevTGrid = shared_ptr(prevTInfo->Grid()->ToNewbaseGrid());\n\t\t\t}\n\n\n\t\t\tbool equalGrids = (\t*myTargetInfo->Grid() == *HInfo->Grid() \n\t\t\t\t\t\t\t\t&& *myTargetInfo->Grid() == *TInfo->Grid() \n\t\t\t\t\t\t\t\t&& ( firstLevel || ( *myTargetInfo->Grid() == *prevHInfo->Grid() && *myTargetInfo->Grid() == *prevTInfo->Grid() ) ) );\n\n\t\t\twhile ( myTargetInfo->NextLocation() && targetGrid->Next() && HGrid->Next() && TGrid->Next() && ( firstLevel || (prevHGrid->Next() && prevTGrid->Next() ) ) )\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t\tstring deviceType;\n\n\t\t\t\tdeviceType = \"CPU\";\n\n\t\t\t\tdouble height = kFloatMissing;\n\t\t\t\tdouble temp = kFloatMissing;\n\t\t\t\tdouble prevHeight = kFloatMissing;\n\t\t\t\tdouble prevTemp = kFloatMissing;\n\n\t\t\t\tdouble targetHeight = myTargetInfo->Value();\n\n\t\t\t\tassert(targetGrid->Size() == myTargetInfo->Data()->Size());\n\n\t\t\t\tInterpolateToPoint(targetGrid, HGrid, equalGrids, height);\n\t\t\t\tInterpolateToPoint(targetGrid, TGrid, equalGrids, temp);\n\n\t\t\t\tif (!firstLevel)\n\t\t\t\t{\n\t\t\t\t\tInterpolateToPoint(targetGrid, prevHGrid, equalGrids, prevHeight);\n\t\t\t\t\tInterpolateToPoint(targetGrid, prevTGrid, equalGrids, prevTemp);\n\t\t\t\t}\n\n\t\t\t\tif (height == kFloatMissing || temp == kFloatMissing || (!firstLevel && ( prevHeight == kFloatMissing || prevTemp == kFloatMissing)))\n\t\t\t\t{\n\t\t\t\t\tmissingCount++;\n\n\t\t\t\t\tmyTargetInfo->Value(kFloatMissing);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\ttemp -= 273.15;\n\t\t\t\tprevTemp -= 273.15;\n\n\t\t\t\tif (targetHeight == 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/itsLogger->Debug(\"level: \" + boost::lexical_cast (height));\n\t\t\t\t\t\n\t\t\t\t\tif (temp < targetTemperature)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!firstLevel)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble p_rel = (targetTemperature - temp) \/ (prevTemp - temp);\n\t\t\t\t\t\t\ttargetHeight = height + (prevHeight - height) * p_rel;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttargetHeight = kFloatMissing;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/Inversiotilanteessa pelastetaan vielä pisteitä uudelleen laskentaan\n\t\t\t\telse if (targetHeight != 0 && temp > targetTemperature)\n\t\t\t\t{\n\t\t\t\t\ttargetHeight = 0;\n\t\t\t\t}\n\n\t\t\n\t\t\t\t\/\/itsLogger->Debug(\"level: \" + boost::lexical_cast (targetHeight));\n\t\t\t\tif (!myTargetInfo->Value(targetHeight))\n\t\t\t\t{\n\t\t\t\t\tthrow runtime_error(ClassName() + \": Failed to set value to matrix\");\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tprevLevel = curLevel;\n\t\t\tcurLevel = level(himan::kHybrid, levelNumber, \"HYBRID\");\n\t\t\t\n\t\t\tHInfo = FetchPrevious(conf, myTargetInfo->Time(), curLevel, HParam);\n\t\t\tTInfo = FetchPrevious(conf, myTargetInfo->Time(), curLevel, TParam);\n\t\t\t\n\t\t\tprevHInfo = FetchPrevious(conf, myTargetInfo->Time(), prevLevel, HParam);\n\t\t\tprevTInfo = FetchPrevious(conf, myTargetInfo->Time(), prevLevel, TParam);\n\n\n\t\t\tfirstLevel = false;\n\t\t} \n\n\t\tif (conf->StatisticsEnabled())\n\t\t{\n\t\t\tprocessTimer->Stop();\n\t\t\tconf->Statistics()->AddToProcessingTime(processTimer->GetTime());\n\n#ifdef DEBUG\n\t\t\titsLogger->Debug(\"Calculation took \" + boost::lexical_cast (processTimer->GetTime()) + \" microseconds on \" + deviceType);\n#endif\n\n\t\t\tconf->Statistics()->AddToMissingCount(missingCount);\n\t\t\tconf->Statistics()->AddToValueCount(count);\n\t\t}\t\n\n\n\t\t\/*\n\t\t * Now we are done for this level\n\t\t *\n\t\t * Clone info-instance to writer since it might change our descriptor places\n\t\t * *\/\n\n\t\tmyThreadedLogger->Info(\"Missing values: \" + boost::lexical_cast (missingCount) + \"\/\" + boost::lexical_cast (count));\n\n\t\tif (conf->FileWriteOption() == kNeons || conf->FileWriteOption() == kMultipleFiles)\n\t\t{\n\t\t\tshared_ptr theWriter = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"writer\"));\n\n\t\t\ttheWriter->ToFile(shared_ptr (new info(*myTargetInfo)), conf);\n\t\t}\n\t}\n}\nshared_ptr ncl::FetchPrevious(shared_ptr conf, const forecast_time& wantedTime, const level& wantedLevel, const param& wantedParam)\n{\n\tshared_ptr f = dynamic_pointer_cast (plugin_factory::Instance()->Plugin(\"fetcher\"));\n\n\ttry\n\t{\n\t\treturn f->Fetch(conf,\n\t\t\t\t\t\twantedTime,\n\t\t\t\t\t\twantedLevel,\n\t\t\t\t\t\twantedParam);\n \t}\n\tcatch (HPExceptionType e)\n\t{\n\t\tthrow e;\n\t}\n\n}<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2746\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1611372 by chui@ocl-promo-incrementor on 2018\/09\/27 02:56:48\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2747\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2752\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1614408 by chui@ocl-promo-incrementor on 2018\/10\/04 02:56:51\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2753\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1992\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1224277 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/01\/02 03:00:11\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1993\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2481\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1449639 by johtaylo@johtaylo-jtincrementor-increment on 2017\/08\/21 03:00:05\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2482\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2694\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1580522 by chui@ocl-promo-incrementor on 2018\/07\/14 03:00:23\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2695\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2998\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1999173 by chui@ocl-promo-incrementor on 2019\/09\/17 03:00:37\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2999\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2084\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1254404 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/04\/05 03:00:10\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2085\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1906\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1197854 by johtaylo@johtaylo-JTBUILDER03-increment on 2015\/10\/08 03:00:13\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1907\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2186\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1299375 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/08\/05 03:00:10\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2187\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2313\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1357043 by johtaylo@johtaylo-jtincrementor-increment on 2016\/12\/24 03:00:05\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2314\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2992\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1995962 by chui@ocl-promo-incrementor on 2019\/09\/10 03:00:33\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2993\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace {\n\tstatic uint8_t zero_padding[255];\n}\n\nSSH::TransportPipe::TransportPipe(void)\n: PipeProducer(\"\/ssh\/transport\/pipe\"),\n state_(GetIdentificationString),\n block_size_(8),\n mac_length_(0),\n algorithm_negotiation_(NULL),\n receive_callback_(NULL),\n receive_action_(NULL)\n{\n\tBuffer identification_string(\"SSH-2.0-WANProxy \" + (std::string)log_ + \"\\r\\n\");\n\tproduce(&identification_string);\n}\n\nSSH::TransportPipe::~TransportPipe()\n{\n\tASSERT(receive_callback_ == NULL);\n\tASSERT(receive_action_ == NULL);\n}\n\nAction *\nSSH::TransportPipe::receive(EventCallback *cb)\n{\n\tASSERT(receive_callback_ == NULL);\n\tASSERT(receive_action_ == NULL);\n\n\t\/*\n\t * XXX\n\t * This pattern is implemented about three different\n\t * ways in the WANProxy codebase, and they are all kind\n\t * of awful. Need a better way to handle code that\n\t * needs executed either on the request of the caller\n\t * or when data comes in that satisfies a deferred\n\t * callback to a caller.\n\t *\/\n\treceive_callback_ = cb;\n\treceive_do();\n\n\tif (receive_callback_ != NULL)\n\t\treturn (cancellation(this, &SSH::TransportPipe::receive_cancel));\n\n\tASSERT(receive_action_ != NULL);\n\tAction *a = receive_action_;\n\treceive_action_ = NULL;\n\treturn (a);\n}\n\n\/*\n * Because this is primarily for WAN optimization we always use minimal\n * padding and zero padding. Quick and dirty. Perhaps revisit later,\n * although it makes send() asynchronous unless we add a blocking\n * RNG interface.\n *\/\nvoid\nSSH::TransportPipe::send(Buffer *payload)\n{\n\tBuffer packet;\n\tuint8_t padding_len;\n\tuint32_t packet_len;\n\n\tASSERT(state_ == GetPacket);\n\n\tpacket_len = sizeof padding_len + payload->length();\n\tpadding_len = 4 + (block_size_ - ((sizeof packet_len + packet_len + 4) % block_size_));\n\tpacket_len += padding_len;\n\n\tpacket_len = BigEndian::encode(packet_len);\n\tpacket.append(&packet_len);\n\tpacket.append(padding_len);\n\tpacket.append(payload);\n\tpacket.append(zero_padding, padding_len);\n\n\tif (mac_length_ != 0)\n\t\tNOTREACHED();\n\n\tpayload->clear();\n\n\tproduce(&packet);\n}\n\nvoid\nSSH::TransportPipe::consume(Buffer *in)\n{\n\t\/* XXX XXX XXX *\/\n\tif (in->empty()) {\n\t\tif (!input_buffer_.empty())\n\t\t\tDEBUG(log_) << \"Received EOS with data outstanding.\";\n\t\tproduce_eos();\n\t\treturn;\n\t}\n\n\tin->moveout(&input_buffer_);\n\n\tif (state_ == GetIdentificationString) {\n\t\tHTTPProtocol::ParseStatus status;\n\n\t\twhile (!input_buffer_.empty()) {\n\t\t\tBuffer line;\n\t\t\tstatus = HTTPProtocol::ExtractLine(&line, &input_buffer_);\n\t\t\tswitch (status) {\n\t\t\tcase HTTPProtocol::ParseSuccess:\n\t\t\t\tbreak;\n\t\t\tcase HTTPProtocol::ParseFailure:\n\t\t\t\tERROR(log_) << \"Invalid line while waiting for identification string.\";\n\t\t\t\tproduce_error();\n\t\t\t\treturn;\n\t\t\tcase HTTPProtocol::ParseIncomplete:\n\t\t\t\t\/* Wait for more. *\/\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!line.prefix(\"SSH-\"))\n\t\t\t\tcontinue; \/* Next line. *\/\n\n\t\t\tif (!line.prefix(\"SSH-2.0\")) {\n\t\t\t\tERROR(log_) << \"Unsupported version.\";\n\t\t\t\tproduce_error();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tstate_ = GetPacket;\n\t\t\t\/*\n\t\t\t * XXX\n\t\t\t * Should have a callback here?\n\t\t\t *\/\n\t\t\tif (algorithm_negotiation_ != NULL) {\n\t\t\t\tBuffer packet;\n\t\t\t\tif (algorithm_negotiation_->output(&packet))\n\t\t\t\t\tsend(&packet);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (state_ == GetPacket && receive_callback_ != NULL)\n\t\treceive_do();\n}\n\nvoid\nSSH::TransportPipe::receive_cancel(void)\n{\n\tif (receive_action_ != NULL) {\n\t\treceive_action_->cancel();\n\t\treceive_action_ = NULL;\n\t}\n\n\tif (receive_callback_ != NULL) {\n\t\tdelete receive_callback_;\n\t\treceive_callback_ = NULL;\n\t}\n}\n\nvoid\nSSH::TransportPipe::receive_do(void)\n{\n\tASSERT(receive_action_ == NULL);\n\tASSERT(receive_callback_ != NULL);\n\n\tif (state_ != GetPacket)\n\t\treturn;\n\n\twhile (!input_buffer_.empty()) {\n\t\tBuffer packet;\n\t\tBuffer mac;\n\t\tuint32_t packet_len;\n\t\tuint8_t padding_len;\n\t\tuint8_t msg;\n\n\t\tif (input_buffer_.length() <= sizeof packet_len) {\n\t\t\tDEBUG(log_) << \"Waiting for packet length.\";\n\t\t\treturn;\n\t\t}\n\n\t\tinput_buffer_.extract(&packet_len);\n\t\tpacket_len = BigEndian::decode(packet_len);\n\n\t\tif (packet_len == 0) {\n\t\t\tERROR(log_) << \"Need to handle 0-length packet.\";\n\t\t\tproduce_error();\n\t\t\treturn;\n\t\t}\n\n\t\tif (input_buffer_.length() < sizeof packet_len + packet_len + mac_length_) {\n\t\t\tDEBUG(log_) << \"Need \" << sizeof packet_len + packet_len + mac_length_ << \"bytes; have \" << input_buffer_.length() << \".\";\n\t\t\treturn;\n\t\t}\n\n\t\tinput_buffer_.moveout(&packet, sizeof packet_len, packet_len);\n\t\tif (mac_length_ != 0)\n\t\t\tinput_buffer_.moveout(&mac, 0, mac_length_);\n\n\t\tpadding_len = packet.peek();\n\t\tpacket.skip(sizeof padding_len);\n\t\tif (padding_len != 0) {\n\t\t\tif (packet.length() < padding_len) {\n\t\t\t\tERROR(log_) << \"Padding too large for packet.\";\n\t\t\t\tproduce_error();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpacket.trim(padding_len);\n\t\t}\n\n\t\tif (packet.empty()) {\n\t\t\tERROR(log_) << \"Need to handle empty packet.\";\n\t\t\tproduce_error();\n\t\t\treturn;\n\t\t}\n\n\t\t\/*\n\t\t * Pass by range to registered handlers for each range.\n\t\t * Unhandled messages go to the receive_callback_, and\n\t\t * the caller can register key exchange mechanisms,\n\t\t * and handle (or discard) whatever they don't handle.\n\t\t *\n\t\t * NB: The caller could do all this, but it's assumed\n\t\t * that they usually have better things to do. If\n\t\t * they register no handlers, they can certainly do\n\t\t * so by hand.\n\t\t *\/\n\t\tmsg = packet.peek();\n\t\tif (msg >= SSH::Message::TransportRangeBegin &&\n\t\t msg <= SSH::Message::TransportRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for transport message.\";\n\t\t} else if (msg >= SSH::Message::AlgorithmNegotiationRangeBegin &&\n\t\t\t msg <= SSH::Message::AlgorithmNegotiationRangeEnd) {\n\t\t\tif (algorithm_negotiation_ != NULL) {\n\t\t\t\tif (algorithm_negotiation_->input(&packet))\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tDEBUG(log_) << \"Using default handler for algorithm negotiation message.\";\n\t\t} else if (msg >= SSH::Message::KeyExchangeMethodRangeBegin &&\n\t\t\t msg <= SSH::Message::KeyExchangeMethodRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for key exchange method message.\";\n\t\t} else if (msg >= SSH::Message::UserAuthenticationGenericRangeBegin &&\n\t\t\t msg <= SSH::Message::UserAuthenticationGenericRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for generic user authentication message.\";\n\t\t} else if (msg >= SSH::Message::UserAuthenticationMethodRangeBegin &&\n\t\t\t msg <= SSH::Message::UserAuthenticationMethodRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for user authentication method message.\";\n\t\t} else if (msg >= SSH::Message::ConnectionProtocolGlobalRangeBegin &&\n\t\t\t msg <= SSH::Message::ConnectionProtocolGlobalRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for generic connection protocol message.\";\n\t\t} else if (msg >= SSH::Message::ConnectionChannelRangeBegin &&\n\t\t\t msg <= SSH::Message::ConnectionChannelRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for connection channel message.\";\n\t\t} else if (msg >= SSH::Message::ClientProtocolReservedRangeBegin &&\n\t\t\t msg <= SSH::Message::ClientProtocolReservedRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for client protocol message.\";\n\t\t} else if (msg >= SSH::Message::LocalExtensionRangeBegin) {\n\t\t\t\/* Because msg is a uint8_t, it will always be <= SSH::Message::LocalExtensionRangeEnd. *\/\n\t\t\tDEBUG(log_) << \"Using default handler for local extension message.\";\n\t\t} else {\n\t\t\tASSERT(msg == 0);\n\t\t\tERROR(log_) << \"Message outside of protocol range received. Passing to default handler, but not expecting much.\";\n\t\t}\n\n\t\treceive_callback_->param(Event(Event::Done, packet));\n\t\treceive_action_ = receive_callback_->schedule();\n\t\treceive_callback_ = NULL;\n\n\t\treturn;\n\t}\n}\nUse new moveout(Buffer *).#include \n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace {\n\tstatic uint8_t zero_padding[255];\n}\n\nSSH::TransportPipe::TransportPipe(void)\n: PipeProducer(\"\/ssh\/transport\/pipe\"),\n state_(GetIdentificationString),\n block_size_(8),\n mac_length_(0),\n algorithm_negotiation_(NULL),\n receive_callback_(NULL),\n receive_action_(NULL)\n{\n\tBuffer identification_string(\"SSH-2.0-WANProxy \" + (std::string)log_ + \"\\r\\n\");\n\tproduce(&identification_string);\n}\n\nSSH::TransportPipe::~TransportPipe()\n{\n\tASSERT(receive_callback_ == NULL);\n\tASSERT(receive_action_ == NULL);\n}\n\nAction *\nSSH::TransportPipe::receive(EventCallback *cb)\n{\n\tASSERT(receive_callback_ == NULL);\n\tASSERT(receive_action_ == NULL);\n\n\t\/*\n\t * XXX\n\t * This pattern is implemented about three different\n\t * ways in the WANProxy codebase, and they are all kind\n\t * of awful. Need a better way to handle code that\n\t * needs executed either on the request of the caller\n\t * or when data comes in that satisfies a deferred\n\t * callback to a caller.\n\t *\/\n\treceive_callback_ = cb;\n\treceive_do();\n\n\tif (receive_callback_ != NULL)\n\t\treturn (cancellation(this, &SSH::TransportPipe::receive_cancel));\n\n\tASSERT(receive_action_ != NULL);\n\tAction *a = receive_action_;\n\treceive_action_ = NULL;\n\treturn (a);\n}\n\n\/*\n * Because this is primarily for WAN optimization we always use minimal\n * padding and zero padding. Quick and dirty. Perhaps revisit later,\n * although it makes send() asynchronous unless we add a blocking\n * RNG interface.\n *\/\nvoid\nSSH::TransportPipe::send(Buffer *payload)\n{\n\tBuffer packet;\n\tuint8_t padding_len;\n\tuint32_t packet_len;\n\n\tASSERT(state_ == GetPacket);\n\n\tpacket_len = sizeof padding_len + payload->length();\n\tpadding_len = 4 + (block_size_ - ((sizeof packet_len + packet_len + 4) % block_size_));\n\tpacket_len += padding_len;\n\n\tpacket_len = BigEndian::encode(packet_len);\n\tpacket.append(&packet_len);\n\tpacket.append(padding_len);\n\tpayload->moveout(&packet);\n\tpacket.append(zero_padding, padding_len);\n\n\tif (mac_length_ != 0)\n\t\tNOTREACHED();\n\n\tproduce(&packet);\n}\n\nvoid\nSSH::TransportPipe::consume(Buffer *in)\n{\n\t\/* XXX XXX XXX *\/\n\tif (in->empty()) {\n\t\tif (!input_buffer_.empty())\n\t\t\tDEBUG(log_) << \"Received EOS with data outstanding.\";\n\t\tproduce_eos();\n\t\treturn;\n\t}\n\n\tin->moveout(&input_buffer_);\n\n\tif (state_ == GetIdentificationString) {\n\t\tHTTPProtocol::ParseStatus status;\n\n\t\twhile (!input_buffer_.empty()) {\n\t\t\tBuffer line;\n\t\t\tstatus = HTTPProtocol::ExtractLine(&line, &input_buffer_);\n\t\t\tswitch (status) {\n\t\t\tcase HTTPProtocol::ParseSuccess:\n\t\t\t\tbreak;\n\t\t\tcase HTTPProtocol::ParseFailure:\n\t\t\t\tERROR(log_) << \"Invalid line while waiting for identification string.\";\n\t\t\t\tproduce_error();\n\t\t\t\treturn;\n\t\t\tcase HTTPProtocol::ParseIncomplete:\n\t\t\t\t\/* Wait for more. *\/\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!line.prefix(\"SSH-\"))\n\t\t\t\tcontinue; \/* Next line. *\/\n\n\t\t\tif (!line.prefix(\"SSH-2.0\")) {\n\t\t\t\tERROR(log_) << \"Unsupported version.\";\n\t\t\t\tproduce_error();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tstate_ = GetPacket;\n\t\t\t\/*\n\t\t\t * XXX\n\t\t\t * Should have a callback here?\n\t\t\t *\/\n\t\t\tif (algorithm_negotiation_ != NULL) {\n\t\t\t\tBuffer packet;\n\t\t\t\tif (algorithm_negotiation_->output(&packet))\n\t\t\t\t\tsend(&packet);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (state_ == GetPacket && receive_callback_ != NULL)\n\t\treceive_do();\n}\n\nvoid\nSSH::TransportPipe::receive_cancel(void)\n{\n\tif (receive_action_ != NULL) {\n\t\treceive_action_->cancel();\n\t\treceive_action_ = NULL;\n\t}\n\n\tif (receive_callback_ != NULL) {\n\t\tdelete receive_callback_;\n\t\treceive_callback_ = NULL;\n\t}\n}\n\nvoid\nSSH::TransportPipe::receive_do(void)\n{\n\tASSERT(receive_action_ == NULL);\n\tASSERT(receive_callback_ != NULL);\n\n\tif (state_ != GetPacket)\n\t\treturn;\n\n\twhile (!input_buffer_.empty()) {\n\t\tBuffer packet;\n\t\tBuffer mac;\n\t\tuint32_t packet_len;\n\t\tuint8_t padding_len;\n\t\tuint8_t msg;\n\n\t\tif (input_buffer_.length() <= sizeof packet_len) {\n\t\t\tDEBUG(log_) << \"Waiting for packet length.\";\n\t\t\treturn;\n\t\t}\n\n\t\tinput_buffer_.extract(&packet_len);\n\t\tpacket_len = BigEndian::decode(packet_len);\n\n\t\tif (packet_len == 0) {\n\t\t\tERROR(log_) << \"Need to handle 0-length packet.\";\n\t\t\tproduce_error();\n\t\t\treturn;\n\t\t}\n\n\t\tif (input_buffer_.length() < sizeof packet_len + packet_len + mac_length_) {\n\t\t\tDEBUG(log_) << \"Need \" << sizeof packet_len + packet_len + mac_length_ << \"bytes; have \" << input_buffer_.length() << \".\";\n\t\t\treturn;\n\t\t}\n\n\t\tinput_buffer_.moveout(&packet, sizeof packet_len, packet_len);\n\t\tif (mac_length_ != 0)\n\t\t\tinput_buffer_.moveout(&mac, 0, mac_length_);\n\n\t\tpadding_len = packet.peek();\n\t\tpacket.skip(sizeof padding_len);\n\t\tif (padding_len != 0) {\n\t\t\tif (packet.length() < padding_len) {\n\t\t\t\tERROR(log_) << \"Padding too large for packet.\";\n\t\t\t\tproduce_error();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpacket.trim(padding_len);\n\t\t}\n\n\t\tif (packet.empty()) {\n\t\t\tERROR(log_) << \"Need to handle empty packet.\";\n\t\t\tproduce_error();\n\t\t\treturn;\n\t\t}\n\n\t\t\/*\n\t\t * Pass by range to registered handlers for each range.\n\t\t * Unhandled messages go to the receive_callback_, and\n\t\t * the caller can register key exchange mechanisms,\n\t\t * and handle (or discard) whatever they don't handle.\n\t\t *\n\t\t * NB: The caller could do all this, but it's assumed\n\t\t * that they usually have better things to do. If\n\t\t * they register no handlers, they can certainly do\n\t\t * so by hand.\n\t\t *\/\n\t\tmsg = packet.peek();\n\t\tif (msg >= SSH::Message::TransportRangeBegin &&\n\t\t msg <= SSH::Message::TransportRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for transport message.\";\n\t\t} else if (msg >= SSH::Message::AlgorithmNegotiationRangeBegin &&\n\t\t\t msg <= SSH::Message::AlgorithmNegotiationRangeEnd) {\n\t\t\tif (algorithm_negotiation_ != NULL) {\n\t\t\t\tif (algorithm_negotiation_->input(&packet))\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tDEBUG(log_) << \"Using default handler for algorithm negotiation message.\";\n\t\t} else if (msg >= SSH::Message::KeyExchangeMethodRangeBegin &&\n\t\t\t msg <= SSH::Message::KeyExchangeMethodRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for key exchange method message.\";\n\t\t} else if (msg >= SSH::Message::UserAuthenticationGenericRangeBegin &&\n\t\t\t msg <= SSH::Message::UserAuthenticationGenericRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for generic user authentication message.\";\n\t\t} else if (msg >= SSH::Message::UserAuthenticationMethodRangeBegin &&\n\t\t\t msg <= SSH::Message::UserAuthenticationMethodRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for user authentication method message.\";\n\t\t} else if (msg >= SSH::Message::ConnectionProtocolGlobalRangeBegin &&\n\t\t\t msg <= SSH::Message::ConnectionProtocolGlobalRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for generic connection protocol message.\";\n\t\t} else if (msg >= SSH::Message::ConnectionChannelRangeBegin &&\n\t\t\t msg <= SSH::Message::ConnectionChannelRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for connection channel message.\";\n\t\t} else if (msg >= SSH::Message::ClientProtocolReservedRangeBegin &&\n\t\t\t msg <= SSH::Message::ClientProtocolReservedRangeEnd) {\n\t\t\tDEBUG(log_) << \"Using default handler for client protocol message.\";\n\t\t} else if (msg >= SSH::Message::LocalExtensionRangeBegin) {\n\t\t\t\/* Because msg is a uint8_t, it will always be <= SSH::Message::LocalExtensionRangeEnd. *\/\n\t\t\tDEBUG(log_) << \"Using default handler for local extension message.\";\n\t\t} else {\n\t\t\tASSERT(msg == 0);\n\t\t\tERROR(log_) << \"Message outside of protocol range received. Passing to default handler, but not expecting much.\";\n\t\t}\n\n\t\treceive_callback_->param(Event(Event::Done, packet));\n\t\treceive_action_ = receive_callback_->schedule();\n\t\treceive_callback_ = NULL;\n\n\t\treturn;\n\t}\n}\n<|endoftext|>"} {"text":"#define MYSQLPP_NOT_HEADER\n#include \"platform.h\"\n\n#include \"sql_query.h\"\n\n#include \"exceptions.h\"\n\nusing namespace std;\n\nnamespace mysqlpp {\n\nSQLQuery::SQLQuery(const SQLQuery& q) :\nstringstream(const_cast(q).str()),\t\/\/ yes, the cast is evil -- got a better idea?\nSuccess(q.Success),\nerrmsg(q.errmsg),\ndef(q.def)\n{\n}\n\nvoid SQLQuery::reset()\n{\n\tseekg(0);\n\tseekp(0);\n\tclear();\n\tstringstream::str(\"\");\n\n\tparsed.clear();\n\tdef.clear();\n}\n\nchar* SQLQuery::preview_char()\n{\n\t*this << std::ends;\n\tsize_t length = rdbuf()->str().size();\n\tchar *s = new char[length + 1];\n\tget(s, length, '\\0');\n\tseekg(0, std::ios::beg);\n\tseekp(-1, std::ios::cur);\n\treturn s;\n}\n\nstatic SQLString* pprepare(char option, SQLString& S,\n\t\tbool replace = true)\n{\n\tif (S.processed) {\n\t\treturn &S;\n\t}\n\n\tif (option == 'r' || (option == 'q' && S.is_string)) {\n\t\tchar *s = new char[S.size() * 2 + 1];\n\t\tmysql_escape_string(s, S.c_str(), (unsigned long) S.size());\n\t\tSQLString *ss = new SQLString(\"'\");\n\t\t*ss += s;\n\t\t*ss += \"'\";\n\t\tdelete[] s;\n\n\t\tif (replace) {\n\t\t\tS = *ss;\n\t\t\tS.processed = true;\n\t\t\treturn &S;\n\t\t}\n\t\telse {\n\t\t\treturn ss;\n\t\t}\n\t}\n\telse if (option == 'R' || (option == 'Q' && S.is_string)) {\n\t\tSQLString *ss = new SQLString(\"'\" + S + \"'\");\n\n\t\tif (replace) {\n\t\t\tS = *ss;\n\t\t\tS.processed = true;\n\t\t\treturn &S;\n\t\t}\n\t\telse {\n\t\t\treturn ss;\n\t\t}\n\t}\n\telse {\n\t\tif (replace) {\n\t\t\tS.processed = true;\n\t\t}\n\t\treturn &S;\n\t}\n}\n\nvoid SQLQuery::proc(SQLQueryParms& p)\n{\n\tseekg(0, std::ios::beg);\n\tseekp(0, std::ios::beg);\n\tchar num;\n\tSQLString *ss;\n\tSQLQueryParms *c;\n\n\tfor (std::vector::iterator i = parsed.begin();\n\t\t\ti != parsed.end(); ++i) {\n\t\t*this << i->before;\n\t\tnum = i->num;\n\t\tif (num != -1) {\n\t\t\tif (num < static_cast < int >(p.size()))\n\t\t\t\tc = &p;\n\t\t\telse if (num < static_cast < int >(def.size()))\n\t\t\t\tc = &def;\n\t\t\telse {\n\t\t\t\t*this << \" ERROR\";\n\t\t\t\tthrow\n\t\t\t\t\tSQLQueryNEParms\n\t\t\t\t\t(\"Not enough parameters to fill the template.\");\n\t\t\t}\n\t\t\tss = pprepare(i->option, (*c)[num], c->bound());\n\t\t\t*this << *ss;\n\t\t\tif (ss != &(*c)[num]) {\n\t\t\t\tdelete ss;\n\t\t\t}\n\t\t}\n\t}\n}\n\nstd::string SQLQuery::str(SQLQueryParms& p)\n{\n\tif (!parsed.empty()) {\n\t\tproc(p);\n\t}\n\n\t*this << std::ends;\n\n\treturn stringstream::str();\n}\n\nstd::string SQLQuery::str(SQLQueryParms& p, query_reset r)\n{\n\tstd::string tmp = str(p);\n\tif (r == RESET_QUERY) {\n\t\treset();\n\t}\n\treturn tmp;\n}\n\nSQLQueryParms SQLQueryParms::operator +(const SQLQueryParms & other) const\n{\n\tif (other.size() <= size()) {\n\t\treturn *this;\n\t}\n\tSQLQueryParms New = *this;\n\tsize_t i;\n\tfor (i = size(); i < other.size(); i++) {\n\t\tNew.push_back(other[i]);\n\t}\n\n\treturn New;\n}\n\nvoid SQLQuery::parse()\n{\n\tstd::string str = \"\";\n\tchar num[4];\n\tlong int n;\n\tchar option;\n\tstd::string name;\n\tchar *s, *s0;\n\ts0 = s = preview_char();\n\twhile (*s) {\n\t\tif (*s == '%') {\n\t\t\ts++;\n\t\t\tif (*s == '%') {\n\t\t\t\tstr += *s++;\n\t\t\t}\n\t\t\telse if (*s >= '0' && *s <= '9') {\n\t\t\t\tnum[0] = *s;\n\t\t\t\ts++;\n\t\t\t\tif (*s >= '0' && *s <= '9') {\n\t\t\t\t\tnum[1] = *s;\n\t\t\t\t\tnum[2] = 0;\n\t\t\t\t\ts++;\n\t\t\t\t\tif (*s >= '0' && *s <= '9') {\n\t\t\t\t\t\tnum[2] = *s;\n\t\t\t\t\t\tnum[3] = 0;\n\t\t\t\t\t\ts++;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tnum[2] = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnum[1] = 0;\n\t\t\t\t}\n\n\t\t\t\tn = strtol(num, NULL, 10);\n\t\t\t\toption = ' ';\n\n\t\t\t\tif (*s == 'q' || *s == 'Q' || *s == 'r' || *s == 'R') {\n\t\t\t\t\toption = *s++;\n\t\t\t\t}\n\n\t\t\t\tif (*s == ':') {\n\t\t\t\t\ts++;\n\t\t\t\t\tfor ( \/* *\/ ; (*s >= 'A' && *s <= 'Z') ||\n\t\t\t\t\t\t *s == '_' || (*s >= 'a' && *s <= 'z'); s++) {\n\t\t\t\t\t\tname += *s;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (*s == ':') {\n\t\t\t\t\t\ts++;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (n >= static_cast <\n\t\t\t\t\t\tlong int >(parsed_names.size())) {\n\t\t\t\t\t\tparsed_names.insert(parsed_names.end(),\n\t\t\t\t\t\t\t\t\t\t\tstatic_cast < vector <\n\t\t\t\t\t\t\t\t\t\t\tstring >::size_type >\n\t\t\t\t\t\t\t\t\t\t\t(n + 1) -\n\t\t\t\t\t\t\t\t\t\t\tparsed_names.size(),\n\t\t\t\t\t\t\t\t\t\t\tstring());\n\t\t\t\t\t}\n\t\t\t\t\tparsed_names[n] = name;\n\t\t\t\t\tparsed_nums[name] = n;\n\t\t\t\t}\n\n\t\t\t\tparsed.\n\t\t\t\t\tpush_back(SQLParseElement(str, option, char (n)));\n\t\t\t\tstr = \"\";\n\t\t\t\tname = \"\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstr += '%';\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tstr += *s++;\n\t\t}\n\t}\n\n\tparsed.push_back(SQLParseElement(str, ' ', -1));\n\tdelete[] s0;\n}\n\n} \/\/ end namespace mysqlpp\nChanged some C-style casts to static_casts to avoid GCC 4 warnings.#define MYSQLPP_NOT_HEADER\n#include \"platform.h\"\n\n#include \"sql_query.h\"\n\n#include \"exceptions.h\"\n\nusing namespace std;\n\nnamespace mysqlpp {\n\nSQLQuery::SQLQuery(const SQLQuery& q) :\nstringstream(const_cast(q).str()),\t\/\/ yes, the cast is evil -- got a better idea?\nSuccess(q.Success),\nerrmsg(q.errmsg),\ndef(q.def)\n{\n}\n\nvoid SQLQuery::reset()\n{\n\tseekg(0);\n\tseekp(0);\n\tclear();\n\tstringstream::str(\"\");\n\n\tparsed.clear();\n\tdef.clear();\n}\n\nchar* SQLQuery::preview_char()\n{\n\t*this << std::ends;\n\tsize_t length = rdbuf()->str().size();\n\tchar *s = new char[length + 1];\n\tget(s, length, '\\0');\n\tseekg(0, std::ios::beg);\n\tseekp(-1, std::ios::cur);\n\treturn s;\n}\n\nstatic SQLString* pprepare(char option, SQLString& S,\n\t\tbool replace = true)\n{\n\tif (S.processed) {\n\t\treturn &S;\n\t}\n\n\tif (option == 'r' || (option == 'q' && S.is_string)) {\n\t\tchar *s = new char[S.size() * 2 + 1];\n\t\tmysql_escape_string(s, S.c_str(), static_cast (S.size()));\n\t\tSQLString *ss = new SQLString(\"'\");\n\t\t*ss += s;\n\t\t*ss += \"'\";\n\t\tdelete[] s;\n\n\t\tif (replace) {\n\t\t\tS = *ss;\n\t\t\tS.processed = true;\n\t\t\treturn &S;\n\t\t}\n\t\telse {\n\t\t\treturn ss;\n\t\t}\n\t}\n\telse if (option == 'R' || (option == 'Q' && S.is_string)) {\n\t\tSQLString *ss = new SQLString(\"'\" + S + \"'\");\n\n\t\tif (replace) {\n\t\t\tS = *ss;\n\t\t\tS.processed = true;\n\t\t\treturn &S;\n\t\t}\n\t\telse {\n\t\t\treturn ss;\n\t\t}\n\t}\n\telse {\n\t\tif (replace) {\n\t\t\tS.processed = true;\n\t\t}\n\t\treturn &S;\n\t}\n}\n\nvoid SQLQuery::proc(SQLQueryParms& p)\n{\n\tseekg(0, std::ios::beg);\n\tseekp(0, std::ios::beg);\n\tchar num;\n\tSQLString *ss;\n\tSQLQueryParms *c;\n\n\tfor (std::vector::iterator i = parsed.begin();\n\t\t\ti != parsed.end(); ++i) {\n\t\t*this << i->before;\n\t\tnum = i->num;\n\t\tif (num != -1) {\n\t\t\tif (num < static_cast < int >(p.size()))\n\t\t\t\tc = &p;\n\t\t\telse if (num < static_cast < int >(def.size()))\n\t\t\t\tc = &def;\n\t\t\telse {\n\t\t\t\t*this << \" ERROR\";\n\t\t\t\tthrow\n\t\t\t\t\tSQLQueryNEParms\n\t\t\t\t\t(\"Not enough parameters to fill the template.\");\n\t\t\t}\n\t\t\tss = pprepare(i->option, (*c)[num], c->bound());\n\t\t\t*this << *ss;\n\t\t\tif (ss != &(*c)[num]) {\n\t\t\t\tdelete ss;\n\t\t\t}\n\t\t}\n\t}\n}\n\nstd::string SQLQuery::str(SQLQueryParms& p)\n{\n\tif (!parsed.empty()) {\n\t\tproc(p);\n\t}\n\n\t*this << std::ends;\n\n\treturn stringstream::str();\n}\n\nstd::string SQLQuery::str(SQLQueryParms& p, query_reset r)\n{\n\tstd::string tmp = str(p);\n\tif (r == RESET_QUERY) {\n\t\treset();\n\t}\n\treturn tmp;\n}\n\nSQLQueryParms SQLQueryParms::operator +(const SQLQueryParms & other) const\n{\n\tif (other.size() <= size()) {\n\t\treturn *this;\n\t}\n\tSQLQueryParms New = *this;\n\tsize_t i;\n\tfor (i = size(); i < other.size(); i++) {\n\t\tNew.push_back(other[i]);\n\t}\n\n\treturn New;\n}\n\nvoid SQLQuery::parse()\n{\n\tstd::string str = \"\";\n\tchar num[4];\n\tlong int n;\n\tchar option;\n\tstd::string name;\n\tchar *s, *s0;\n\ts0 = s = preview_char();\n\twhile (*s) {\n\t\tif (*s == '%') {\n\t\t\ts++;\n\t\t\tif (*s == '%') {\n\t\t\t\tstr += *s++;\n\t\t\t}\n\t\t\telse if (*s >= '0' && *s <= '9') {\n\t\t\t\tnum[0] = *s;\n\t\t\t\ts++;\n\t\t\t\tif (*s >= '0' && *s <= '9') {\n\t\t\t\t\tnum[1] = *s;\n\t\t\t\t\tnum[2] = 0;\n\t\t\t\t\ts++;\n\t\t\t\t\tif (*s >= '0' && *s <= '9') {\n\t\t\t\t\t\tnum[2] = *s;\n\t\t\t\t\t\tnum[3] = 0;\n\t\t\t\t\t\ts++;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tnum[2] = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnum[1] = 0;\n\t\t\t\t}\n\n\t\t\t\tn = strtol(num, NULL, 10);\n\t\t\t\toption = ' ';\n\n\t\t\t\tif (*s == 'q' || *s == 'Q' || *s == 'r' || *s == 'R') {\n\t\t\t\t\toption = *s++;\n\t\t\t\t}\n\n\t\t\t\tif (*s == ':') {\n\t\t\t\t\ts++;\n\t\t\t\t\tfor ( \/* *\/ ; (*s >= 'A' && *s <= 'Z') ||\n\t\t\t\t\t\t *s == '_' || (*s >= 'a' && *s <= 'z'); s++) {\n\t\t\t\t\t\tname += *s;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (*s == ':') {\n\t\t\t\t\t\ts++;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (n >= static_cast <\n\t\t\t\t\t\tlong int >(parsed_names.size())) {\n\t\t\t\t\t\tparsed_names.insert(parsed_names.end(),\n\t\t\t\t\t\t\t\t\t\t\tstatic_cast < vector <\n\t\t\t\t\t\t\t\t\t\t\tstring >::size_type >\n\t\t\t\t\t\t\t\t\t\t\t(n + 1) -\n\t\t\t\t\t\t\t\t\t\t\tparsed_names.size(),\n\t\t\t\t\t\t\t\t\t\t\tstring());\n\t\t\t\t\t}\n\t\t\t\t\tparsed_names[n] = name;\n\t\t\t\t\tparsed_nums[name] = n;\n\t\t\t\t}\n\n\t\t\t\tparsed.\n\t\t\t\t\tpush_back(SQLParseElement(str, option, char (n)));\n\t\t\t\tstr = \"\";\n\t\t\t\tname = \"\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstr += '%';\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tstr += *s++;\n\t\t}\n\t}\n\n\tparsed.push_back(SQLParseElement(str, ' ', -1));\n\tdelete[] s0;\n}\n\n} \/\/ end namespace mysqlpp\n<|endoftext|>"} {"text":"\/* $Header$ *\/\n\/\/ Copyright ***********************************************************\n\/\/ \n\/\/ File ecmdMain.C \n\/\/ \n\/\/ IBM Confidential \n\/\/ OCO Source Materials \n\/\/ 9400 Licensed Internal Code \n\/\/ (C) COPYRIGHT IBM CORP. 1996 \n\/\/ \n\/\/ The source code for this program is not published or otherwise \n\/\/ divested of its trade secrets, irrespective of what has been \n\/\/ deposited with the U.S. Copyright Office. \n\/\/ \n\/\/ End Copyright *******************************************************\n\/**\n @file ecmdMain.C\n @brief Main Program entry point for ecmdDllClient Application\n*\/\n\n\n\/\/----------------------------------------------------------------------\n\/\/ Includes\n\/\/----------------------------------------------------------------------\n\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nint main (int argc, char *argv[])\n{\n uint32_t rc = ECMD_SUCCESS;\n\n std::string cmdSave;\n char errorbuf[200];\n for (int i = 0; i < argc; i++) {\n cmdSave += argv[i];\n cmdSave += \" \";\n }\n cmdSave += \"\\n\";\n\n rc = ecmdLoadDll(\"\");\n if (rc) {\n ecmdLoadDllRecovery(cmdSave, rc);\n }\n\n \/\/ By default, quiet error mode is on. This means no errors are printing in the dll wrapper code\n \/\/ For the command line, turn off quiet error mode so those errors will be reported as the plugin call returns\n rc = ecmdSetGlobalVar(ECMD_GLOBALVAR_QUIETERRORMODE, 0);\n if (rc) return rc;\n\n if (rc == ECMD_SUCCESS) {\n \/* Check to see if we are using stdin to pass in multiple commands *\/\n bool shellMode = ecmdParseOption(&argc, &argv, \"-shell\");\n bool stdinMode = ecmdParseOption(&argc, &argv, \"-stdin\");\n if (stdinMode || shellMode) {\n\n \/* Grab any other args that may be there *\/\n rc = ecmdCommandArgs(&argc, &argv);\n if (rc) return rc;\n\n \/* There shouldn't be any more args when doing a -stdin\/-shell *\/\n if (argc > 1) {\n ecmdOutputError(\"ecmd - Invalid args passed to ecmd in -stdin\/-shell mode\\n\");\n return ECMD_INVALID_ARGS;\n }\n\n \/* Let's get things going *\/\n std::vector commands;\n int c_argc;\n char* c_argv[ECMD_ARG_LIMIT + 1]; \/\/\/< A limit of 20 tokens(args) per command\n char* buffer = NULL;\n size_t bufflen = 0;\n size_t commlen;\n bool shellAlive = true;\n\n if (shellMode) {\n ecmdOutput(\"ecmd> \"); fflush(0);\n }\n\n \/* ecmdParseStdInCommands reads from stdin and returns a vector of strings *\/\n \/* each string contains one command (ie 'ecmdquery version') *\/\n \/* When Ctrl-D or EOF is reached this function will fail to break out of loop *\/\n while (shellAlive && (rc = ecmdParseStdinCommands(commands))) {\n\n rc = 0;\n\n \/* Walk through individual commands from ecmdParseStdInCommands *\/\n for (std::vector< std::string >::iterator commandIter = commands.begin(); commandIter != commands.end(); commandIter++) {\n\n c_argc = 0;\n c_argv[0] = NULL;\n\n \/* Check for a comment or empty line, if so delete it *\/\n if ((*commandIter)[0] == '#') {\n continue;\n } else if (commandIter->length() == 0) {\n continue;\n }\n if (shellMode) {\n if ((*commandIter) == \"quit\" || (*commandIter) == \"exit\") {\n ecmdOutput(\"Leaving ecmd shell at users request... \\n\");\n shellAlive = false;\n break;\n }\n }\n\n \/* Create a char buffer to hold the whole command, we will use this to create pointers to each token in the command (like argc,argv) *\/\n commlen = commandIter->length();\n if ( commlen > bufflen) {\n if (buffer != NULL) delete[] buffer;\n buffer = new char[commlen + 20];\n bufflen = commlen + 19;\n }\n\n \/\/ Beam \"error\" of possible NULL 'buffer' value requires mutually\n \/\/ exclusive conditions (need an argument present to enter \n \/\/ \"commands\" FOR loop but commandIter->length = 0 ie. no command). So\n \/\/ tell beam to ignore NULL pointer message for 'buffer' parm via\n \/\/ comment on next line.\n \/\/lint -e(668) Ignore passing null, same as above for lint\n strcpy(buffer, commandIter->c_str()); \/*passing null object*\/\n\n \/* Now start carving this thing up *\/\n bool lookingForStart = true; \/* Are we looking for the start of a word ? *\/\n for (size_t c = 0; c < commlen; c++) {\n if (lookingForStart) {\n if (buffer[c] != ' ' && buffer[c] != '\\t') {\n c_argv[c_argc++] = &buffer[c];\n lookingForStart = false;\n }\n } else {\n \/* Looking for the end *\/\n if (buffer[c] == ' ' || buffer[c] == '\\t') {\n buffer[c] = '\\0';\n lookingForStart = true;\n }\n }\n if (c_argc > ECMD_ARG_LIMIT) {\n sprintf(errorbuf,\"ecmd - Found a command with greater then %d arguments, not supported\\n\",ECMD_ARG_LIMIT);\n ecmdOutputError(errorbuf);\n rc = ECMD_INVALID_ARGS;\n break;\n }\n }\n\n \/\/ ignore a line if it is only space or tabs - \n \/\/ This prevents c_argv[o] being accessed below when still pointing to NULL\n if (c_argc == 0) continue;\n\n \/\/ Before Executing the cmd save it on the Dll side \n ecmdSetCurrentCmdline(c_argc, c_argv);\n\n \/* We now want to call the command interpreter to handle what the user provided us *\/\n if (!rc) rc = ecmdCallInterpreters(c_argc, c_argv);\n\n\n if (rc == ECMD_INT_UNKNOWN_COMMAND) {\n if (strlen(c_argv[0]) < 200)\n sprintf(errorbuf,\"ecmd - Unknown Command specified '%s'\\n\", c_argv[0]);\n else\n sprintf(errorbuf,\"ecmd - Unknown Command specified \\n\");\n ecmdOutputError(errorbuf);\n } else if (rc) {\n std::string parse = ecmdGetErrorMsg(ECMD_GET_ALL_REMAINING_ERRORS, false);\n if (parse.length() > 0) {\n \/* Display the registered message right away BZ#160 *\/\n ecmdOutput(parse.c_str());\n }\n parse = ecmdParseReturnCodeHidden(rc);\n if (strlen(c_argv[0]) + parse.length() < 300)\n sprintf(errorbuf,\"ecmd - '%s' returned with error code 0x%X (%s)\\n\", c_argv[0], rc, parse.c_str());\n else\n sprintf(errorbuf,\"ecmd - Command returned with error code 0x%X (%s)\\n\", rc, parse.c_str());\n ecmdOutputError(errorbuf);\n break;\n }\n\n if (!ecmdGetGlobalVar(ECMD_GLOBALVAR_QUIETMODE)) {\n ecmdOutput((*commandIter + \"\\n\").c_str());\n }\n } \/* tokens loop *\/\n if (rc) break;\n\n \/* Print the prompt again *\/\n if (shellMode && shellAlive) {\n ecmdOutput(\"ecmd> \"); fflush(0);\n }\n }\n if (buffer != NULL) delete[] buffer;\n\n } else {\n \/* Standard command line command *\/\n\n \/\/ Before Executing the cmd save it on the Dll side \n ecmdSetCurrentCmdline(argc-1, argv+1);\n\n \/* We now want to call the command interpreter to handle what the user provided us *\/\n rc = ecmdCallInterpreters(argc - 1, argv + 1);\n\n\n if (rc == ECMD_INT_UNKNOWN_COMMAND) {\n if (argv[1] == NULL)\n sprintf(errorbuf,\"ecmd - Must specify a command to execute. Run 'ecmd -h' for command list.\\n\");\n else if (strlen(argv[1]) < 200)\n sprintf(errorbuf,\"ecmd - Unknown Command specified '%s'\\n\", argv[1]);\n else\n sprintf(errorbuf,\"ecmd - Unknown Command specified \\n\");\n ecmdOutputError(errorbuf);\n } else if (rc) {\n std::string parse = ecmdGetErrorMsg(ECMD_GET_ALL_REMAINING_ERRORS, false);\n if (parse.length() > 0) {\n \/* Display the registered message right away BZ#160 *\/\n ecmdOutput(parse.c_str());\n }\n parse = ecmdParseReturnCodeHidden(rc);\n if (strlen(argv[1]) + parse.length() < 300)\n sprintf(errorbuf,\"ecmd - '%s' returned with error code 0x%X (%s)\\n\", argv[1], rc, parse.c_str());\n else\n sprintf(errorbuf,\"ecmd - Command returned with error code 0x%X (%s)\\n\", rc, parse.c_str());\n ecmdOutputError(errorbuf);\n }\n }\n\n\n \/* Move these outputs into the if !rc to fix BZ#224 - cje *\/\n if (!ecmdGetGlobalVar(ECMD_GLOBALVAR_QUIETMODE)) {\n ecmdOutput(cmdSave.c_str());\n }\n\n\n rc = ecmdUnloadDll();\n if (rc) return rc;\n }\n\n return rc;\n}\n\n\n\n\n\n\/\/ Change Log *********************************************************\n\/\/ \n\/\/ Flag Reason Vers Date Coder Description \n\/\/ ---- -------- ---- -------- -------- ------------------------------ \n\/\/ CENGEL Initial Creation\n\/\/ none STGC7449 04\/18\/05 prahl Clean up Beam messages.\n\/\/\n\/\/ End Change Log *****************************************************\nMoved ecmdSetGlobalVar call into if condition to fix problem where it reset an failing rc from the loaddll\/* $Header$ *\/\n\/\/ Copyright ***********************************************************\n\/\/ \n\/\/ File ecmdMain.C \n\/\/ \n\/\/ IBM Confidential \n\/\/ OCO Source Materials \n\/\/ 9400 Licensed Internal Code \n\/\/ (C) COPYRIGHT IBM CORP. 1996 \n\/\/ \n\/\/ The source code for this program is not published or otherwise \n\/\/ divested of its trade secrets, irrespective of what has been \n\/\/ deposited with the U.S. Copyright Office. \n\/\/ \n\/\/ End Copyright *******************************************************\n\/**\n @file ecmdMain.C\n @brief Main Program entry point for ecmdDllClient Application\n*\/\n\n\n\/\/----------------------------------------------------------------------\n\/\/ Includes\n\/\/----------------------------------------------------------------------\n\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nint main (int argc, char *argv[])\n{\n uint32_t rc = ECMD_SUCCESS;\n\n std::string cmdSave;\n char errorbuf[200];\n for (int i = 0; i < argc; i++) {\n cmdSave += argv[i];\n cmdSave += \" \";\n }\n cmdSave += \"\\n\";\n\n rc = ecmdLoadDll(\"\");\n if (rc) {\n ecmdLoadDllRecovery(cmdSave, rc);\n }\n\n if (rc == ECMD_SUCCESS) {\n\n \/\/ By default, quiet error mode is on. This means no errors are printing in the dll wrapper code\n \/\/ For the command line, turn off quiet error mode so those errors will be reported as the plugin call returns\n rc = ecmdSetGlobalVar(ECMD_GLOBALVAR_QUIETERRORMODE, 0);\n if (rc) return rc;\n\n \/* Check to see if we are using stdin to pass in multiple commands *\/\n bool shellMode = ecmdParseOption(&argc, &argv, \"-shell\");\n bool stdinMode = ecmdParseOption(&argc, &argv, \"-stdin\");\n if (stdinMode || shellMode) {\n\n \/* Grab any other args that may be there *\/\n rc = ecmdCommandArgs(&argc, &argv);\n if (rc) return rc;\n\n \/* There shouldn't be any more args when doing a -stdin\/-shell *\/\n if (argc > 1) {\n ecmdOutputError(\"ecmd - Invalid args passed to ecmd in -stdin\/-shell mode\\n\");\n return ECMD_INVALID_ARGS;\n }\n\n \/* Let's get things going *\/\n std::vector commands;\n int c_argc;\n char* c_argv[ECMD_ARG_LIMIT + 1]; \/\/\/< A limit of 20 tokens(args) per command\n char* buffer = NULL;\n size_t bufflen = 0;\n size_t commlen;\n bool shellAlive = true;\n\n if (shellMode) {\n ecmdOutput(\"ecmd> \"); fflush(0);\n }\n\n \/* ecmdParseStdInCommands reads from stdin and returns a vector of strings *\/\n \/* each string contains one command (ie 'ecmdquery version') *\/\n \/* When Ctrl-D or EOF is reached this function will fail to break out of loop *\/\n while (shellAlive && (rc = ecmdParseStdinCommands(commands))) {\n\n rc = 0;\n\n \/* Walk through individual commands from ecmdParseStdInCommands *\/\n for (std::vector< std::string >::iterator commandIter = commands.begin(); commandIter != commands.end(); commandIter++) {\n\n c_argc = 0;\n c_argv[0] = NULL;\n\n \/* Check for a comment or empty line, if so delete it *\/\n if ((*commandIter)[0] == '#') {\n continue;\n } else if (commandIter->length() == 0) {\n continue;\n }\n if (shellMode) {\n if ((*commandIter) == \"quit\" || (*commandIter) == \"exit\") {\n ecmdOutput(\"Leaving ecmd shell at users request... \\n\");\n shellAlive = false;\n break;\n }\n }\n\n \/* Create a char buffer to hold the whole command, we will use this to create pointers to each token in the command (like argc,argv) *\/\n commlen = commandIter->length();\n if ( commlen > bufflen) {\n if (buffer != NULL) delete[] buffer;\n buffer = new char[commlen + 20];\n bufflen = commlen + 19;\n }\n\n \/\/ Beam \"error\" of possible NULL 'buffer' value requires mutually\n \/\/ exclusive conditions (need an argument present to enter \n \/\/ \"commands\" FOR loop but commandIter->length = 0 ie. no command). So\n \/\/ tell beam to ignore NULL pointer message for 'buffer' parm via\n \/\/ comment on next line.\n \/\/lint -e(668) Ignore passing null, same as above for lint\n strcpy(buffer, commandIter->c_str()); \/*passing null object*\/\n\n \/* Now start carving this thing up *\/\n bool lookingForStart = true; \/* Are we looking for the start of a word ? *\/\n for (size_t c = 0; c < commlen; c++) {\n if (lookingForStart) {\n if (buffer[c] != ' ' && buffer[c] != '\\t') {\n c_argv[c_argc++] = &buffer[c];\n lookingForStart = false;\n }\n } else {\n \/* Looking for the end *\/\n if (buffer[c] == ' ' || buffer[c] == '\\t') {\n buffer[c] = '\\0';\n lookingForStart = true;\n }\n }\n if (c_argc > ECMD_ARG_LIMIT) {\n sprintf(errorbuf,\"ecmd - Found a command with greater then %d arguments, not supported\\n\",ECMD_ARG_LIMIT);\n ecmdOutputError(errorbuf);\n rc = ECMD_INVALID_ARGS;\n break;\n }\n }\n\n \/\/ ignore a line if it is only space or tabs - \n \/\/ This prevents c_argv[o] being accessed below when still pointing to NULL\n if (c_argc == 0) continue;\n\n \/\/ Before Executing the cmd save it on the Dll side \n ecmdSetCurrentCmdline(c_argc, c_argv);\n\n \/* We now want to call the command interpreter to handle what the user provided us *\/\n if (!rc) rc = ecmdCallInterpreters(c_argc, c_argv);\n\n\n if (rc == ECMD_INT_UNKNOWN_COMMAND) {\n if (strlen(c_argv[0]) < 200)\n sprintf(errorbuf,\"ecmd - Unknown Command specified '%s'\\n\", c_argv[0]);\n else\n sprintf(errorbuf,\"ecmd - Unknown Command specified \\n\");\n ecmdOutputError(errorbuf);\n } else if (rc) {\n std::string parse = ecmdGetErrorMsg(ECMD_GET_ALL_REMAINING_ERRORS, false);\n if (parse.length() > 0) {\n \/* Display the registered message right away BZ#160 *\/\n ecmdOutput(parse.c_str());\n }\n parse = ecmdParseReturnCodeHidden(rc);\n if (strlen(c_argv[0]) + parse.length() < 300)\n sprintf(errorbuf,\"ecmd - '%s' returned with error code 0x%X (%s)\\n\", c_argv[0], rc, parse.c_str());\n else\n sprintf(errorbuf,\"ecmd - Command returned with error code 0x%X (%s)\\n\", rc, parse.c_str());\n ecmdOutputError(errorbuf);\n break;\n }\n\n if (!ecmdGetGlobalVar(ECMD_GLOBALVAR_QUIETMODE)) {\n ecmdOutput((*commandIter + \"\\n\").c_str());\n }\n } \/* tokens loop *\/\n if (rc) break;\n\n \/* Print the prompt again *\/\n if (shellMode && shellAlive) {\n ecmdOutput(\"ecmd> \"); fflush(0);\n }\n }\n if (buffer != NULL) delete[] buffer;\n\n } else {\n \/* Standard command line command *\/\n\n \/\/ Before Executing the cmd save it on the Dll side \n ecmdSetCurrentCmdline(argc-1, argv+1);\n\n \/* We now want to call the command interpreter to handle what the user provided us *\/\n rc = ecmdCallInterpreters(argc - 1, argv + 1);\n\n\n if (rc == ECMD_INT_UNKNOWN_COMMAND) {\n if (argv[1] == NULL)\n sprintf(errorbuf,\"ecmd - Must specify a command to execute. Run 'ecmd -h' for command list.\\n\");\n else if (strlen(argv[1]) < 200)\n sprintf(errorbuf,\"ecmd - Unknown Command specified '%s'\\n\", argv[1]);\n else\n sprintf(errorbuf,\"ecmd - Unknown Command specified \\n\");\n ecmdOutputError(errorbuf);\n } else if (rc) {\n std::string parse = ecmdGetErrorMsg(ECMD_GET_ALL_REMAINING_ERRORS, false);\n if (parse.length() > 0) {\n \/* Display the registered message right away BZ#160 *\/\n ecmdOutput(parse.c_str());\n }\n parse = ecmdParseReturnCodeHidden(rc);\n if (strlen(argv[1]) + parse.length() < 300)\n sprintf(errorbuf,\"ecmd - '%s' returned with error code 0x%X (%s)\\n\", argv[1], rc, parse.c_str());\n else\n sprintf(errorbuf,\"ecmd - Command returned with error code 0x%X (%s)\\n\", rc, parse.c_str());\n ecmdOutputError(errorbuf);\n }\n }\n\n\n \/* Move these outputs into the if !rc to fix BZ#224 - cje *\/\n if (!ecmdGetGlobalVar(ECMD_GLOBALVAR_QUIETMODE)) {\n ecmdOutput(cmdSave.c_str());\n }\n\n\n rc = ecmdUnloadDll();\n if (rc) return rc;\n }\n\n return rc;\n}\n\n\n\n\n\n\/\/ Change Log *********************************************************\n\/\/ \n\/\/ Flag Reason Vers Date Coder Description \n\/\/ ---- -------- ---- -------- -------- ------------------------------ \n\/\/ CENGEL Initial Creation\n\/\/ none STGC7449 04\/18\/05 prahl Clean up Beam messages.\n\/\/\n\/\/ End Change Log *****************************************************\n<|endoftext|>"} {"text":"\n\/\/ Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree. An additional intellectual property rights grant can be found\n\/\/ in the file PATENTS. All contributing project authors may\n\/\/ be found in the AUTHORS file in the root of the source tree.\n\n\/\/ Class1.cpp\n#include \n#include \n\n#include \"GlobalObserver.h\"\n#include \"PeerConnectionInterface.h\"\n#include \"Marshalling.h\"\n#include \"Media.h\"\n#include \"DataChannel.h\"\n#include \"webrtc\/common_video\/video_common_winuwp.h\"\n\nusing Platform::Collections::Vector;\n\nnamespace Org {\n\tnamespace WebRtc {\n\t\tnamespace Internal {\n\n#define POST_PC_EVENT(fn, evt) \\\n auto pc = _pc;\\\n Windows::UI::Core::CoreDispatcher^ _windowDispatcher = webrtc::VideoCommonWinUWP::GetCoreDispatcher();\\\n if (_windowDispatcher != nullptr) {\\\n _windowDispatcher->RunAsync(\\\n Windows::UI::Core::CoreDispatcherPriority::Normal, \\\n ref new Windows::UI::Core::DispatchedHandler([pc, evt] {\\\n if (pc != nullptr) {\\\n pc->##fn(evt);\\\n }\\\n }));\\\n } else {\\\n if (pc != nullptr) {\\\n pc->##fn(evt);\\\n }\\\n }\n\n#define POST_PC_ACTION(fn) \\\n auto pc = _pc;\\\n Windows::UI::Core::CoreDispatcher^ _windowDispatcher = webrtc::VideoCommonWinUWP::GetCoreDispatcher();\\\n if (_windowDispatcher != nullptr) {\\\n _windowDispatcher->RunAsync(\\\n Windows::UI::Core::CoreDispatcherPriority::Normal, \\\n ref new Windows::UI::Core::DispatchedHandler([pc] {\\\n if (pc != nullptr) {\\\n pc->##fn();\\\n }\\\n }));\\\n } else {\\\n if (pc != nullptr) {\\\n pc->##fn();\\\n }\\\n }\n\n\t\t\tGlobalObserver::GlobalObserver() {\n\t\t\t\tResetStatsConfig();\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::SetPeerConnection(\n\t\t\t\tOrg::WebRtc::RTCPeerConnection^ pc) {\n\t\t\t\t_pc = pc;\n\t\t\t\tif (_pc == nullptr) {\n\t\t\t\t\t_stats_observer = nullptr;\n\t\t\t\t}\n\t\t\t\tResetStatsConfig();\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::ResetStatsConfig() {\n\t\t\t\t_etwStatsEnabled = false;\n\t\t\t\t_connectionHealthStatsEnabled = false;\n\t\t\t\t_rtcStatsEnabled = false;\n\t\t\t\t_sendRtcStatsToRemoteHostEnabled = false;\n\t\t\t\t_rtcStatsDestinationHost = \"localhost\";\n\t\t\t\t_rtcStatsDestinationPort = 47005;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::EnableETWStats(bool enable) {\n\t\t\t\t_etwStatsEnabled = enable;\n\t\t\t\tif (_stats_observer) {\n\t\t\t\t\t_stats_observer->ToggleETWStats(enable);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool GlobalObserver::AreETWStatsEnabled() {\n\t\t\t\treturn _etwStatsEnabled;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::EnableConnectionHealthStats(bool enable) {\n\t\t\t\t_connectionHealthStatsEnabled = enable;\n\t\t\t\tif (_stats_observer) {\n\t\t\t\t\t_stats_observer->ToggleConnectionHealthStats(enable ? this : NULL);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool GlobalObserver::AreConnectionHealthStatsEnabled() {\n\t\t\t\treturn _connectionHealthStatsEnabled;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::EnableRTCStats(bool enable) {\n\t\t\t\t_rtcStatsEnabled = enable;\n\t\t\t\tif (_stats_observer) {\n\t\t\t\t\t_stats_observer->ToggleRTCStats(enable ? this : NULL);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool GlobalObserver::AreRTCStatsEnabled() {\n\t\t\t\treturn _rtcStatsEnabled;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::EnableSendRtcStatsToRemoteHost(bool enable) {\n\t\t\t\t_sendRtcStatsToRemoteHostEnabled = enable;\n\t\t\t\tif (_stats_observer) {\n\t\t\t\t\tif (enable) {\n\t\t\t\t\t\t_stats_observer->SetStatsNetworkDestination(\n\t\t\t\t\t\t\t_rtcStatsDestinationHost, _rtcStatsDestinationPort);\n\t\t\t\t\t}\n\t\t\t\t\t_stats_observer->ToggleStatsSendToRemoteHost(enable);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool GlobalObserver::IsSendRtcStatsToRemoteHostEnabled() {\n\t\t\t\treturn _sendRtcStatsToRemoteHostEnabled;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::SetRtcStatsDestinationHost(std::string value) {\n\t\t\t\t_rtcStatsDestinationHost = value;\n\t\t\t}\n\n\t\t\tstd::string GlobalObserver::GetRtcStatsDestinationHost() {\n\t\t\t\treturn _rtcStatsDestinationHost;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::SetRtcStatsDestinationPort(int port) {\n\t\t\t\t_rtcStatsDestinationPort = port;\n\t\t\t}\n\t\t\tint GlobalObserver::GetRtcStatsDestinationPort() {\n\t\t\t\treturn _rtcStatsDestinationPort;\n\t\t\t}\n\n\n\t\t\t\/\/ Triggered when the SignalingState changed.\n\t\t\tvoid GlobalObserver::OnSignalingChange(\n\t\t\t\twebrtc::PeerConnectionInterface::SignalingState new_state) {\n\t\t\t\tPOST_PC_ACTION(OnSignalingStateChange);\n\t\t\t}\n\n\t\t\t\/\/ Triggered when SignalingState or IceState have changed.\n\t\t\t\/\/ TODO(bemasc): Remove once callers transition to OnSignalingChange.\n\t\t\tvoid GlobalObserver::OnStateChange(StateType state_changed) {\n\t\t\t}\n\n\t\t\t\/\/ Triggered when media is received on a new stream from remote peer.\n\t\t\tvoid GlobalObserver::OnAddStream(rtc::scoped_refptr stream) {\n\t\t\t\tauto evt = ref new Org::WebRtc::MediaStreamEvent();\n\t\t\t\tevt->Stream = ref new Org::WebRtc::MediaStream(stream);\n\t\t\t\tPOST_PC_EVENT(OnAddStream, evt);\n\t\t\t}\n\n\t\t\t\/\/ Triggered when a remote peer close a stream.\n\t\t\tvoid GlobalObserver::OnRemoveStream(rtc::scoped_refptr stream) {\n\t\t\t\tauto evt = ref new Org::WebRtc::MediaStreamEvent();\n\t\t\t\tevt->Stream = ref new Org::WebRtc::MediaStream(stream);\n\t\t\t\tPOST_PC_EVENT(OnRemoveStream, evt);\n\t\t\t}\n\n\t\t\t\/\/ Triggered when a remote peer open a data channel.\n\t\t\tvoid GlobalObserver::OnDataChannel(rtc::scoped_refptr data_channel) {\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCDataChannelEvent();\n\t\t\t\tevt->Channel = ref new Org::WebRtc::RTCDataChannel(data_channel);\n\t\t\t\t\/\/ This observer is deleted when the channel closes.\n\t\t\t\t\/\/ See DataChannelObserver::OnStateChange().\n\t\t\t\tdata_channel->RegisterObserver(new DataChannelObserver(evt->Channel));\n\t\t\t\tPOST_PC_EVENT(OnDataChannel, evt);\n\t\t\t}\n\n\t\t\t\/\/ Triggered when renegotiation is needed, for example the ICE has restarted.\n\t\t\tvoid GlobalObserver::OnRenegotiationNeeded() {\n\t\t\t\tPOST_PC_ACTION(OnNegotiationNeeded);\n\t\t\t}\n\n\t\t\t\/\/ Called any time the IceConnectionState changes\n\t\t\tvoid GlobalObserver::OnIceConnectionChange(\n\t\t\t\twebrtc::PeerConnectionInterface::IceConnectionState new_state) {\n\t\t\t\tif (new_state == webrtc::PeerConnectionInterface::kIceConnectionConnected) {\n\t\t\t\t\tif (!_stats_observer.get()) {\n\t\t\t\t\t\tauto temp_impl = _pc->_impl;\n\t\t\t\t\t\t_stats_observer =\n\t\t\t\t\t\t\tnew rtc::RefCountedObject(temp_impl);\n\t\t\t\t\t}\n\t\t\t\t\t_stats_observer->ToggleETWStats(_etwStatsEnabled);\n\t\t\t\t\t_stats_observer->ToggleConnectionHealthStats(\n\t\t\t\t\t\t_connectionHealthStatsEnabled ? this : NULL);\n\t\t\t\t\t_stats_observer->ToggleRTCStats(\n\t\t\t\t\t\t_rtcStatsEnabled ? this : NULL);\n\t\t\t\t\tif (_sendRtcStatsToRemoteHostEnabled) {\n\t\t\t\t\t\t_stats_observer->SetStatsNetworkDestination(\n\t\t\t\t\t\t\t_rtcStatsDestinationHost, _rtcStatsDestinationPort);\n\t\t\t\t\t}\n\t\t\t\t\t_stats_observer->ToggleStatsSendToRemoteHost(_sendRtcStatsToRemoteHostEnabled);\n\t\t\t\t}\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCPeerConnectionIceStateChangeEvent();\n\t\t\t\tOrg::WebRtc::RTCIceConnectionState cxNewState;\n\t\t\t\tToCx(new_state, &cxNewState);\n\t\t\t\tevt->State = cxNewState;\n\t\t\t\tPOST_PC_EVENT(OnIceConnectionChange, evt);\n\t\t\t}\n\n\t\t\t\/\/ Called any time the IceGatheringState changes\n\t\t\tvoid GlobalObserver::OnIceGatheringChange(\n\t\t\t\twebrtc::PeerConnectionInterface::IceGatheringState new_state) {\n\t\t\t\tLOG(LS_INFO) << \"OnIceGatheringChange\";\n\t\t\t}\n\n\t\t\t\/\/ New Ice candidate have been found.\n\t\t\tvoid GlobalObserver::OnIceCandidate(\n\t\t\t\tconst webrtc::IceCandidateInterface* candidate) {\n\t\t\t\tstd::string c;\n\t\t\t\tcandidate->ToString(&c);\n\t\t\t\tLOG(LS_INFO) << \"Ice candidate = \" << c;\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCPeerConnectionIceEvent();\n\t\t\t\tOrg::WebRtc::RTCIceCandidate^ cxCandidate;\n\t\t\t\tif (candidate == nullptr) {\n\t\t\t\t\tevt->Candidate = nullptr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tToCx(*candidate, &cxCandidate);\n\t\t\t\t\tevt->Candidate = cxCandidate;\n\t\t\t\t}\n\t\t\t\tPOST_PC_EVENT(OnIceCandidate, evt);\n\t\t\t}\n\n\t\t\t\/\/ TODO(bemasc): Remove this once callers transition to OnIceGatheringChange.\n\t\t\t\/\/ All Ice candidates have been found.\n\t\t\tvoid GlobalObserver::OnIceComplete() {\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCPeerConnectionIceEvent();\n\t\t\t\tevt->Candidate = nullptr;\n\t\t\t\tPOST_PC_EVENT(OnIceCandidate, evt);\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::OnConnectionHealthStats(\n\t\t\t\tconst webrtc::ConnectionHealthStats& stats) {\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCPeerConnectionHealthStats();\n\t\t\t\tevt->ReceivedBytes = stats.received_bytes;\n\t\t\t\tevt->ReceivedKpbs = stats.received_kbps;\n\t\t\t\tevt->SentBytes = stats.sent_bytes;\n\t\t\t\tevt->SentKbps = stats.sent_kbps;\n\t\t\t\tevt->RTT = stats.rtt;\n\t\t\t\tevt->LocalCandidateType = ToCx(stats.local_candidate_type);\n\t\t\t\tevt->RemoteCandidateType = ToCx(stats.remote_candidate_type);\n\t\t\t\tPOST_PC_EVENT(OnConnectionHealthStats, evt);\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::OnRTCStatsReportsReady(\n\t\t\t\tconst Org::WebRtc::RTCStatsReports& rtcStatsReports) {\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCStatsReportsReadyEvent();\n\t\t\t\tevt->rtcStatsReports = rtcStatsReports;\n\t\t\t\tPOST_PC_EVENT(OnRTCStatsReportsReady, evt);\n\t\t\t}\n\n\t\t\t\/\/============================================================================\n\n\t\t\tCreateSdpObserver::CreateSdpObserver(\n\t\t\t\tConcurrency::task_completion_event tce)\n\t\t\t\t: _tce(tce) {\n\t\t\t}\n\n\t\t\tvoid CreateSdpObserver::OnSuccess(webrtc::SessionDescriptionInterface* desc) {\n\t\t\t\t_tce.set(desc);\n\t\t\t}\n\n\t\t\tvoid CreateSdpObserver::OnFailure(const std::string& error) {\n\t\t\t\t_tce.set_exception(error);\n\t\t\t}\n\n\t\t\t\/\/============================================================================\n\n\t\t\tSetSdpObserver::SetSdpObserver(Concurrency::task_completion_event tce)\n\t\t\t\t: _tce(tce) {\n\t\t\t}\n\n\t\t\tvoid SetSdpObserver::OnSuccess() {\n\t\t\t\t_tce.set();\n\t\t\t}\n\n\t\t\tvoid SetSdpObserver::OnFailure(const std::string& error) {\n\t\t\t\t_tce.set_exception(error);\n\t\t\t}\n\n\t\t\t\/\/============================================================================\n\n\t\t\tDataChannelObserver::DataChannelObserver(\n\t\t\t\tOrg::WebRtc::RTCDataChannel^ channel)\n\t\t\t\t: _channel(channel) {\n\t\t\t}\n\n\t\t\tvoid DataChannelObserver::OnStateChange() {\n\t\t\t\tWindows::UI::Core::CoreDispatcher^ _windowDispatcher = webrtc::VideoCommonWinUWP::GetCoreDispatcher();\n\t\t\t\tswitch (_channel->GetImpl()->state()) {\n\t\t\t\tcase webrtc::DataChannelInterface::kOpen:\n\t\t\t\t\tif (_windowDispatcher != nullptr) {\n\t\t\t\t\t\t_windowDispatcher->RunAsync(\n\t\t\t\t\t\t\tWindows::UI::Core::CoreDispatcherPriority::Normal,\n\t\t\t\t\t\t\tref new Windows::UI::Core::DispatchedHandler([this] {\n\t\t\t\t\t\t\t_channel->OnOpen();\n\t\t\t\t\t\t}));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t_channel->OnOpen();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase webrtc::DataChannelInterface::kClosed:\n\t\t\t\t\t_channel->_impl->UnregisterObserver();\n\t\t\t\t\tif (_windowDispatcher != nullptr) {\n\t\t\t\t\t\t_windowDispatcher->RunAsync(\n\t\t\t\t\t\t\tWindows::UI::Core::CoreDispatcherPriority::Normal,\n\t\t\t\t\t\t\tref new Windows::UI::Core::DispatchedHandler([this] {\n\t\t\t\t\t\t\t_channel->OnClose();\n\t\t\t\t\t\t\tdelete this;\n\t\t\t\t\t\t}));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t_channel->OnClose();\n\t\t\t\t\t\tdelete this;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvoid DataChannelObserver::OnMessage(const webrtc::DataBuffer& buffer) {\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCDataChannelMessageEvent();\n\n\t\t\t\tif (!buffer.binary) {\n\t\t\t\t\t\/\/ convert buffer data from uint_8[] to char*\n\t\t\t\t\tString^ receivedString = ToCx(std::string(\n\t\t\t\t\t\treinterpret_cast(buffer.data.data()),\n\t\t\t\t\t\tbuffer.size()));\n\n\t\t\t\t\tevt->Data = ref new Org::WebRtc::StringDataChannelMessage(\n\t\t\t\t\t\treceivedString);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ convert byte[] from buffer to Vector\n\t\t\t\t\tstd::vector bytesFromBuffer = std::vector();\n\t\t\t\t\tbytesFromBuffer.insert(bytesFromBuffer.end(), buffer.data.data(),\n\t\t\t\t\t\tbuffer.data.data() + buffer.size());\n\t\t\t\t\tVector^ convertedBytes = ref new Vector();\n\t\t\t\t\tToCx(&bytesFromBuffer, convertedBytes);\n\n\t\t\t\t\tevt->Data = ref new Org::WebRtc::BinaryDataChannelMessage(\n\t\t\t\t\t\tconvertedBytes);\n\t\t\t\t}\n\n\n\t\t\t\tWindows::UI::Core::CoreDispatcher^ _windowDispatcher = webrtc::VideoCommonWinUWP::GetCoreDispatcher();\n\t\t\t\tif (_windowDispatcher != nullptr) {\n\t\t\t\t\t_windowDispatcher->RunAsync(\n\t\t\t\t\t\tWindows::UI::Core::CoreDispatcherPriority::Normal,\n\t\t\t\t\t\tref new Windows::UI::Core::DispatchedHandler([this, evt] {\n\t\t\t\t\t\t_channel->OnMessage(evt);\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t_channel->OnMessage(evt);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n} \/\/ namespace Org.WebRtc.Internal\n\ndon't delete DataChannerlObserver in OnStateChange\n\/\/ Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree. An additional intellectual property rights grant can be found\n\/\/ in the file PATENTS. All contributing project authors may\n\/\/ be found in the AUTHORS file in the root of the source tree.\n\n\/\/ Class1.cpp\n#include \n#include \n\n#include \"GlobalObserver.h\"\n#include \"PeerConnectionInterface.h\"\n#include \"Marshalling.h\"\n#include \"Media.h\"\n#include \"DataChannel.h\"\n#include \"webrtc\/common_video\/video_common_winuwp.h\"\n\nusing Platform::Collections::Vector;\n\nnamespace Org {\n\tnamespace WebRtc {\n\t\tnamespace Internal {\n\n#define POST_PC_EVENT(fn, evt) \\\n auto pc = _pc;\\\n Windows::UI::Core::CoreDispatcher^ _windowDispatcher = webrtc::VideoCommonWinUWP::GetCoreDispatcher();\\\n if (_windowDispatcher != nullptr) {\\\n _windowDispatcher->RunAsync(\\\n Windows::UI::Core::CoreDispatcherPriority::Normal, \\\n ref new Windows::UI::Core::DispatchedHandler([pc, evt] {\\\n if (pc != nullptr) {\\\n pc->##fn(evt);\\\n }\\\n }));\\\n } else {\\\n if (pc != nullptr) {\\\n pc->##fn(evt);\\\n }\\\n }\n\n#define POST_PC_ACTION(fn) \\\n auto pc = _pc;\\\n Windows::UI::Core::CoreDispatcher^ _windowDispatcher = webrtc::VideoCommonWinUWP::GetCoreDispatcher();\\\n if (_windowDispatcher != nullptr) {\\\n _windowDispatcher->RunAsync(\\\n Windows::UI::Core::CoreDispatcherPriority::Normal, \\\n ref new Windows::UI::Core::DispatchedHandler([pc] {\\\n if (pc != nullptr) {\\\n pc->##fn();\\\n }\\\n }));\\\n } else {\\\n if (pc != nullptr) {\\\n pc->##fn();\\\n }\\\n }\n\n\t\t\tGlobalObserver::GlobalObserver() {\n\t\t\t\tResetStatsConfig();\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::SetPeerConnection(\n\t\t\t\tOrg::WebRtc::RTCPeerConnection^ pc) {\n\t\t\t\t_pc = pc;\n\t\t\t\tif (_pc == nullptr) {\n\t\t\t\t\t_stats_observer = nullptr;\n\t\t\t\t}\n\t\t\t\tResetStatsConfig();\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::ResetStatsConfig() {\n\t\t\t\t_etwStatsEnabled = false;\n\t\t\t\t_connectionHealthStatsEnabled = false;\n\t\t\t\t_rtcStatsEnabled = false;\n\t\t\t\t_sendRtcStatsToRemoteHostEnabled = false;\n\t\t\t\t_rtcStatsDestinationHost = \"localhost\";\n\t\t\t\t_rtcStatsDestinationPort = 47005;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::EnableETWStats(bool enable) {\n\t\t\t\t_etwStatsEnabled = enable;\n\t\t\t\tif (_stats_observer) {\n\t\t\t\t\t_stats_observer->ToggleETWStats(enable);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool GlobalObserver::AreETWStatsEnabled() {\n\t\t\t\treturn _etwStatsEnabled;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::EnableConnectionHealthStats(bool enable) {\n\t\t\t\t_connectionHealthStatsEnabled = enable;\n\t\t\t\tif (_stats_observer) {\n\t\t\t\t\t_stats_observer->ToggleConnectionHealthStats(enable ? this : NULL);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool GlobalObserver::AreConnectionHealthStatsEnabled() {\n\t\t\t\treturn _connectionHealthStatsEnabled;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::EnableRTCStats(bool enable) {\n\t\t\t\t_rtcStatsEnabled = enable;\n\t\t\t\tif (_stats_observer) {\n\t\t\t\t\t_stats_observer->ToggleRTCStats(enable ? this : NULL);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool GlobalObserver::AreRTCStatsEnabled() {\n\t\t\t\treturn _rtcStatsEnabled;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::EnableSendRtcStatsToRemoteHost(bool enable) {\n\t\t\t\t_sendRtcStatsToRemoteHostEnabled = enable;\n\t\t\t\tif (_stats_observer) {\n\t\t\t\t\tif (enable) {\n\t\t\t\t\t\t_stats_observer->SetStatsNetworkDestination(\n\t\t\t\t\t\t\t_rtcStatsDestinationHost, _rtcStatsDestinationPort);\n\t\t\t\t\t}\n\t\t\t\t\t_stats_observer->ToggleStatsSendToRemoteHost(enable);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool GlobalObserver::IsSendRtcStatsToRemoteHostEnabled() {\n\t\t\t\treturn _sendRtcStatsToRemoteHostEnabled;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::SetRtcStatsDestinationHost(std::string value) {\n\t\t\t\t_rtcStatsDestinationHost = value;\n\t\t\t}\n\n\t\t\tstd::string GlobalObserver::GetRtcStatsDestinationHost() {\n\t\t\t\treturn _rtcStatsDestinationHost;\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::SetRtcStatsDestinationPort(int port) {\n\t\t\t\t_rtcStatsDestinationPort = port;\n\t\t\t}\n\t\t\tint GlobalObserver::GetRtcStatsDestinationPort() {\n\t\t\t\treturn _rtcStatsDestinationPort;\n\t\t\t}\n\n\n\t\t\t\/\/ Triggered when the SignalingState changed.\n\t\t\tvoid GlobalObserver::OnSignalingChange(\n\t\t\t\twebrtc::PeerConnectionInterface::SignalingState new_state) {\n\t\t\t\tPOST_PC_ACTION(OnSignalingStateChange);\n\t\t\t}\n\n\t\t\t\/\/ Triggered when SignalingState or IceState have changed.\n\t\t\t\/\/ TODO(bemasc): Remove once callers transition to OnSignalingChange.\n\t\t\tvoid GlobalObserver::OnStateChange(StateType state_changed) {\n\t\t\t}\n\n\t\t\t\/\/ Triggered when media is received on a new stream from remote peer.\n\t\t\tvoid GlobalObserver::OnAddStream(rtc::scoped_refptr stream) {\n\t\t\t\tauto evt = ref new Org::WebRtc::MediaStreamEvent();\n\t\t\t\tevt->Stream = ref new Org::WebRtc::MediaStream(stream);\n\t\t\t\tPOST_PC_EVENT(OnAddStream, evt);\n\t\t\t}\n\n\t\t\t\/\/ Triggered when a remote peer close a stream.\n\t\t\tvoid GlobalObserver::OnRemoveStream(rtc::scoped_refptr stream) {\n\t\t\t\tauto evt = ref new Org::WebRtc::MediaStreamEvent();\n\t\t\t\tevt->Stream = ref new Org::WebRtc::MediaStream(stream);\n\t\t\t\tPOST_PC_EVENT(OnRemoveStream, evt);\n\t\t\t}\n\n\t\t\t\/\/ Triggered when a remote peer open a data channel.\n\t\t\tvoid GlobalObserver::OnDataChannel(rtc::scoped_refptr data_channel) {\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCDataChannelEvent();\n\t\t\t\tevt->Channel = ref new Org::WebRtc::RTCDataChannel(data_channel);\n\t\t\t\t\/\/ This observer is deleted when the channel closes.\n\t\t\t\t\/\/ See DataChannelObserver::OnStateChange().\n\t\t\t\tdata_channel->RegisterObserver(new DataChannelObserver(evt->Channel));\n\t\t\t\tPOST_PC_EVENT(OnDataChannel, evt);\n\t\t\t}\n\n\t\t\t\/\/ Triggered when renegotiation is needed, for example the ICE has restarted.\n\t\t\tvoid GlobalObserver::OnRenegotiationNeeded() {\n\t\t\t\tPOST_PC_ACTION(OnNegotiationNeeded);\n\t\t\t}\n\n\t\t\t\/\/ Called any time the IceConnectionState changes\n\t\t\tvoid GlobalObserver::OnIceConnectionChange(\n\t\t\t\twebrtc::PeerConnectionInterface::IceConnectionState new_state) {\n\t\t\t\tif (new_state == webrtc::PeerConnectionInterface::kIceConnectionConnected) {\n\t\t\t\t\tif (!_stats_observer.get()) {\n\t\t\t\t\t\tauto temp_impl = _pc->_impl;\n\t\t\t\t\t\t_stats_observer =\n\t\t\t\t\t\t\tnew rtc::RefCountedObject(temp_impl);\n\t\t\t\t\t}\n\t\t\t\t\t_stats_observer->ToggleETWStats(_etwStatsEnabled);\n\t\t\t\t\t_stats_observer->ToggleConnectionHealthStats(\n\t\t\t\t\t\t_connectionHealthStatsEnabled ? this : NULL);\n\t\t\t\t\t_stats_observer->ToggleRTCStats(\n\t\t\t\t\t\t_rtcStatsEnabled ? this : NULL);\n\t\t\t\t\tif (_sendRtcStatsToRemoteHostEnabled) {\n\t\t\t\t\t\t_stats_observer->SetStatsNetworkDestination(\n\t\t\t\t\t\t\t_rtcStatsDestinationHost, _rtcStatsDestinationPort);\n\t\t\t\t\t}\n\t\t\t\t\t_stats_observer->ToggleStatsSendToRemoteHost(_sendRtcStatsToRemoteHostEnabled);\n\t\t\t\t}\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCPeerConnectionIceStateChangeEvent();\n\t\t\t\tOrg::WebRtc::RTCIceConnectionState cxNewState;\n\t\t\t\tToCx(new_state, &cxNewState);\n\t\t\t\tevt->State = cxNewState;\n\t\t\t\tPOST_PC_EVENT(OnIceConnectionChange, evt);\n\t\t\t}\n\n\t\t\t\/\/ Called any time the IceGatheringState changes\n\t\t\tvoid GlobalObserver::OnIceGatheringChange(\n\t\t\t\twebrtc::PeerConnectionInterface::IceGatheringState new_state) {\n\t\t\t\tLOG(LS_INFO) << \"OnIceGatheringChange\";\n\t\t\t}\n\n\t\t\t\/\/ New Ice candidate have been found.\n\t\t\tvoid GlobalObserver::OnIceCandidate(\n\t\t\t\tconst webrtc::IceCandidateInterface* candidate) {\n\t\t\t\tstd::string c;\n\t\t\t\tcandidate->ToString(&c);\n\t\t\t\tLOG(LS_INFO) << \"Ice candidate = \" << c;\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCPeerConnectionIceEvent();\n\t\t\t\tOrg::WebRtc::RTCIceCandidate^ cxCandidate;\n\t\t\t\tif (candidate == nullptr) {\n\t\t\t\t\tevt->Candidate = nullptr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tToCx(*candidate, &cxCandidate);\n\t\t\t\t\tevt->Candidate = cxCandidate;\n\t\t\t\t}\n\t\t\t\tPOST_PC_EVENT(OnIceCandidate, evt);\n\t\t\t}\n\n\t\t\t\/\/ TODO(bemasc): Remove this once callers transition to OnIceGatheringChange.\n\t\t\t\/\/ All Ice candidates have been found.\n\t\t\tvoid GlobalObserver::OnIceComplete() {\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCPeerConnectionIceEvent();\n\t\t\t\tevt->Candidate = nullptr;\n\t\t\t\tPOST_PC_EVENT(OnIceCandidate, evt);\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::OnConnectionHealthStats(\n\t\t\t\tconst webrtc::ConnectionHealthStats& stats) {\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCPeerConnectionHealthStats();\n\t\t\t\tevt->ReceivedBytes = stats.received_bytes;\n\t\t\t\tevt->ReceivedKpbs = stats.received_kbps;\n\t\t\t\tevt->SentBytes = stats.sent_bytes;\n\t\t\t\tevt->SentKbps = stats.sent_kbps;\n\t\t\t\tevt->RTT = stats.rtt;\n\t\t\t\tevt->LocalCandidateType = ToCx(stats.local_candidate_type);\n\t\t\t\tevt->RemoteCandidateType = ToCx(stats.remote_candidate_type);\n\t\t\t\tPOST_PC_EVENT(OnConnectionHealthStats, evt);\n\t\t\t}\n\n\t\t\tvoid GlobalObserver::OnRTCStatsReportsReady(\n\t\t\t\tconst Org::WebRtc::RTCStatsReports& rtcStatsReports) {\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCStatsReportsReadyEvent();\n\t\t\t\tevt->rtcStatsReports = rtcStatsReports;\n\t\t\t\tPOST_PC_EVENT(OnRTCStatsReportsReady, evt);\n\t\t\t}\n\n\t\t\t\/\/============================================================================\n\n\t\t\tCreateSdpObserver::CreateSdpObserver(\n\t\t\t\tConcurrency::task_completion_event tce)\n\t\t\t\t: _tce(tce) {\n\t\t\t}\n\n\t\t\tvoid CreateSdpObserver::OnSuccess(webrtc::SessionDescriptionInterface* desc) {\n\t\t\t\t_tce.set(desc);\n\t\t\t}\n\n\t\t\tvoid CreateSdpObserver::OnFailure(const std::string& error) {\n\t\t\t\t_tce.set_exception(error);\n\t\t\t}\n\n\t\t\t\/\/============================================================================\n\n\t\t\tSetSdpObserver::SetSdpObserver(Concurrency::task_completion_event tce)\n\t\t\t\t: _tce(tce) {\n\t\t\t}\n\n\t\t\tvoid SetSdpObserver::OnSuccess() {\n\t\t\t\t_tce.set();\n\t\t\t}\n\n\t\t\tvoid SetSdpObserver::OnFailure(const std::string& error) {\n\t\t\t\t_tce.set_exception(error);\n\t\t\t}\n\n\t\t\t\/\/============================================================================\n\n\t\t\tDataChannelObserver::DataChannelObserver(\n\t\t\t\tOrg::WebRtc::RTCDataChannel^ channel)\n\t\t\t\t: _channel(channel) {\n\t\t\t}\n\n\t\t\tvoid DataChannelObserver::OnStateChange() {\n\t\t\t\tWindows::UI::Core::CoreDispatcher^ _windowDispatcher = webrtc::VideoCommonWinUWP::GetCoreDispatcher();\n\t\t\t\tswitch (_channel->GetImpl()->state()) {\n\t\t\t\tcase webrtc::DataChannelInterface::kOpen:\n\t\t\t\t\tif (_windowDispatcher != nullptr) {\n\t\t\t\t\t\t_windowDispatcher->RunAsync(\n\t\t\t\t\t\t\tWindows::UI::Core::CoreDispatcherPriority::Normal,\n\t\t\t\t\t\t\tref new Windows::UI::Core::DispatchedHandler([this] {\n\t\t\t\t\t\t\t_channel->OnOpen();\n\t\t\t\t\t\t}));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t_channel->OnOpen();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase webrtc::DataChannelInterface::kClosed:\n\t\t\t\t\t_channel->_impl->UnregisterObserver();\n\t\t\t\t\tif (_windowDispatcher != nullptr) {\n\t\t\t\t\t\t_windowDispatcher->RunAsync(\n\t\t\t\t\t\t\tWindows::UI::Core::CoreDispatcherPriority::Normal,\n\t\t\t\t\t\t\tref new Windows::UI::Core::DispatchedHandler([this] {\n\t\t\t\t\t\t\t_channel->OnClose();\n\t\t\t\t\t\t\t\/\/delete this;\n\t\t\t\t\t\t}));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t_channel->OnClose();\n\t\t\t\t\t\t\/\/delete this;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvoid DataChannelObserver::OnMessage(const webrtc::DataBuffer& buffer) {\n\t\t\t\tauto evt = ref new Org::WebRtc::RTCDataChannelMessageEvent();\n\n\t\t\t\tif (!buffer.binary) {\n\t\t\t\t\t\/\/ convert buffer data from uint_8[] to char*\n\t\t\t\t\tString^ receivedString = ToCx(std::string(\n\t\t\t\t\t\treinterpret_cast(buffer.data.data()),\n\t\t\t\t\t\tbuffer.size()));\n\n\t\t\t\t\tevt->Data = ref new Org::WebRtc::StringDataChannelMessage(\n\t\t\t\t\t\treceivedString);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ convert byte[] from buffer to Vector\n\t\t\t\t\tstd::vector bytesFromBuffer = std::vector();\n\t\t\t\t\tbytesFromBuffer.insert(bytesFromBuffer.end(), buffer.data.data(),\n\t\t\t\t\t\tbuffer.data.data() + buffer.size());\n\t\t\t\t\tVector^ convertedBytes = ref new Vector();\n\t\t\t\t\tToCx(&bytesFromBuffer, convertedBytes);\n\n\t\t\t\t\tevt->Data = ref new Org::WebRtc::BinaryDataChannelMessage(\n\t\t\t\t\t\tconvertedBytes);\n\t\t\t\t}\n\n\n\t\t\t\tWindows::UI::Core::CoreDispatcher^ _windowDispatcher = webrtc::VideoCommonWinUWP::GetCoreDispatcher();\n\t\t\t\tif (_windowDispatcher != nullptr) {\n\t\t\t\t\t_windowDispatcher->RunAsync(\n\t\t\t\t\t\tWindows::UI::Core::CoreDispatcherPriority::Normal,\n\t\t\t\t\t\tref new Windows::UI::Core::DispatchedHandler([this, evt] {\n\t\t\t\t\t\t_channel->OnMessage(evt);\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t_channel->OnMessage(evt);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n} \/\/ namespace Org.WebRtc.Internal\n\n<|endoftext|>"} {"text":"\/\/ -*- c-basic-offset: 2; related-file-name: \"task.h\" -*-\n\/*\n * @(#)$Id$\n *\n * Modified from the Click Task class by Eddie Kohler and Benjie Chen\n * \n * Copyright (c) 1999-2000 Massachusetts Institute of Technology\n * Copyright (c) 2004 Regents of the University of California\n * Copyright (c) 2004 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\")\n * to deal in the Software without restriction, subject to the conditions\n * listed in the Click LICENSE file. These conditions include: you must\n * preserve this copyright notice, and you cannot mention the copyright\n * holders in advertising related to the Software without their permission.\n * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This\n * notice is a summary of the Click LICENSE file; the license in that file is\n * legally binding.\n * \n * This file is distributed under the terms in the attached INTEL-LICENSE file.\n * If you do not find these files, copies can be found by writing to:\n * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,\n * Berkeley, CA, 94704. Attention: Intel License Inquiry.\n * \n * DESCRIPTION: A linked list of schedulable entities\n *\/\n\n#include \n#include \n#include \n#include \n\n\/\/ - Changes to _thread are protected by _thread->lock.\n\/\/ - Changes to _thread_preference are protected by\n\/\/ _router->master()->task_lock.\n\/\/ - If _pending is nonzero, then _pending_next is nonnull.\n\/\/ - Either _thread_preference == _thread->thread_id(), or\n\/\/ _thread->thread_id() == -1.\n\n\nREMOVABLE_INLINE Task::Task()\n : _prev(0),\n _next(0),\n _thread(0),\n _router(0),\n _pending(0),\n _pending_next(0)\n{\n}\n\nMaster * Task::master() const\n{\n assert(_thread);\n return _thread->master();\n}\n\nvoid Task::initialize(Router* router,\n bool join)\n{\n assert(!initialized() && !scheduled());\n\n _router = router;\n \n _thread = router->master()->thread();\n \n if (join)\n add_pending(RESCHEDULE);\n}\n\nvoid Task::add_pending(int p)\n{\n Master *m = _router->master();\n m->_task_lock.acquire();\n _pending |= p;\n if (!_pending_next && _pending) {\n _pending_next = m->_task_list._pending_next;\n m->_task_list._pending_next = this;\n }\n if (_pending)\n _thread->add_pending();\n m->_task_lock.release();\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nbool Task::error_hook(Task *, void *)\n{\n assert(0);\n return false;\n}\n\nvoid Task::make_list()\n{\n _pending_next = this;\n}\n\nTask::~Task()\n{\n if (scheduled() || _pending)\n cleanup();\n}\n\nvoid Task::cleanup()\n{\n if (initialized()) {\n strong_unschedule();\n\n if (_pending) {\n Master *m = _router->master();\n m->_task_lock.acquire();\n Task *prev = &m->_task_list;\n for (Task *t = prev->_pending_next; t != &m->_task_list; prev = t, t = t->_pending_next)\n if (t == this) {\n prev->_pending_next = t->_pending_next;\n break;\n }\n _pending = 0;\n _pending_next = 0;\n m->_task_lock.release();\n }\n\t\n _router = 0;\n _thread = 0;\n }\n}\n\ninline void\nTask::lock_tasks()\n{\n while (1) {\n RouterThread *t = _thread;\n t->lock_tasks();\n if (t == _thread)\n return;\n t->unlock_tasks();\n }\n}\n\ninline bool\nTask::attempt_lock_tasks()\n{\n RouterThread *t = _thread;\n if (t->attempt_lock_tasks()) {\n if (t == _thread)\n return true;\n t->unlock_tasks();\n }\n return false;\n}\n\nvoid\nTask::unschedule()\n{\n \/\/ Thanksgiving 2001: unschedule() will always unschedule the task. This\n \/\/ seems more reliable, since some people depend on unschedule() ensuring\n \/\/ that the task is not scheduled any more, no way, no how. Possible\n \/\/ problem: calling unschedule() from run_task() will hang!\n if (_thread) {\n lock_tasks();\n fast_unschedule();\n _pending &= ~RESCHEDULE;\n _thread->unlock_tasks();\n }\n}\n\nvoid Task::true_reschedule()\n{\n assert(_thread);\n bool done = false;\n \/\/ If I can lock the queue\n if (attempt_lock_tasks()) {\n if (!scheduled()) {\n \/\/ I've already locked, so call the fast_ version\n fast_schedule();\n _thread->unsleep();\n }\n done = true;\n _thread->unlock_tasks();\n }\n\n \/\/ Wasn't able to lock the queue. Try later\n if (!done)\n add_pending(RESCHEDULE);\n}\n\nvoid Task::strong_unschedule()\n{\n \/\/ unschedule() and move to the quiescent thread, so that subsequent\n \/\/ reschedule()s won't have any effect\n if (_thread) {\n lock_tasks();\n fast_unschedule();\n RouterThread *old_thread = _thread;\n _pending &= ~RESCHEDULE;\n _thread = _router->master()->thread();\n old_thread->unlock_tasks();\n }\n}\n\nvoid Task::strong_reschedule()\n{\n assert(_thread);\n lock_tasks();\n fast_unschedule();\n RouterThread *old_thread = _thread;\n _thread = _router->master()->thread();\n add_pending(RESCHEDULE);\n old_thread->unlock_tasks();\n}\n\nvoid Task::process_pending(RouterThread *thread)\n{\n \/\/ must be called with thread->lock held\n if (_thread == thread) {\n if (_pending & RESCHEDULE) {\n _pending &= ~RESCHEDULE;\n if (!scheduled())\n fast_schedule();\n }\n }\n \n if (_pending)\n add_pending(0);\n}\n\n\nREMOVABLE_INLINE int Task::fast_unschedule()\n{\n if (_prev) {\n _next->_prev = _prev;\n _prev->_next = _next;\n _next = _prev = 0;\n }\n return 0;\n}\n\nREMOVABLE_INLINE void Task::fast_reschedule()\n{\n assert(_thread);\n if (!scheduled()) {\n _prev = _thread->_taskList._prev;\n _next = &_thread->_taskList;\n _thread->_taskList._prev = this;\n _thread->_taskList._next = this;\n }\n}\n\nREMOVABLE_INLINE void Task::reschedule()\n{\n assert(_thread);\n if (!scheduled())\n true_reschedule();\n}\n\nREMOVABLE_INLINE void Task::fast_schedule()\n{\n fast_reschedule();\n}\n\nsyntax protection\/\/ -*- c-basic-offset: 2; related-file-name: \"task.h\" -*-\n\/*\n * @(#)$Id$\n *\n * Modified from the Click Task class by Eddie Kohler and Benjie Chen\n * \n * Copyright (c) 1999-2000 Massachusetts Institute of Technology\n * Copyright (c) 2004 Regents of the University of California\n * Copyright (c) 2004 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\")\n * to deal in the Software without restriction, subject to the conditions\n * listed in the Click LICENSE file. These conditions include: you must\n * preserve this copyright notice, and you cannot mention the copyright\n * holders in advertising related to the Software without their permission.\n * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This\n * notice is a summary of the Click LICENSE file; the license in that file is\n * legally binding.\n * \n * This file is distributed under the terms in the attached INTEL-LICENSE file.\n * If you do not find these files, copies can be found by writing to:\n * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,\n * Berkeley, CA, 94704. Attention: Intel License Inquiry.\n * \n * DESCRIPTION: A linked list of schedulable entities\n *\/\n\n#include \n#include \n#include \n#include \n\n\/\/ - Changes to _thread are protected by _thread->lock.\n\/\/ - Changes to _thread_preference are protected by\n\/\/ _router->master()->task_lock.\n\/\/ - If _pending is nonzero, then _pending_next is nonnull.\n\/\/ - Either _thread_preference == _thread->thread_id(), or\n\/\/ _thread->thread_id() == -1.\n\n\nREMOVABLE_INLINE Task::Task()\n : _prev(0),\n _next(0),\n _thread(0),\n _router(0),\n _pending(0),\n _pending_next(0)\n{\n}\n\nMaster * Task::master() const\n{\n assert(_thread);\n return _thread->master();\n}\n\nvoid Task::initialize(Router* router,\n bool join)\n{\n assert(!initialized() && !scheduled());\n\n _router = router;\n \n _thread = router->master()->thread();\n \n if (join)\n add_pending(RESCHEDULE);\n}\n\nvoid Task::add_pending(int p)\n{\n Master *m = _router->master();\n m->_task_lock.acquire();\n _pending |= p;\n if (!_pending_next && _pending) {\n _pending_next = m->_task_list._pending_next;\n m->_task_list._pending_next = this;\n }\n if (_pending) {\n _thread->add_pending();\n }\n m->_task_lock.release();\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nbool Task::error_hook(Task *, void *)\n{\n assert(0);\n return false;\n}\n\nvoid Task::make_list()\n{\n _pending_next = this;\n}\n\nTask::~Task()\n{\n if (scheduled() || _pending) {\n cleanup();\n }\n}\n\nvoid Task::cleanup()\n{\n if (initialized()) {\n strong_unschedule();\n\n if (_pending) {\n Master *m = _router->master();\n m->_task_lock.acquire();\n Task *prev = &m->_task_list;\n for (Task *t = prev->_pending_next; t != &m->_task_list; prev = t, t = t->_pending_next)\n if (t == this) {\n prev->_pending_next = t->_pending_next;\n break;\n }\n _pending = 0;\n _pending_next = 0;\n m->_task_lock.release();\n }\n\t\n _router = 0;\n _thread = 0;\n }\n}\n\ninline void\nTask::lock_tasks()\n{\n while (1) {\n RouterThread *t = _thread;\n t->lock_tasks();\n if (t == _thread)\n return;\n t->unlock_tasks();\n }\n}\n\ninline bool\nTask::attempt_lock_tasks()\n{\n RouterThread *t = _thread;\n if (t->attempt_lock_tasks()) {\n if (t == _thread)\n return true;\n t->unlock_tasks();\n }\n return false;\n}\n\nvoid\nTask::unschedule()\n{\n \/\/ Thanksgiving 2001: unschedule() will always unschedule the task. This\n \/\/ seems more reliable, since some people depend on unschedule() ensuring\n \/\/ that the task is not scheduled any more, no way, no how. Possible\n \/\/ problem: calling unschedule() from run_task() will hang!\n if (_thread) {\n lock_tasks();\n fast_unschedule();\n _pending &= ~RESCHEDULE;\n _thread->unlock_tasks();\n }\n}\n\nvoid Task::true_reschedule()\n{\n assert(_thread);\n bool done = false;\n \/\/ If I can lock the queue\n if (attempt_lock_tasks()) {\n if (!scheduled()) {\n \/\/ I've already locked, so call the fast_ version\n fast_schedule();\n _thread->unsleep();\n }\n done = true;\n _thread->unlock_tasks();\n }\n\n \/\/ Wasn't able to lock the queue. Try later\n if (!done)\n add_pending(RESCHEDULE);\n}\n\nvoid Task::strong_unschedule()\n{\n \/\/ unschedule() and move to the quiescent thread, so that subsequent\n \/\/ reschedule()s won't have any effect\n if (_thread) {\n lock_tasks();\n fast_unschedule();\n RouterThread *old_thread = _thread;\n _pending &= ~RESCHEDULE;\n _thread = _router->master()->thread();\n old_thread->unlock_tasks();\n }\n}\n\nvoid Task::strong_reschedule()\n{\n assert(_thread);\n lock_tasks();\n fast_unschedule();\n RouterThread *old_thread = _thread;\n _thread = _router->master()->thread();\n add_pending(RESCHEDULE);\n old_thread->unlock_tasks();\n}\n\nvoid Task::process_pending(RouterThread *thread)\n{\n \/\/ must be called with thread->lock held\n if (_thread == thread) {\n if (_pending & RESCHEDULE) {\n _pending &= ~RESCHEDULE;\n if (!scheduled())\n fast_schedule();\n }\n }\n \n if (_pending)\n add_pending(0);\n}\n\n\nREMOVABLE_INLINE int Task::fast_unschedule()\n{\n if (_prev) {\n _next->_prev = _prev;\n _prev->_next = _next;\n _next = _prev = 0;\n }\n return 0;\n}\n\nREMOVABLE_INLINE void Task::fast_reschedule()\n{\n assert(_thread);\n if (!scheduled()) {\n _prev = _thread->_taskList._prev;\n _next = &_thread->_taskList;\n _thread->_taskList._prev = this;\n _thread->_taskList._next = this;\n }\n}\n\nREMOVABLE_INLINE void Task::reschedule()\n{\n assert(_thread);\n if (!scheduled())\n true_reschedule();\n}\n\nREMOVABLE_INLINE void Task::fast_schedule()\n{\n fast_reschedule();\n}\n\n<|endoftext|>"} {"text":"#include \"BluPrivatePCH.h\"\n\nclass FBlu : public IBlu\n{\n\n\t\/** IModuleInterface implementation *\/\n\tvirtual void StartupModule() override\n\t{\n\n\t\tFString GameDir = FPaths::ConvertRelativePathToFull(FPaths::GameDir() + \"BluCache\");\n\t\tCefString GameDirCef = *GameDir;\n\n\t\t\/\/ Setup the default settings for BluManager\n\t\tBluManager::settings.windowless_rendering_enabled = true;\n\t\tBluManager::settings.no_sandbox = true;\n\t\tBluManager::settings.multi_threaded_message_loop = 1;\n\t\tBluManager::settings.remote_debugging_port = 7777;\n\t\t\n#if PLATFORM_LINUX\n\t\tCefString(&BluManager::settings.browser_subprocess_path).FromASCII(\".\/blu_ue4_process\");\n#endif\n#if PLATFORM_WINDOWS\n\t\tCefString(&BluManager::settings.browser_subprocess_path).FromASCII(\".\/blu_ue4_process.exe\");\n#endif\n\t\tCefString(&BluManager::settings.cache_path).FromString(GameDirCef);\n\n\t\tCefExecuteProcess(BluManager::main_args, NULL, NULL);\n\t\tCefInitialize(BluManager::main_args, BluManager::settings, NULL, NULL);\n\n\t\tUE_LOG(LogBlu, Log, TEXT(\" STATUS: Loaded\"));\n\t}\n\n\tvirtual void ShutdownModule() override\n\t{\n\t\tUE_LOG(LogBlu, Log, TEXT(\" STATUS: Shutdown\"));\n\t\tCefShutdown();\n\t}\n\n};\n\n\n\n\nIMPLEMENT_MODULE( FBlu, Blu )\nDEFINE_LOG_CATEGORY(LogBlu);Revert \"Allow multi-thread message loop\"#include \"BluPrivatePCH.h\"\n\nclass FBlu : public IBlu\n{\n\n\t\/** IModuleInterface implementation *\/\n\tvirtual void StartupModule() override\n\t{\n\n\t\tFString GameDir = FPaths::ConvertRelativePathToFull(FPaths::GameDir() + \"BluCache\");\n\t\tCefString GameDirCef = *GameDir;\n\n\t\t\/\/ Setup the default settings for BluManager\n\t\tBluManager::settings.windowless_rendering_enabled = true;\n\t\tBluManager::settings.no_sandbox = true;\n\n\t\tBluManager::settings.remote_debugging_port = 7777;\n\t\t\n#if PLATFORM_LINUX\n\t\tCefString(&BluManager::settings.browser_subprocess_path).FromASCII(\".\/blu_ue4_process\");\n#endif\n#if PLATFORM_WINDOWS\n\t\tCefString(&BluManager::settings.browser_subprocess_path).FromASCII(\".\/blu_ue4_process.exe\");\n#endif\n\t\tCefString(&BluManager::settings.cache_path).FromString(GameDirCef);\n\n\t\tCefExecuteProcess(BluManager::main_args, NULL, NULL);\n\t\tCefInitialize(BluManager::main_args, BluManager::settings, NULL, NULL);\n\n\t\tUE_LOG(LogBlu, Log, TEXT(\" STATUS: Loaded\"));\n\t}\n\n\tvirtual void ShutdownModule() override\n\t{\n\t\tUE_LOG(LogBlu, Log, TEXT(\" STATUS: Shutdown\"));\n\t\tCefShutdown();\n\t}\n\n};\n\n\n\n\nIMPLEMENT_MODULE( FBlu, Blu )\nDEFINE_LOG_CATEGORY(LogBlu);<|endoftext|>"} {"text":"\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \n#include \nLOG_SETUP(\".proton.metrics.legacy_documentdb_metrics\");\n#include \"legacy_documentdb_metrics.h\"\n#include \n\nusing vespalib::asciistream;\nusing vespalib::make_string;\nusing metrics::MetricSet;\n\nnamespace proton {\n\nusing matching::MatchingStats;\n\nLegacyDocumentDBMetrics::IndexMetrics::IndexMetrics(MetricSet *parent)\n : MetricSet(\"index\", \"\", \"Index metrics\", parent),\n memoryUsage(\"memoryusage\", \"\", \"Memory usage for memory indexes\", this),\n docsInMemory(\"docsinmemory\", \"\", \"Number of documents in memory\", this),\n diskUsage(\"diskusage\", \"\", \"Disk usage for disk indexes\", this)\n{\n}\n\nLegacyDocumentDBMetrics::DocstoreMetrics::DocstoreMetrics(MetricSet *parent)\n : MetricSet(\"docstore\", \"\", \"Document store metrics\", parent),\n memoryUsage(\"memoryusage\", \"\", \"Memory usage for docstore\", this),\n cacheLookups(\"cachelookups\", \"\", \"Number of lookups in summary cache\",\n this),\n hits(0),\n cacheHitRate(\"cachehitrate\", \"\", \"Rate of cache hits in summary cache\",\n this),\n cacheElements(\"cacheelements\", \"\", \"Number of elements in summary cache\",\n this),\n cacheMemoryUsed(\"cachememoryused\", \"\", \"Memory used by summary cache\",\n this)\n{\n}\n\nvoid\nLegacyDocumentDBMetrics::MatchingMetrics::update(const MatchingStats &stats)\n{\n docsMatched.inc(stats.docsMatched());\n docsRanked.inc(stats.docsRanked());\n docsReRanked.inc(stats.docsReRanked());\n queries.inc(stats.queries());\n queryCollateralTime.addValueBatch(stats.queryCollateralTimeAvg(),\n stats.queryCollateralTimeCount());\n queryLatency.addValueBatch(stats.queryLatencyAvg(),\n stats.queryLatencyCount());\n}\n\nLegacyDocumentDBMetrics::MatchingMetrics::MatchingMetrics(MetricSet *parent)\n : MetricSet(\"matching\", \"\", \"Matching metrics\", parent),\n docsMatched(\"docsmatched\", \"\", \"Number of documents matched\", this),\n docsRanked(\"docsranked\", \"\", \"Number of documents ranked (first phase)\", this),\n docsReRanked(\"docsreranked\", \"\",\n \"Number of documents re-ranked (second phase)\", this),\n queries(\"queries\", \"\", \"Number of queries executed\", this),\n queryCollateralTime(\"querycollateraltime\", \"\", \"Average time spent setting up and tearing down queries\", this),\n queryLatency(\"querylatency\", \"\", \"Average latency when matching a query\", this)\n{\n}\n\nLegacyDocumentDBMetrics::MatchingMetrics::RankProfileMetrics::RankProfileMetrics(\n const std::string &name, size_t numDocIdPartitions, MetricSet *parent)\n : MetricSet(name, \"\", \"Rank profile metrics\", parent),\n queries(\"queries\", \"\", \"Number of queries executed\", this),\n limited_queries(\"limitedqueries\", \"\", \"Number of queries limited in match phase\", this),\n matchTime(\"match_time\", \"\", \"Average time for matching a query\", this),\n groupingTime(\"grouping_time\", \"\", \"Average time spent on grouping\", this),\n rerankTime(\"rerank_time\", \"\", \"Average time spent on 2nd phase ranking\", this)\n{\n for (size_t i=0; i < numDocIdPartitions; i++) {\n vespalib::string s(make_string(\"docid_part%02ld\", i));\n partitions.push_back(DocIdPartition::LP(new DocIdPartition(s, this)));\n }\n}\n\nLegacyDocumentDBMetrics::MatchingMetrics::RankProfileMetrics::DocIdPartition::DocIdPartition(const std::string &name, MetricSet *parent) :\n MetricSet(name, \"\", \"DocId Partition profile metrics\", parent),\n docsMatched(\"docsmatched\", \"\", \"Number of documents matched\", this),\n docsRanked(\"docsranked\", \"\", \"Number of documents ranked (first phase)\", this),\n docsReRanked(\"docsreranked\", \"\",\n \"Number of documents re-ranked (second phase)\", this),\n active_time(\"activetime\", \"\", \"Time spent doing actual work\", this),\n wait_time(\"waittime\", \"\", \"Time spent waiting for other external threads and resources\", this)\n{\n}\n\nvoid\nLegacyDocumentDBMetrics::MatchingMetrics::RankProfileMetrics::DocIdPartition::update(const MatchingStats::Partition &stats)\n{\n docsMatched.inc(stats.docsMatched());\n docsRanked.inc(stats.docsRanked());\n docsReRanked.inc(stats.docsReRanked());\n active_time.addValueBatch(stats.active_time_avg(), stats.active_time_count());\n wait_time.addValueBatch(stats.wait_time_avg(), stats.wait_time_count());\n}\n\nvoid\nLegacyDocumentDBMetrics::MatchingMetrics::RankProfileMetrics::update(const MatchingStats &stats)\n{\n queries.inc(stats.queries());\n limited_queries.inc(stats.limited_queries());\n matchTime.addValueBatch(stats.matchTimeAvg(), stats.matchTimeCount());\n groupingTime.addValueBatch(stats.groupingTimeAvg(),\n stats.groupingTimeCount());\n rerankTime.addValueBatch(stats.rerankTimeAvg(), stats.rerankTimeCount());\n if (stats.getNumPartitions() > 0) {\n if (stats.getNumPartitions() == partitions.size()) {\n for (size_t i(0), m(stats.getNumPartitions()); i < m; i++) {\n DocIdPartition & partition(*partitions[i]);\n const MatchingStats::Partition & s(stats.getPartition(i));\n partition.update(s);\n }\n } else {\n vespalib::string msg(make_string(\"Num partitions use '%ld' is not equal to number of partitions '%ld' configured.\",\n stats.getNumPartitions(),\n partitions.size()));\n throw vespalib::IllegalStateException(msg, VESPA_STRLOC);\n }\n }\n}\n\nLegacyDocumentDBMetrics::SubDBMetrics::DocumentMetaStoreMetrics::\nDocumentMetaStoreMetrics(MetricSet *parent)\n : MetricSet(\"docmetastore\", \"\", \"Document meta store metrics\", parent),\n lidLimit(\"lidlimit\", \"\", \"The size of the allocated lid space\", this),\n usedLids(\"usedlids\", \"\", \"The number of lids used\", this),\n lowestFreeLid(\"lowestfreelid\", \"\", \"The lowest free lid\", this),\n highestUsedLid(\"highestusedlid\", \"\", \"The highest used lid\", this),\n lidBloatFactor(\"lidbloatfactor\", \"\", \"The bloat factor of this lid space, indicating the total amount of holes in the allocated lid space \"\n \"((lidlimit - usedlids) \/ lidlimit)\", this),\n lidFragmentationFactor(\"lid_fragmentation_factor\", \"\",\n \"The fragmentation factor of this lid space, indicating the amount of holes in the currently used part of the lid space \"\n \"((highestusedlid - usedlids) \/ highestusedlid)\", this)\n{\n}\n\nLegacyDocumentDBMetrics::SubDBMetrics::SubDBMetrics(const vespalib::string &name,\n MetricSet *parent)\n : MetricSet(name, \"\", \"Sub database metrics\", parent),\n attributes(this),\n docMetaStore(this)\n{\n}\n\nLegacyDocumentDBMetrics::LegacyDocumentDBMetrics(const std::string &docTypeName, size_t maxNumThreads)\n : MetricSet(make_string(\"%s\", docTypeName.c_str()), \"\", \"Document DB Metrics\", 0),\n index(this),\n attributes(this),\n docstore(this),\n matching(this),\n executor(\"executor\", this),\n indexExecutor(\"indexexecutor\", this),\n feed(this),\n sessionManager(this),\n ready(\"ready\", this),\n notReady(\"notready\", this),\n removed(\"removed\", this),\n memoryUsage(\"memoryusage\", \"\", \"Memory usage for this Document DB\",\n this),\n numDocs(\"numdocs\", \"\",\n \"Number of ready\/indexed documents in this Document DB (aka number of documents in the 'ready' sub db)\", this),\n numActiveDocs(\"numactivedocs\", \"\",\n \"Number of active\/searchable documents in this Document DB (aka number of active\/searchable documents in the 'ready' sub db)\", this),\n numIndexedDocs(\"numindexeddocs\", \"\",\n \"Number of ready\/indexed documents in this Document DB (aka number of documents in the 'ready' sub db)\", this),\n numStoredDocs(\"numstoreddocs\", \"\",\n \"Total number of documents stored in this Document DB (aka number of documents in the 'ready' and 'notready' sub dbs)\", this),\n numRemovedDocs(\"numremoveddocs\", \"\",\n \"Number of removed documents in this Document DB (aka number of documents in the 'removed' sub db)\", this),\n numBadConfigs(\"numBadConfigs\", \"\",\n \"Number of bad configs for this Document DB\", this),\n _maxNumThreads(maxNumThreads)\n{\n memoryUsage.addMetricToSum(index.memoryUsage);\n memoryUsage.addMetricToSum(attributes.memoryUsage);\n memoryUsage.addMetricToSum(docstore.memoryUsage);\n}\n\n} \/\/ namespace proton\nAllow to update metrics even if you have actually used less partitions.\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \n#include \nLOG_SETUP(\".proton.metrics.legacy_documentdb_metrics\");\n#include \"legacy_documentdb_metrics.h\"\n#include \n\nusing vespalib::asciistream;\nusing vespalib::make_string;\nusing metrics::MetricSet;\n\nnamespace proton {\n\nusing matching::MatchingStats;\n\nLegacyDocumentDBMetrics::IndexMetrics::IndexMetrics(MetricSet *parent)\n : MetricSet(\"index\", \"\", \"Index metrics\", parent),\n memoryUsage(\"memoryusage\", \"\", \"Memory usage for memory indexes\", this),\n docsInMemory(\"docsinmemory\", \"\", \"Number of documents in memory\", this),\n diskUsage(\"diskusage\", \"\", \"Disk usage for disk indexes\", this)\n{\n}\n\nLegacyDocumentDBMetrics::DocstoreMetrics::DocstoreMetrics(MetricSet *parent)\n : MetricSet(\"docstore\", \"\", \"Document store metrics\", parent),\n memoryUsage(\"memoryusage\", \"\", \"Memory usage for docstore\", this),\n cacheLookups(\"cachelookups\", \"\", \"Number of lookups in summary cache\",\n this),\n hits(0),\n cacheHitRate(\"cachehitrate\", \"\", \"Rate of cache hits in summary cache\",\n this),\n cacheElements(\"cacheelements\", \"\", \"Number of elements in summary cache\",\n this),\n cacheMemoryUsed(\"cachememoryused\", \"\", \"Memory used by summary cache\",\n this)\n{\n}\n\nvoid\nLegacyDocumentDBMetrics::MatchingMetrics::update(const MatchingStats &stats)\n{\n docsMatched.inc(stats.docsMatched());\n docsRanked.inc(stats.docsRanked());\n docsReRanked.inc(stats.docsReRanked());\n queries.inc(stats.queries());\n queryCollateralTime.addValueBatch(stats.queryCollateralTimeAvg(),\n stats.queryCollateralTimeCount());\n queryLatency.addValueBatch(stats.queryLatencyAvg(),\n stats.queryLatencyCount());\n}\n\nLegacyDocumentDBMetrics::MatchingMetrics::MatchingMetrics(MetricSet *parent)\n : MetricSet(\"matching\", \"\", \"Matching metrics\", parent),\n docsMatched(\"docsmatched\", \"\", \"Number of documents matched\", this),\n docsRanked(\"docsranked\", \"\", \"Number of documents ranked (first phase)\", this),\n docsReRanked(\"docsreranked\", \"\",\n \"Number of documents re-ranked (second phase)\", this),\n queries(\"queries\", \"\", \"Number of queries executed\", this),\n queryCollateralTime(\"querycollateraltime\", \"\", \"Average time spent setting up and tearing down queries\", this),\n queryLatency(\"querylatency\", \"\", \"Average latency when matching a query\", this)\n{\n}\n\nLegacyDocumentDBMetrics::MatchingMetrics::RankProfileMetrics::RankProfileMetrics(\n const std::string &name, size_t numDocIdPartitions, MetricSet *parent)\n : MetricSet(name, \"\", \"Rank profile metrics\", parent),\n queries(\"queries\", \"\", \"Number of queries executed\", this),\n limited_queries(\"limitedqueries\", \"\", \"Number of queries limited in match phase\", this),\n matchTime(\"match_time\", \"\", \"Average time for matching a query\", this),\n groupingTime(\"grouping_time\", \"\", \"Average time spent on grouping\", this),\n rerankTime(\"rerank_time\", \"\", \"Average time spent on 2nd phase ranking\", this)\n{\n for (size_t i=0; i < numDocIdPartitions; i++) {\n vespalib::string s(make_string(\"docid_part%02ld\", i));\n partitions.push_back(DocIdPartition::LP(new DocIdPartition(s, this)));\n }\n}\n\nLegacyDocumentDBMetrics::MatchingMetrics::RankProfileMetrics::DocIdPartition::DocIdPartition(const std::string &name, MetricSet *parent) :\n MetricSet(name, \"\", \"DocId Partition profile metrics\", parent),\n docsMatched(\"docsmatched\", \"\", \"Number of documents matched\", this),\n docsRanked(\"docsranked\", \"\", \"Number of documents ranked (first phase)\", this),\n docsReRanked(\"docsreranked\", \"\",\n \"Number of documents re-ranked (second phase)\", this),\n active_time(\"activetime\", \"\", \"Time spent doing actual work\", this),\n wait_time(\"waittime\", \"\", \"Time spent waiting for other external threads and resources\", this)\n{\n}\n\nvoid\nLegacyDocumentDBMetrics::MatchingMetrics::RankProfileMetrics::DocIdPartition::update(const MatchingStats::Partition &stats)\n{\n docsMatched.inc(stats.docsMatched());\n docsRanked.inc(stats.docsRanked());\n docsReRanked.inc(stats.docsReRanked());\n active_time.addValueBatch(stats.active_time_avg(), stats.active_time_count());\n wait_time.addValueBatch(stats.wait_time_avg(), stats.wait_time_count());\n}\n\nvoid\nLegacyDocumentDBMetrics::MatchingMetrics::RankProfileMetrics::update(const MatchingStats &stats)\n{\n queries.inc(stats.queries());\n limited_queries.inc(stats.limited_queries());\n matchTime.addValueBatch(stats.matchTimeAvg(), stats.matchTimeCount());\n groupingTime.addValueBatch(stats.groupingTimeAvg(),\n stats.groupingTimeCount());\n rerankTime.addValueBatch(stats.rerankTimeAvg(), stats.rerankTimeCount());\n if (stats.getNumPartitions() > 0) {\n if (stats.getNumPartitions() <= partitions.size()) {\n for (size_t i(0), m(stats.getNumPartitions()); i < m; i++) {\n DocIdPartition & partition(*partitions[i]);\n const MatchingStats::Partition & s(stats.getPartition(i));\n partition.update(s);\n }\n } else {\n vespalib::string msg(make_string(\"Num partitions used '%ld' is larger than number of partitions '%ld' configured.\",\n stats.getNumPartitions(),\n partitions.size()));\n throw vespalib::IllegalStateException(msg, VESPA_STRLOC);\n }\n }\n}\n\nLegacyDocumentDBMetrics::SubDBMetrics::DocumentMetaStoreMetrics::\nDocumentMetaStoreMetrics(MetricSet *parent)\n : MetricSet(\"docmetastore\", \"\", \"Document meta store metrics\", parent),\n lidLimit(\"lidlimit\", \"\", \"The size of the allocated lid space\", this),\n usedLids(\"usedlids\", \"\", \"The number of lids used\", this),\n lowestFreeLid(\"lowestfreelid\", \"\", \"The lowest free lid\", this),\n highestUsedLid(\"highestusedlid\", \"\", \"The highest used lid\", this),\n lidBloatFactor(\"lidbloatfactor\", \"\", \"The bloat factor of this lid space, indicating the total amount of holes in the allocated lid space \"\n \"((lidlimit - usedlids) \/ lidlimit)\", this),\n lidFragmentationFactor(\"lid_fragmentation_factor\", \"\",\n \"The fragmentation factor of this lid space, indicating the amount of holes in the currently used part of the lid space \"\n \"((highestusedlid - usedlids) \/ highestusedlid)\", this)\n{\n}\n\nLegacyDocumentDBMetrics::SubDBMetrics::SubDBMetrics(const vespalib::string &name,\n MetricSet *parent)\n : MetricSet(name, \"\", \"Sub database metrics\", parent),\n attributes(this),\n docMetaStore(this)\n{\n}\n\nLegacyDocumentDBMetrics::LegacyDocumentDBMetrics(const std::string &docTypeName, size_t maxNumThreads)\n : MetricSet(make_string(\"%s\", docTypeName.c_str()), \"\", \"Document DB Metrics\", 0),\n index(this),\n attributes(this),\n docstore(this),\n matching(this),\n executor(\"executor\", this),\n indexExecutor(\"indexexecutor\", this),\n feed(this),\n sessionManager(this),\n ready(\"ready\", this),\n notReady(\"notready\", this),\n removed(\"removed\", this),\n memoryUsage(\"memoryusage\", \"\", \"Memory usage for this Document DB\",\n this),\n numDocs(\"numdocs\", \"\",\n \"Number of ready\/indexed documents in this Document DB (aka number of documents in the 'ready' sub db)\", this),\n numActiveDocs(\"numactivedocs\", \"\",\n \"Number of active\/searchable documents in this Document DB (aka number of active\/searchable documents in the 'ready' sub db)\", this),\n numIndexedDocs(\"numindexeddocs\", \"\",\n \"Number of ready\/indexed documents in this Document DB (aka number of documents in the 'ready' sub db)\", this),\n numStoredDocs(\"numstoreddocs\", \"\",\n \"Total number of documents stored in this Document DB (aka number of documents in the 'ready' and 'notready' sub dbs)\", this),\n numRemovedDocs(\"numremoveddocs\", \"\",\n \"Number of removed documents in this Document DB (aka number of documents in the 'removed' sub db)\", this),\n numBadConfigs(\"numBadConfigs\", \"\",\n \"Number of bad configs for this Document DB\", this),\n _maxNumThreads(maxNumThreads)\n{\n memoryUsage.addMetricToSum(index.memoryUsage);\n memoryUsage.addMetricToSum(attributes.memoryUsage);\n memoryUsage.addMetricToSum(docstore.memoryUsage);\n}\n\n} \/\/ namespace proton\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: CharacterPropertyItemConverter.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: bm $ $Date: 2003-11-25 13:07:19 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2003 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef CHART_CHARACTERPROPERTYITEMCONVERTER_HXX\n#define CHART_CHARACTERPROPERTYITEMCONVERTER_HXX\n\n#include \"ItemConverter.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_\n#include \n#endif\n\n#include \n\nnamespace chart\n{\nnamespace wrapper\n{\n\nclass CharacterPropertyItemConverter :\n public ::comphelper::ItemConverter\n{\npublic:\n CharacterPropertyItemConverter(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > & rPropertySet,\n SfxItemPool& rItemPool,\n ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =\n ::std::auto_ptr< ::com::sun::star::awt::Size >(),\n const ::rtl::OUString & rRefSizePropertyName =\n ::rtl::OUString() );\n virtual ~CharacterPropertyItemConverter();\n\nprotected:\n virtual const USHORT * GetWhichPairs() const;\n virtual bool GetItemPropertyName( USHORT nWhichId, ::rtl::OUString & rOutName ) const;\n\n virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const\n throw( ::com::sun::star::uno::Exception );\n virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet )\n throw( ::com::sun::star::uno::Exception );\n\nprivate:\n ::std::auto_ptr< ::com::sun::star::awt::Size > m_pRefSize;\n ::rtl::OUString m_aRefSizePropertyName;\n};\n\n} \/\/ namespace wrapper\n} \/\/ namespace chart\n\n\/\/ CHART_CHARACTERPROPERTYITEMCONVERTER_HXX\n#endif\nINTEGRATION: CWS ooo19126 (1.5.110); FILE MERGED 2005\/09\/05 18:42:31 rt 1.5.110.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: CharacterPropertyItemConverter.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 00:21:11 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef CHART_CHARACTERPROPERTYITEMCONVERTER_HXX\n#define CHART_CHARACTERPROPERTYITEMCONVERTER_HXX\n\n#include \"ItemConverter.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_\n#include \n#endif\n\n#include \n\nnamespace chart\n{\nnamespace wrapper\n{\n\nclass CharacterPropertyItemConverter :\n public ::comphelper::ItemConverter\n{\npublic:\n CharacterPropertyItemConverter(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > & rPropertySet,\n SfxItemPool& rItemPool,\n ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =\n ::std::auto_ptr< ::com::sun::star::awt::Size >(),\n const ::rtl::OUString & rRefSizePropertyName =\n ::rtl::OUString() );\n virtual ~CharacterPropertyItemConverter();\n\nprotected:\n virtual const USHORT * GetWhichPairs() const;\n virtual bool GetItemPropertyName( USHORT nWhichId, ::rtl::OUString & rOutName ) const;\n\n virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const\n throw( ::com::sun::star::uno::Exception );\n virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet )\n throw( ::com::sun::star::uno::Exception );\n\nprivate:\n ::std::auto_ptr< ::com::sun::star::awt::Size > m_pRefSize;\n ::rtl::OUString m_aRefSizePropertyName;\n};\n\n} \/\/ namespace wrapper\n} \/\/ namespace chart\n\n\/\/ CHART_CHARACTERPROPERTYITEMCONVERTER_HXX\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"app\/l10n_util.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/browser\/views\/bookmark_bar_view.h\"\n#include \"chrome\/browser\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/views\/toolbar_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"views\/accessibility\/view_accessibility_wrapper.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_win.h\"\n#include \"views\/window\/window.h\"\n\nnamespace {\n\nVARIANT id_self = {VT_I4, CHILDID_SELF};\n\n\/\/ Dummy class to force creation of ATL module, needed by COM to instantiate\n\/\/ ViewAccessibility.\nclass TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};\nTestAtlModule test_atl_module_;\n\nclass BrowserViewsAccessibilityTest : public InProcessBrowserTest {\n public:\n BrowserViewsAccessibilityTest() {\n ::CoInitialize(NULL);\n }\n\n ~BrowserViewsAccessibilityTest() {\n ::CoUninitialize();\n }\n\n \/\/ Retrieves an instance of BrowserWindowTesting\n BrowserWindowTesting* GetBrowserWindowTesting() {\n BrowserWindow* browser_window = browser()->window();\n\n if (!browser_window)\n return NULL;\n\n return browser_window->GetBrowserWindowTesting();\n }\n\n \/\/ Retrieve an instance of BrowserView\n BrowserView* GetBrowserView() {\n return BrowserView::GetBrowserViewForNativeWindow(\n browser()->window()->GetNativeHandle());\n }\n\n \/\/ Retrieves and initializes an instance of LocationBarView.\n LocationBarView* GetLocationBarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return GetBrowserWindowTesting()->GetLocationBarView();\n }\n\n \/\/ Retrieves and initializes an instance of ToolbarView.\n ToolbarView* GetToolbarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return browser_window_testing->GetToolbarView();\n }\n\n \/\/ Retrieves and initializes an instance of BookmarkBarView.\n BookmarkBarView* GetBookmarkBarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return browser_window_testing->GetBookmarkBarView();\n }\n\n \/\/ Retrieves and verifies the accessibility object for the given View.\n void TestViewAccessibilityObject(views::View* view, std::wstring name,\n int32 role) {\n ASSERT_TRUE(NULL != view);\n\n IAccessible* acc_obj = NULL;\n HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(\n IID_IAccessible, reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n TestAccessibilityInfo(acc_obj, name, role);\n }\n\n\n \/\/ Verifies MSAA Name and Role properties of the given IAccessible.\n void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,\n int32 role) {\n \/\/ Verify MSAA Name property.\n BSTR acc_name;\n\n HRESULT hr = acc_obj->get_accName(id_self, &acc_name);\n ASSERT_EQ(S_OK, hr);\n EXPECT_STREQ(acc_name, name.c_str());\n\n \/\/ Verify MSAA Role property.\n VARIANT acc_role;\n ::VariantInit(&acc_role);\n\n hr = acc_obj->get_accRole(id_self, &acc_role);\n ASSERT_EQ(S_OK, hr);\n EXPECT_EQ(VT_I4, acc_role.vt);\n EXPECT_EQ(role, acc_role.lVal);\n\n ::VariantClear(&acc_role);\n ::SysFreeString(acc_name);\n }\n};\n\n\/\/ Retrieve accessibility object for main window and verify accessibility info.\n\/\/ Fails, http:\/\/crbug.com\/44486.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n FAILS_TestChromeWindowAccObj) {\n BrowserWindow* browser_window = browser()->window();\n ASSERT_TRUE(NULL != browser_window);\n\n HWND hwnd = browser_window->GetNativeHandle();\n ASSERT_TRUE(NULL != hwnd);\n\n \/\/ Get accessibility object.\n ScopedComPtr acc_obj;\n HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,\n reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));\n std::wstring title =\n l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,\n ASCIIToWide(chrome::kAboutBlankURL));\n TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);\n}\n\n\/\/ Retrieve accessibility object for non client view and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {\n views::View* non_client_view =\n GetBrowserView()->GetWindow()->GetNonClientView();\n\n TestViewAccessibilityObject(non_client_view,\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_WINDOW);\n}\n\n\/\/ Retrieve accessibility object for browser root view and verify\n\/\/ accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestBrowserRootViewAccObj) {\n views::View* browser_root_view =\n GetBrowserView()->frame()->GetFrameView()->GetRootView();\n\n TestViewAccessibilityObject(browser_root_view,\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_APPLICATION);\n}\n\n\/\/ Retrieve accessibility object for browser view and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {\n \/\/ Verify root view MSAA name and role.\n TestViewAccessibilityObject(GetBrowserView(),\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_CLIENT);\n}\n\n\/\/ Retrieve accessibility object for toolbar view and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {\n \/\/ Verify toolbar MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView(),\n l10n_util::GetString(IDS_ACCNAME_TOOLBAR),\n ROLE_SYSTEM_TOOLBAR);\n}\n\n\/\/ Retrieve accessibility object for Back button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {\n \/\/ Verify Back button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);\n}\n\n\/\/ Retrieve accessibility object for Forward button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {\n \/\/ Verify Forward button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);\n}\n\n\/\/ Retrieve accessibility object for Reload button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {\n \/\/ Verify Reload button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Home button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {\n \/\/ Verify Home button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Star button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestStarButtonAccObj) {\n \/\/ Verify Star button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for location bar view and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestLocationBarViewAccObj) {\n \/\/ Verify location bar MSAA name and role.\n TestViewAccessibilityObject(GetLocationBarView(),\n l10n_util::GetString(IDS_ACCNAME_LOCATION),\n ROLE_SYSTEM_GROUPING);\n}\n\n\/\/ Retrieve accessibility object for Go button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {\n \/\/ Verify Go button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_GO),\n ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Page menu button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {\n \/\/ Verify Page menu button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),\n l10n_util::GetString(IDS_ACCNAME_PAGE),\n ROLE_SYSTEM_BUTTONMENU);\n}\n\n\/\/ Retrieve accessibility object for App menu button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {\n \/\/ Verify App menu button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),\n l10n_util::GetString(IDS_ACCNAME_APP),\n ROLE_SYSTEM_BUTTONMENU);\n}\n\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestBookmarkBarViewAccObj) {\n TestViewAccessibilityObject(GetBookmarkBarView(),\n l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),\n ROLE_SYSTEM_TOOLBAR);\n}\n\n\/\/ Fails, http:\/\/crbug.com\/44486.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n FAILS_TestAboutChromeViewAccObj) {\n \/\/ Firstly, test that the WindowDelegate got updated.\n views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();\n EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),\n l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());\n EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),\n AccessibilityTypes::ROLE_DIALOG);\n\n \/\/ Also test the accessibility object directly.\n IAccessible* acc_obj = NULL;\n HRESULT hr =\n ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),\n OBJID_CLIENT,\n IID_IAccessible,\n reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),\n ROLE_SYSTEM_DIALOG);\n\n acc_obj->Release();\n}\n} \/\/ Namespace.\n\nRe-enabling TestAboutChromeViewAccObj.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"app\/l10n_util.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/browser\/views\/bookmark_bar_view.h\"\n#include \"chrome\/browser\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/views\/toolbar_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"views\/accessibility\/view_accessibility_wrapper.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_win.h\"\n#include \"views\/window\/window.h\"\n\nnamespace {\n\nVARIANT id_self = {VT_I4, CHILDID_SELF};\n\n\/\/ Dummy class to force creation of ATL module, needed by COM to instantiate\n\/\/ ViewAccessibility.\nclass TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};\nTestAtlModule test_atl_module_;\n\nclass BrowserViewsAccessibilityTest : public InProcessBrowserTest {\n public:\n BrowserViewsAccessibilityTest() {\n ::CoInitialize(NULL);\n }\n\n ~BrowserViewsAccessibilityTest() {\n ::CoUninitialize();\n }\n\n \/\/ Retrieves an instance of BrowserWindowTesting\n BrowserWindowTesting* GetBrowserWindowTesting() {\n BrowserWindow* browser_window = browser()->window();\n\n if (!browser_window)\n return NULL;\n\n return browser_window->GetBrowserWindowTesting();\n }\n\n \/\/ Retrieve an instance of BrowserView\n BrowserView* GetBrowserView() {\n return BrowserView::GetBrowserViewForNativeWindow(\n browser()->window()->GetNativeHandle());\n }\n\n \/\/ Retrieves and initializes an instance of LocationBarView.\n LocationBarView* GetLocationBarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return GetBrowserWindowTesting()->GetLocationBarView();\n }\n\n \/\/ Retrieves and initializes an instance of ToolbarView.\n ToolbarView* GetToolbarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return browser_window_testing->GetToolbarView();\n }\n\n \/\/ Retrieves and initializes an instance of BookmarkBarView.\n BookmarkBarView* GetBookmarkBarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return browser_window_testing->GetBookmarkBarView();\n }\n\n \/\/ Retrieves and verifies the accessibility object for the given View.\n void TestViewAccessibilityObject(views::View* view, std::wstring name,\n int32 role) {\n ASSERT_TRUE(NULL != view);\n\n IAccessible* acc_obj = NULL;\n HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(\n IID_IAccessible, reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n TestAccessibilityInfo(acc_obj, name, role);\n }\n\n\n \/\/ Verifies MSAA Name and Role properties of the given IAccessible.\n void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,\n int32 role) {\n \/\/ Verify MSAA Name property.\n BSTR acc_name;\n\n HRESULT hr = acc_obj->get_accName(id_self, &acc_name);\n ASSERT_EQ(S_OK, hr);\n EXPECT_STREQ(acc_name, name.c_str());\n\n \/\/ Verify MSAA Role property.\n VARIANT acc_role;\n ::VariantInit(&acc_role);\n\n hr = acc_obj->get_accRole(id_self, &acc_role);\n ASSERT_EQ(S_OK, hr);\n EXPECT_EQ(VT_I4, acc_role.vt);\n EXPECT_EQ(role, acc_role.lVal);\n\n ::VariantClear(&acc_role);\n ::SysFreeString(acc_name);\n }\n};\n\n\/\/ Retrieve accessibility object for main window and verify accessibility info.\n\/\/ Fails, http:\/\/crbug.com\/44486.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n FAILS_TestChromeWindowAccObj) {\n BrowserWindow* browser_window = browser()->window();\n ASSERT_TRUE(NULL != browser_window);\n\n HWND hwnd = browser_window->GetNativeHandle();\n ASSERT_TRUE(NULL != hwnd);\n\n \/\/ Get accessibility object.\n ScopedComPtr acc_obj;\n HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,\n reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));\n std::wstring title =\n l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,\n ASCIIToWide(chrome::kAboutBlankURL));\n TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);\n}\n\n\/\/ Retrieve accessibility object for non client view and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {\n views::View* non_client_view =\n GetBrowserView()->GetWindow()->GetNonClientView();\n\n TestViewAccessibilityObject(non_client_view,\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_WINDOW);\n}\n\n\/\/ Retrieve accessibility object for browser root view and verify\n\/\/ accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestBrowserRootViewAccObj) {\n views::View* browser_root_view =\n GetBrowserView()->frame()->GetFrameView()->GetRootView();\n\n TestViewAccessibilityObject(browser_root_view,\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_APPLICATION);\n}\n\n\/\/ Retrieve accessibility object for browser view and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {\n \/\/ Verify root view MSAA name and role.\n TestViewAccessibilityObject(GetBrowserView(),\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_CLIENT);\n}\n\n\/\/ Retrieve accessibility object for toolbar view and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {\n \/\/ Verify toolbar MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView(),\n l10n_util::GetString(IDS_ACCNAME_TOOLBAR),\n ROLE_SYSTEM_TOOLBAR);\n}\n\n\/\/ Retrieve accessibility object for Back button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {\n \/\/ Verify Back button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);\n}\n\n\/\/ Retrieve accessibility object for Forward button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {\n \/\/ Verify Forward button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);\n}\n\n\/\/ Retrieve accessibility object for Reload button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {\n \/\/ Verify Reload button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Home button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {\n \/\/ Verify Home button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Star button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestStarButtonAccObj) {\n \/\/ Verify Star button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for location bar view and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestLocationBarViewAccObj) {\n \/\/ Verify location bar MSAA name and role.\n TestViewAccessibilityObject(GetLocationBarView(),\n l10n_util::GetString(IDS_ACCNAME_LOCATION),\n ROLE_SYSTEM_GROUPING);\n}\n\n\/\/ Retrieve accessibility object for Go button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {\n \/\/ Verify Go button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_GO),\n ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Page menu button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {\n \/\/ Verify Page menu button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),\n l10n_util::GetString(IDS_ACCNAME_PAGE),\n ROLE_SYSTEM_BUTTONMENU);\n}\n\n\/\/ Retrieve accessibility object for App menu button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {\n \/\/ Verify App menu button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),\n l10n_util::GetString(IDS_ACCNAME_APP),\n ROLE_SYSTEM_BUTTONMENU);\n}\n\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestBookmarkBarViewAccObj) {\n TestViewAccessibilityObject(GetBookmarkBarView(),\n l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),\n ROLE_SYSTEM_TOOLBAR);\n}\n\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestAboutChromeViewAccObj) {\n \/\/ Firstly, test that the WindowDelegate got updated.\n views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();\n EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),\n l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());\n EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),\n AccessibilityTypes::ROLE_DIALOG);\n\n \/\/ Also test the accessibility object directly.\n IAccessible* acc_obj = NULL;\n HRESULT hr =\n ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),\n OBJID_CLIENT,\n IID_IAccessible,\n reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),\n ROLE_SYSTEM_DIALOG);\n\n acc_obj->Release();\n}\n} \/\/ Namespace.\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#include \"core\/Setup.h\"\n\n#if OUZEL_COMPILE_DIRECTSOUND\n\n#include \n#include \n#include \"AudioDeviceDS.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"core\/Window.hpp\"\n#include \"core\/windows\/NativeWindowWin.hpp\"\n#include \"utils\/Log.hpp\"\n#include \"utils\/Utils.hpp\"\n\nBOOL CALLBACK enumCallback(LPGUID, LPCWSTR description, LPCWSTR, LPVOID)\n{\n int bufferSize = WideCharToMultiByte(CP_UTF8, 0, description, -1, nullptr, 0, nullptr, nullptr);\n if (bufferSize != 0)\n {\n std::vector buffer(bufferSize);\n if (WideCharToMultiByte(CP_UTF8, 0, description, -1, buffer.data(), bufferSize, nullptr, nullptr) != 0)\n ouzel::engine->log(ouzel::Log::Level::INFO) << \"Using \" << buffer.data() << \" for audio\";\n }\n return FALSE;\n}\n\nnamespace ouzel\n{\n namespace audio\n {\n class DirectSoundErrorCategory: public std::error_category\n {\n public:\n const char* name() const noexcept override\n {\n return \"DirectSound\";\n }\n\n std::string message(int condition) const override\n {\n switch (condition)\n {\n case DSERR_ACCESSDENIED: return \"DSERR_ACCESSDENIED\";\n case DSERR_ALLOCATED: return \"DSERR_ALLOCATED\";\n case DSERR_ALREADYINITIALIZED: return \"DSERR_ALREADYINITIALIZED\";\n case DSERR_BADFORMAT: return \"DSERR_BADFORMAT\";\n case DSERR_BADSENDBUFFERGUID: return \"DSERR_BADSENDBUFFERGUID\";\n case DSERR_BUFFERLOST: return \"DSERR_BUFFERLOST\";\n case DSERR_BUFFERTOOSMALL: return \"DSERR_BUFFERTOOSMALL\";\n case DSERR_CONTROLUNAVAIL: return \"DSERR_CONTROLUNAVAIL\";\n case DSERR_DS8_REQUIRED: return \"DSERR_DS8_REQUIRED\";\n case DSERR_FXUNAVAILABLE: return \"DSERR_FXUNAVAILABLE\";\n case DSERR_GENERIC: return \"DSERR_GENERIC\";\n case DSERR_INVALIDCALL: return \"DSERR_INVALIDCALL\";\n case DSERR_INVALIDPARAM: return \"DSERR_INVALIDPARAM\";\n case DSERR_NOAGGREGATION: return \"DSERR_NOAGGREGATION\";\n case DSERR_NODRIVER: return \"DSERR_NODRIVER\";\n case DSERR_NOINTERFACE: return \"DSERR_NOINTERFACE\";\n case DSERR_OBJECTNOTFOUND: return \"DSERR_OBJECTNOTFOUND\";\n case DSERR_OTHERAPPHASPRIO: return \"DSERR_OTHERAPPHASPRIO\";\n case DSERR_OUTOFMEMORY: return \"DSERR_OUTOFMEMORY\";\n case DSERR_PRIOLEVELNEEDED: return \"DSERR_PRIOLEVELNEEDED\";\n case DSERR_SENDLOOP: return \"DSERR_SENDLOOP\";\n case DSERR_UNINITIALIZED: return \"DSERR_UNINITIALIZED\";\n case DSERR_UNSUPPORTED: return \"DSERR_UNSUPPORTED\";\n default: return \"Unknown error (\" + std::to_string(condition) + \")\";\n }\n }\n };\n\n const DirectSoundErrorCategory directSoundErrorCategory {};\n\n AudioDeviceDS::AudioDeviceDS(Window* window):\n AudioDevice(Driver::DIRECTSOUND), running(true)\n {\n HRESULT hr;\n if (FAILED(hr = DirectSoundEnumerateW(enumCallback, this)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to enumerate DirectSound 8 devices\");\n\n if (FAILED(hr = DirectSoundCreate8(&DSDEVID_DefaultPlayback, &directSound, nullptr)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to create DirectSound 8 instance\");\n\n NativeWindowWin* windowWin = static_cast(window->getNativeWindow());\n\n if (FAILED(hr = directSound->SetCooperativeLevel(windowWin->getNativeWindow(), DSSCL_PRIORITY)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to set cooperative level for DirectSound 8\");\n\n DSBUFFERDESC primaryBufferDesc;\n primaryBufferDesc.dwSize = sizeof(primaryBufferDesc);\n primaryBufferDesc.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRLVOLUME;\n primaryBufferDesc.dwBufferBytes = 0;\n primaryBufferDesc.dwReserved = 0;\n primaryBufferDesc.lpwfxFormat = nullptr;\n primaryBufferDesc.guid3DAlgorithm = GUID_NULL;\n\n if (FAILED(hr = directSound->CreateSoundBuffer(&primaryBufferDesc, &primaryBuffer, nullptr)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to create DirectSound buffer\");\n\n WAVEFORMATEX waveFormat;\n waveFormat.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;\n waveFormat.nChannels = channels;\n waveFormat.nSamplesPerSec = sampleRate;\n waveFormat.wBitsPerSample = 32;\n waveFormat.nBlockAlign = waveFormat.nChannels * (waveFormat.wBitsPerSample \/ 8);\n waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;\n waveFormat.cbSize = 0;\n\n if (FAILED(hr = primaryBuffer->SetFormat(&waveFormat)))\n {\n waveFormat.wFormatTag = WAVE_FORMAT_PCM;\n waveFormat.wBitsPerSample = 16;\n\n if (FAILED(hr = primaryBuffer->SetFormat(&waveFormat)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to set DirectSound buffer format\");\n\n sampleFormat = SampleFormat::SINT16;\n sampleSize = sizeof(int16_t);\n }\n else\n {\n sampleFormat = SampleFormat::FLOAT32;\n sampleSize = sizeof(float);\n }\n\n IDirectSoundBuffer* tempBuffer = nullptr;\n\n DSBUFFERDESC bufferDesc;\n bufferDesc.dwSize = sizeof(bufferDesc);\n bufferDesc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPOSITIONNOTIFY;\n bufferDesc.dwBufferBytes = 2 * bufferSize;\n bufferDesc.dwReserved = 0;\n bufferDesc.lpwfxFormat = &waveFormat;\n bufferDesc.guid3DAlgorithm = GUID_NULL;\n\n if (FAILED(hr = directSound->CreateSoundBuffer(&bufferDesc, &tempBuffer, nullptr)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to create DirectSound buffer\");\n\n if (FAILED(hr = tempBuffer->QueryInterface(IID_IDirectSoundBuffer8, reinterpret_cast(&buffer))))\n {\n tempBuffer->Release();\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to create DirectSound buffer\");\n }\n\n if (FAILED(hr = tempBuffer->QueryInterface(IID_IDirectSoundNotify, reinterpret_cast(¬ify))))\n {\n tempBuffer->Release();\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to get DirectSound notify interface\");\n }\n\n tempBuffer->Release();\n\n uint8_t* bufferPointer;\n DWORD lockedBufferSize;\n if (FAILED(hr = buffer->Lock(0, bufferDesc.dwBufferBytes, reinterpret_cast(&bufferPointer), &lockedBufferSize, nullptr, 0, 0)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to lock DirectSound buffer\");\n\n getData(lockedBufferSize \/ (channels * sizeof(int16_t)), data);\n std::copy(data.begin(), data.end(), bufferPointer);\n\n if (FAILED(hr = buffer->Unlock(bufferPointer, lockedBufferSize, nullptr, 0)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to unlock DirectSound buffer\");\n\n nextBuffer = 0;\n\n notifyEvents[0] = CreateEvent(nullptr, true, false, nullptr);\n if (!notifyEvents[0])\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to create event\");\n\n notifyEvents[1] = CreateEvent(nullptr, true, false, nullptr);\n if (!notifyEvents[1])\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to create event\");\n\n DSBPOSITIONNOTIFY positionNotifyEvents[2];\n positionNotifyEvents[0].dwOffset = bufferSize - 1;\n positionNotifyEvents[0].hEventNotify = notifyEvents[0];\n\n positionNotifyEvents[1].dwOffset = 2 * bufferSize - 1;\n positionNotifyEvents[1].hEventNotify = notifyEvents[1];\n\n if (FAILED(hr = notify->SetNotificationPositions(2, positionNotifyEvents)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to set DirectSound notification positions\");\n\n if (FAILED(hr = buffer->Play(0, 0, DSBPLAY_LOOPING)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to play DirectSound buffer\");\n\n audioThread = std::thread(&AudioDeviceDS::run, this);\n }\n\n AudioDeviceDS::~AudioDeviceDS()\n {\n running = false;\n for (HANDLE notifyEvent : notifyEvents)\n SetEvent(notifyEvent);\n\n if (audioThread.joinable()) audioThread.join();\n\n for (HANDLE notifyEvent : notifyEvents)\n if (notifyEvent) CloseHandle(notifyEvent);\n\n if (notify) notify->Release();\n if (buffer) buffer->Release();\n if (primaryBuffer) primaryBuffer->Release();\n if (directSound) directSound->Release();\n }\n\n void AudioDeviceDS::run()\n {\n setCurrentThreadName(\"Audio\");\n\n while (running)\n {\n try\n {\n DWORD result;\n if ((result = WaitForSingleObject(notifyEvents[nextBuffer], INFINITE)) == WAIT_FAILED)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to wait for event\");\n\n if (result == WAIT_OBJECT_0)\n {\n if (!running) break;\n\n if (!ResetEvent(notifyEvents[nextBuffer]))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to reset event\");\n\n process();\n\n uint8_t* bufferPointer;\n DWORD lockedBufferSize;\n HRESULT hr;\n if (FAILED(hr = buffer->Lock(nextBuffer * bufferSize, bufferSize, reinterpret_cast(&bufferPointer), &lockedBufferSize, nullptr, 0, 0)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to lock DirectSound buffer\");\n\n getData(lockedBufferSize \/ (sampleSize * channels), data);\n\n std::copy(data.begin(), data.end(), bufferPointer);\n\n if (FAILED(hr = buffer->Unlock(bufferPointer, lockedBufferSize, nullptr, 0)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to unlock DirectSound buffer\");\n\n nextBuffer = (nextBuffer + 1) % 2;\n }\n }\n catch (const std::exception& e)\n {\n engine->log(Log::Level::ERR) << e.what();\n }\n }\n }\n } \/\/ namespace audio\n} \/\/ namespace ouzel\n\n#endif\nReplace audiodefs.h with mmreg.h\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#include \"core\/Setup.h\"\n\n#if OUZEL_COMPILE_DIRECTSOUND\n\n#include \n#include \n#include \"AudioDeviceDS.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"core\/Window.hpp\"\n#include \"core\/windows\/NativeWindowWin.hpp\"\n#include \"utils\/Log.hpp\"\n#include \"utils\/Utils.hpp\"\n\nBOOL CALLBACK enumCallback(LPGUID, LPCWSTR description, LPCWSTR, LPVOID)\n{\n int bufferSize = WideCharToMultiByte(CP_UTF8, 0, description, -1, nullptr, 0, nullptr, nullptr);\n if (bufferSize != 0)\n {\n std::vector buffer(bufferSize);\n if (WideCharToMultiByte(CP_UTF8, 0, description, -1, buffer.data(), bufferSize, nullptr, nullptr) != 0)\n ouzel::engine->log(ouzel::Log::Level::INFO) << \"Using \" << buffer.data() << \" for audio\";\n }\n return FALSE;\n}\n\nnamespace ouzel\n{\n namespace audio\n {\n class DirectSoundErrorCategory: public std::error_category\n {\n public:\n const char* name() const noexcept override\n {\n return \"DirectSound\";\n }\n\n std::string message(int condition) const override\n {\n switch (condition)\n {\n case DSERR_ACCESSDENIED: return \"DSERR_ACCESSDENIED\";\n case DSERR_ALLOCATED: return \"DSERR_ALLOCATED\";\n case DSERR_ALREADYINITIALIZED: return \"DSERR_ALREADYINITIALIZED\";\n case DSERR_BADFORMAT: return \"DSERR_BADFORMAT\";\n case DSERR_BADSENDBUFFERGUID: return \"DSERR_BADSENDBUFFERGUID\";\n case DSERR_BUFFERLOST: return \"DSERR_BUFFERLOST\";\n case DSERR_BUFFERTOOSMALL: return \"DSERR_BUFFERTOOSMALL\";\n case DSERR_CONTROLUNAVAIL: return \"DSERR_CONTROLUNAVAIL\";\n case DSERR_DS8_REQUIRED: return \"DSERR_DS8_REQUIRED\";\n case DSERR_FXUNAVAILABLE: return \"DSERR_FXUNAVAILABLE\";\n case DSERR_GENERIC: return \"DSERR_GENERIC\";\n case DSERR_INVALIDCALL: return \"DSERR_INVALIDCALL\";\n case DSERR_INVALIDPARAM: return \"DSERR_INVALIDPARAM\";\n case DSERR_NOAGGREGATION: return \"DSERR_NOAGGREGATION\";\n case DSERR_NODRIVER: return \"DSERR_NODRIVER\";\n case DSERR_NOINTERFACE: return \"DSERR_NOINTERFACE\";\n case DSERR_OBJECTNOTFOUND: return \"DSERR_OBJECTNOTFOUND\";\n case DSERR_OTHERAPPHASPRIO: return \"DSERR_OTHERAPPHASPRIO\";\n case DSERR_OUTOFMEMORY: return \"DSERR_OUTOFMEMORY\";\n case DSERR_PRIOLEVELNEEDED: return \"DSERR_PRIOLEVELNEEDED\";\n case DSERR_SENDLOOP: return \"DSERR_SENDLOOP\";\n case DSERR_UNINITIALIZED: return \"DSERR_UNINITIALIZED\";\n case DSERR_UNSUPPORTED: return \"DSERR_UNSUPPORTED\";\n default: return \"Unknown error (\" + std::to_string(condition) + \")\";\n }\n }\n };\n\n const DirectSoundErrorCategory directSoundErrorCategory {};\n\n AudioDeviceDS::AudioDeviceDS(Window* window):\n AudioDevice(Driver::DIRECTSOUND), running(true)\n {\n HRESULT hr;\n if (FAILED(hr = DirectSoundEnumerateW(enumCallback, this)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to enumerate DirectSound 8 devices\");\n\n if (FAILED(hr = DirectSoundCreate8(&DSDEVID_DefaultPlayback, &directSound, nullptr)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to create DirectSound 8 instance\");\n\n NativeWindowWin* windowWin = static_cast(window->getNativeWindow());\n\n if (FAILED(hr = directSound->SetCooperativeLevel(windowWin->getNativeWindow(), DSSCL_PRIORITY)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to set cooperative level for DirectSound 8\");\n\n DSBUFFERDESC primaryBufferDesc;\n primaryBufferDesc.dwSize = sizeof(primaryBufferDesc);\n primaryBufferDesc.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRLVOLUME;\n primaryBufferDesc.dwBufferBytes = 0;\n primaryBufferDesc.dwReserved = 0;\n primaryBufferDesc.lpwfxFormat = nullptr;\n primaryBufferDesc.guid3DAlgorithm = GUID_NULL;\n\n if (FAILED(hr = directSound->CreateSoundBuffer(&primaryBufferDesc, &primaryBuffer, nullptr)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to create DirectSound buffer\");\n\n WAVEFORMATEX waveFormat;\n waveFormat.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;\n waveFormat.nChannels = channels;\n waveFormat.nSamplesPerSec = sampleRate;\n waveFormat.wBitsPerSample = 32;\n waveFormat.nBlockAlign = waveFormat.nChannels * (waveFormat.wBitsPerSample \/ 8);\n waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;\n waveFormat.cbSize = 0;\n\n if (FAILED(hr = primaryBuffer->SetFormat(&waveFormat)))\n {\n waveFormat.wFormatTag = WAVE_FORMAT_PCM;\n waveFormat.wBitsPerSample = 16;\n\n if (FAILED(hr = primaryBuffer->SetFormat(&waveFormat)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to set DirectSound buffer format\");\n\n sampleFormat = SampleFormat::SINT16;\n sampleSize = sizeof(int16_t);\n }\n else\n {\n sampleFormat = SampleFormat::FLOAT32;\n sampleSize = sizeof(float);\n }\n\n IDirectSoundBuffer* tempBuffer = nullptr;\n\n DSBUFFERDESC bufferDesc;\n bufferDesc.dwSize = sizeof(bufferDesc);\n bufferDesc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPOSITIONNOTIFY;\n bufferDesc.dwBufferBytes = 2 * bufferSize;\n bufferDesc.dwReserved = 0;\n bufferDesc.lpwfxFormat = &waveFormat;\n bufferDesc.guid3DAlgorithm = GUID_NULL;\n\n if (FAILED(hr = directSound->CreateSoundBuffer(&bufferDesc, &tempBuffer, nullptr)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to create DirectSound buffer\");\n\n if (FAILED(hr = tempBuffer->QueryInterface(IID_IDirectSoundBuffer8, reinterpret_cast(&buffer))))\n {\n tempBuffer->Release();\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to create DirectSound buffer\");\n }\n\n if (FAILED(hr = tempBuffer->QueryInterface(IID_IDirectSoundNotify, reinterpret_cast(¬ify))))\n {\n tempBuffer->Release();\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to get DirectSound notify interface\");\n }\n\n tempBuffer->Release();\n\n uint8_t* bufferPointer;\n DWORD lockedBufferSize;\n if (FAILED(hr = buffer->Lock(0, bufferDesc.dwBufferBytes, reinterpret_cast(&bufferPointer), &lockedBufferSize, nullptr, 0, 0)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to lock DirectSound buffer\");\n\n getData(lockedBufferSize \/ (channels * sizeof(int16_t)), data);\n std::copy(data.begin(), data.end(), bufferPointer);\n\n if (FAILED(hr = buffer->Unlock(bufferPointer, lockedBufferSize, nullptr, 0)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to unlock DirectSound buffer\");\n\n nextBuffer = 0;\n\n notifyEvents[0] = CreateEvent(nullptr, true, false, nullptr);\n if (!notifyEvents[0])\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to create event\");\n\n notifyEvents[1] = CreateEvent(nullptr, true, false, nullptr);\n if (!notifyEvents[1])\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to create event\");\n\n DSBPOSITIONNOTIFY positionNotifyEvents[2];\n positionNotifyEvents[0].dwOffset = bufferSize - 1;\n positionNotifyEvents[0].hEventNotify = notifyEvents[0];\n\n positionNotifyEvents[1].dwOffset = 2 * bufferSize - 1;\n positionNotifyEvents[1].hEventNotify = notifyEvents[1];\n\n if (FAILED(hr = notify->SetNotificationPositions(2, positionNotifyEvents)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to set DirectSound notification positions\");\n\n if (FAILED(hr = buffer->Play(0, 0, DSBPLAY_LOOPING)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to play DirectSound buffer\");\n\n audioThread = std::thread(&AudioDeviceDS::run, this);\n }\n\n AudioDeviceDS::~AudioDeviceDS()\n {\n running = false;\n for (HANDLE notifyEvent : notifyEvents)\n SetEvent(notifyEvent);\n\n if (audioThread.joinable()) audioThread.join();\n\n for (HANDLE notifyEvent : notifyEvents)\n if (notifyEvent) CloseHandle(notifyEvent);\n\n if (notify) notify->Release();\n if (buffer) buffer->Release();\n if (primaryBuffer) primaryBuffer->Release();\n if (directSound) directSound->Release();\n }\n\n void AudioDeviceDS::run()\n {\n setCurrentThreadName(\"Audio\");\n\n while (running)\n {\n try\n {\n DWORD result;\n if ((result = WaitForSingleObject(notifyEvents[nextBuffer], INFINITE)) == WAIT_FAILED)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to wait for event\");\n\n if (result == WAIT_OBJECT_0)\n {\n if (!running) break;\n\n if (!ResetEvent(notifyEvents[nextBuffer]))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to reset event\");\n\n process();\n\n uint8_t* bufferPointer;\n DWORD lockedBufferSize;\n HRESULT hr;\n if (FAILED(hr = buffer->Lock(nextBuffer * bufferSize, bufferSize, reinterpret_cast(&bufferPointer), &lockedBufferSize, nullptr, 0, 0)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to lock DirectSound buffer\");\n\n getData(lockedBufferSize \/ (sampleSize * channels), data);\n\n std::copy(data.begin(), data.end(), bufferPointer);\n\n if (FAILED(hr = buffer->Unlock(bufferPointer, lockedBufferSize, nullptr, 0)))\n throw std::system_error(hr, directSoundErrorCategory, \"Failed to unlock DirectSound buffer\");\n\n nextBuffer = (nextBuffer + 1) % 2;\n }\n }\n catch (const std::exception& e)\n {\n engine->log(Log::Level::ERR) << e.what();\n }\n }\n }\n } \/\/ namespace audio\n} \/\/ namespace ouzel\n\n#endif\n<|endoftext|>"} {"text":"\/*\n ==============================================================================\n\n This file was auto-generated by the Introjucer!\n\n It contains the basic framework code for a JUCE plugin processor.\n\n ==============================================================================\n*\/\n\n#include \"PluginProcessor.h\"\n#include \"PluginEditor.h\"\n\n\/\/==============================================================================\n\n\/\/ Default parameter values\nconst float defaultFilterType = SVFLowpass;\nconst float defaultCutoff = 40.0f;\nconst float defaultResonance = 0.5f;\nconst float defaultShelfGain = 0.0f;\n\n\/\/==============================================================================\nVAStateVariableFilterProcessor::VAStateVariableFilterProcessor()\n{\n addParameter(filterType = new FilterTypeParam{ svfFilter, defaultFilterType, \"Filter Type\" });\n addParameter(cutoff = new CutoffPitchParam{ svfFilter, defaultCutoff, \"Cutoff Pitch\" });\n addParameter(resonance = new ResonanceParam{ svfFilter, defaultResonance, \"Resonance\" });\n addParameter(shelfGain = new ShelfGainParam{ svfFilter, defaultShelfGain, \"Shelf Gain\" });\n\n lastUIWidth = 500;\n lastUIHeight = 200;\n}\n\nVAStateVariableFilterProcessor::~VAStateVariableFilterProcessor()\n{\n}\n\n\/\/==============================================================================\nconst String VAStateVariableFilterProcessor::getInputChannelName (int channelIndex) const\n{\n return String (channelIndex + 1);\n}\n\nconst String VAStateVariableFilterProcessor::getOutputChannelName (int channelIndex) const\n{\n return String (channelIndex + 1);\n}\n\n#if (_MSC_VER) \/\/ Check MSC version\n#pragma warning(push)\n#pragma warning(disable: 4100) \/\/ Disable unreferenced parameter\n#endif\n\nbool VAStateVariableFilterProcessor::isInputChannelStereoPair (int index) const\n{\n return true;\n}\n\nbool VAStateVariableFilterProcessor::isOutputChannelStereoPair (int index) const\n{\n return true;\n}\n\n#if (_MSC_VER) \/\/ Check MSC version\n#pragma warning(pop) \/\/ Re-enable previous disabled warning\n#endif\n\nbool VAStateVariableFilterProcessor::acceptsMidi() const\n{\n #if JucePlugin_WantsMidiInput\n return true;\n #else\n return false;\n #endif\n}\n\nbool VAStateVariableFilterProcessor::producesMidi() const\n{\n #if JucePlugin_ProducesMidiOutput\n return true;\n #else\n return false;\n #endif\n}\n\nbool VAStateVariableFilterProcessor::silenceInProducesSilenceOut() const\n{\n return false;\n}\n\ndouble VAStateVariableFilterProcessor::getTailLengthSeconds() const\n{\n return 0.0;\n}\n\n\/\/==============================================================================\n#if (_MSC_VER) \/\/ Check if Visual Studio\n#pragma warning(push)\n#pragma warning(disable: 4100) \/\/ disable warning\n#endif\n\nvoid VAStateVariableFilterProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)\n{\n \/\/ Use this method as the place to do any pre-playback\n \/\/ initialization that you need..\n svfFilter.setSampleRate(static_cast(sampleRate));\n}\n\nvoid VAStateVariableFilterProcessor::releaseResources()\n{\n}\n\nvoid VAStateVariableFilterProcessor::processBlock(AudioSampleBuffer& buffer, MidiBuffer& midiMessages)\n{\n const int numSamples = buffer.getNumSamples();\n\n \/\/ This is the place where you'd normally do the guts of your plugin's\n \/\/ audio processing...\n for (int channel = 0; channel < getNumInputChannels(); ++channel) {\n\n float* channelData = buffer.getWritePointer(channel);\n\n \/\/ Process audio sample block through filter\n svfFilter.processAudioBlock(channelData, numSamples, channel);\n }\n\n \/\/ In case we have more outputs than inputs, this code clears any output\n \/\/ channels that didn't contain input data, (because these aren't\n \/\/ guaranteed to be empty - they may contain garbage).\n for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)\n buffer.clear(i, 0, buffer.getNumSamples());\n}\n\n#if (_MSC_VER) \/\/ Check if Visual Studio\n#pragma warning(pop) \/\/ Re-enable previous disabled warning\n#endif\n\n\/\/==============================================================================\nAudioProcessorEditor* VAStateVariableFilterProcessor::createEditor()\n{\n return new VAStateVariableFilterProcessorEditor (*this);\n}\n\n\/\/==============================================================================\nvoid VAStateVariableFilterProcessor::getStateInformation (MemoryBlock& destData)\n{\n \/\/ You should use this method to store your parameters in the memory block.\n \/\/ Here's an example of how you can use XML to make it easy and more robust:\n\n \/\/ Create an outer XML element..\n XmlElement xml(\"MYPLUGINSETTINGS\");\n\n \/\/ add some attributes to it..\n xml.setAttribute(\"uiWidth\", lastUIWidth);\n xml.setAttribute(\"uiHeight\", lastUIHeight);\n xml.setAttribute(\"filterType\", filterType->getValue());\n xml.setAttribute(\"cutoff\", cutoff->getValue());\n xml.setAttribute(\"resonance\", resonance->getValue());\n xml.setAttribute(\"shelfGain\", shelfGain->getValue());\n\n \/\/ then use this helper function to stuff it into the binary blob and return it..\n copyXmlToBinary(xml, destData);\n}\n\nvoid VAStateVariableFilterProcessor::setStateInformation (const void* data, int sizeInBytes)\n{\n \/\/ You should use this method to restore your parameters from this memory block,\n \/\/ whose contents will have been created by the getStateInformation() call.\n\n \/\/ This getXmlFromBinary() helper function retrieves our XML from the binary blob..\n ScopedPointer xmlState{ getXmlFromBinary(data, sizeInBytes) };\n\n if (xmlState != nullptr) {\n \/\/ make sure that it's actually our type of XML object..\n if (xmlState->hasTagName(\"MYPLUGINSETTINGS\")) {\n \/\/ ok, now pull out our parameters..\n lastUIWidth = xmlState->getIntAttribute(\"uiWidth\", lastUIWidth);\n lastUIHeight = xmlState->getIntAttribute(\"uiHeight\", lastUIHeight);\n filterType->setValue((float)xmlState->getDoubleAttribute(\"filterType\", filterType->getValue()));\n cutoff->setValue((float)xmlState->getDoubleAttribute(\"cutoff\", cutoff->getValue()));\n resonance->setValue((float)xmlState->getDoubleAttribute(\"resonance\", resonance->getValue()));\n shelfGain->setValue((float)xmlState->getDoubleAttribute(\"shelfGain\", shelfGain->getValue()));\n }\n }\n}\n\n\/\/==============================================================================\n\/\/ This creates new instances of the plugin..\nAudioProcessor* JUCE_CALLTYPE createPluginFilter()\n{\n return new VAStateVariableFilterProcessor();\n}\nErase Visual Studio warning suppressor macros\/*\n ==============================================================================\n\n This file was auto-generated by the Introjucer!\n\n It contains the basic framework code for a JUCE plugin processor.\n\n ==============================================================================\n*\/\n\n#include \"PluginProcessor.h\"\n#include \"PluginEditor.h\"\n\n\/\/==============================================================================\n\n\/\/ Default parameter values\nconst float defaultFilterType = SVFLowpass;\nconst float defaultCutoff = 40.0f;\nconst float defaultResonance = 0.5f;\nconst float defaultShelfGain = 0.0f;\n\n\/\/==============================================================================\nVAStateVariableFilterProcessor::VAStateVariableFilterProcessor()\n{\n addParameter(filterType = new FilterTypeParam{ svfFilter, defaultFilterType, \"Filter Type\" });\n addParameter(cutoff = new CutoffPitchParam{ svfFilter, defaultCutoff, \"Cutoff Pitch\" });\n addParameter(resonance = new ResonanceParam{ svfFilter, defaultResonance, \"Resonance\" });\n addParameter(shelfGain = new ShelfGainParam{ svfFilter, defaultShelfGain, \"Shelf Gain\" });\n\n lastUIWidth = 500;\n lastUIHeight = 200;\n}\n\nVAStateVariableFilterProcessor::~VAStateVariableFilterProcessor()\n{\n}\n\n\/\/==============================================================================\nconst String VAStateVariableFilterProcessor::getInputChannelName (int channelIndex) const\n{\n return String (channelIndex + 1);\n}\n\nconst String VAStateVariableFilterProcessor::getOutputChannelName (int channelIndex) const\n{\n return String (channelIndex + 1);\n}\n\nbool VAStateVariableFilterProcessor::isInputChannelStereoPair (int index) const\n{\n return true;\n}\n\nbool VAStateVariableFilterProcessor::isOutputChannelStereoPair (int index) const\n{\n return true;\n}\n\nbool VAStateVariableFilterProcessor::acceptsMidi() const\n{\n #if JucePlugin_WantsMidiInput\n return true;\n #else\n return false;\n #endif\n}\n\nbool VAStateVariableFilterProcessor::producesMidi() const\n{\n #if JucePlugin_ProducesMidiOutput\n return true;\n #else\n return false;\n #endif\n}\n\nbool VAStateVariableFilterProcessor::silenceInProducesSilenceOut() const\n{\n return false;\n}\n\ndouble VAStateVariableFilterProcessor::getTailLengthSeconds() const\n{\n return 0.0;\n}\n\n\/\/==============================================================================\n\nvoid VAStateVariableFilterProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)\n{\n \/\/ Use this method as the place to do any pre-playback\n \/\/ initialization that you need..\n svfFilter.setSampleRate(static_cast(sampleRate));\n}\n\nvoid VAStateVariableFilterProcessor::releaseResources()\n{\n}\n\nvoid VAStateVariableFilterProcessor::processBlock(AudioSampleBuffer& buffer, MidiBuffer& midiMessages)\n{\n const int numSamples = buffer.getNumSamples();\n\n \/\/ This is the place where you'd normally do the guts of your plugin's\n \/\/ audio processing...\n for (int channel = 0; channel < getNumInputChannels(); ++channel) {\n\n float* channelData = buffer.getWritePointer(channel);\n\n \/\/ Process audio sample block through filter\n svfFilter.processAudioBlock(channelData, numSamples, channel);\n }\n\n \/\/ In case we have more outputs than inputs, this code clears any output\n \/\/ channels that didn't contain input data, (because these aren't\n \/\/ guaranteed to be empty - they may contain garbage).\n for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)\n buffer.clear(i, 0, buffer.getNumSamples());\n}\n\n\/\/==============================================================================\nAudioProcessorEditor* VAStateVariableFilterProcessor::createEditor()\n{\n return new VAStateVariableFilterProcessorEditor (*this);\n}\n\n\/\/==============================================================================\nvoid VAStateVariableFilterProcessor::getStateInformation (MemoryBlock& destData)\n{\n \/\/ You should use this method to store your parameters in the memory block.\n \/\/ Here's an example of how you can use XML to make it easy and more robust:\n\n \/\/ Create an outer XML element..\n XmlElement xml(\"MYPLUGINSETTINGS\");\n\n \/\/ add some attributes to it..\n xml.setAttribute(\"uiWidth\", lastUIWidth);\n xml.setAttribute(\"uiHeight\", lastUIHeight);\n xml.setAttribute(\"filterType\", filterType->getValue());\n xml.setAttribute(\"cutoff\", cutoff->getValue());\n xml.setAttribute(\"resonance\", resonance->getValue());\n xml.setAttribute(\"shelfGain\", shelfGain->getValue());\n\n \/\/ then use this helper function to stuff it into the binary blob and return it..\n copyXmlToBinary(xml, destData);\n}\n\nvoid VAStateVariableFilterProcessor::setStateInformation (const void* data, int sizeInBytes)\n{\n \/\/ You should use this method to restore your parameters from this memory block,\n \/\/ whose contents will have been created by the getStateInformation() call.\n\n \/\/ This getXmlFromBinary() helper function retrieves our XML from the binary blob..\n ScopedPointer xmlState{ getXmlFromBinary(data, sizeInBytes) };\n\n if (xmlState != nullptr) {\n \/\/ make sure that it's actually our type of XML object..\n if (xmlState->hasTagName(\"MYPLUGINSETTINGS\")) {\n \/\/ ok, now pull out our parameters..\n lastUIWidth = xmlState->getIntAttribute(\"uiWidth\", lastUIWidth);\n lastUIHeight = xmlState->getIntAttribute(\"uiHeight\", lastUIHeight);\n filterType->setValue((float)xmlState->getDoubleAttribute(\"filterType\", filterType->getValue()));\n cutoff->setValue((float)xmlState->getDoubleAttribute(\"cutoff\", cutoff->getValue()));\n resonance->setValue((float)xmlState->getDoubleAttribute(\"resonance\", resonance->getValue()));\n shelfGain->setValue((float)xmlState->getDoubleAttribute(\"shelfGain\", shelfGain->getValue()));\n }\n }\n}\n\n\/\/==============================================================================\n\/\/ This creates new instances of the plugin..\nAudioProcessor* JUCE_CALLTYPE createPluginFilter()\n{\n return new VAStateVariableFilterProcessor();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/renderer\/extensions\/extension_resource_request_policy.h\"\n\n#include \"base\/logging.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/extensions\/extension_set.h\"\n#include \"googleurl\/src\/gurl.h\"\n\n\/\/ static\nbool ExtensionResourceRequestPolicy::CanRequestResource(\n const GURL& resource_url,\n const GURL& frame_url,\n const ExtensionSet* loaded_extensions) {\n CHECK(resource_url.SchemeIs(chrome::kExtensionScheme));\n\n const Extension* extension = loaded_extensions->GetByURL(resource_url);\n if (!extension) {\n \/\/ Allow the load in the case of a non-existent extension. We'll just get a\n \/\/ 404 from the browser process.\n return true;\n }\n\n \/\/ Disallow loading of packaged resources for hosted apps. We don't allow\n \/\/ hybrid hosted\/packaged apps. The one exception is access to icons, since\n \/\/ some extensions want to be able to do things like create their own\n \/\/ launchers.\n std::string resource_root_relative_path =\n resource_url.path().empty() ? \"\" : resource_url.path().substr(1);\n if (extension && extension->is_hosted_app() &&\n !extension->icons().ContainsPath(resource_root_relative_path)) {\n LOG(ERROR) << \"Denying load of \" << resource_url.spec() << \" from \"\n << \"hosted app.\";\n return false;\n }\n\n return true;\n}\n\nExtensionResourceRequestPolicy::ExtensionResourceRequestPolicy() {\n}\nCoverity: Remove an unneeded check.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/renderer\/extensions\/extension_resource_request_policy.h\"\n\n#include \"base\/logging.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/extensions\/extension_set.h\"\n#include \"googleurl\/src\/gurl.h\"\n\n\/\/ static\nbool ExtensionResourceRequestPolicy::CanRequestResource(\n const GURL& resource_url,\n const GURL& frame_url,\n const ExtensionSet* loaded_extensions) {\n CHECK(resource_url.SchemeIs(chrome::kExtensionScheme));\n\n const Extension* extension = loaded_extensions->GetByURL(resource_url);\n if (!extension) {\n \/\/ Allow the load in the case of a non-existent extension. We'll just get a\n \/\/ 404 from the browser process.\n return true;\n }\n\n \/\/ Disallow loading of packaged resources for hosted apps. We don't allow\n \/\/ hybrid hosted\/packaged apps. The one exception is access to icons, since\n \/\/ some extensions want to be able to do things like create their own\n \/\/ launchers.\n std::string resource_root_relative_path =\n resource_url.path().empty() ? \"\" : resource_url.path().substr(1);\n if (extension->is_hosted_app() &&\n !extension->icons().ContainsPath(resource_root_relative_path)) {\n LOG(ERROR) << \"Denying load of \" << resource_url.spec() << \" from \"\n << \"hosted app.\";\n return false;\n }\n\n return true;\n}\n\nExtensionResourceRequestPolicy::ExtensionResourceRequestPolicy() {\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"core\/Setup.h\"\n\n#if OUZEL_COMPILE_OPENAL\n\n#include \"AudioDeviceAL.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"utils\/Log.hpp\"\n\nnamespace ouzel\n{\n namespace audio\n {\n bool AudioDeviceAL::checkALCError(bool logError)\n {\n ALCenum error = alcGetError(device);\n\n if (error != ALC_NO_ERROR)\n {\n if (logError)\n {\n const char* errorStr = \"Unknown error\";\n\n switch (error)\n {\n case ALC_INVALID_DEVICE: errorStr = \"ALC_INVALID_DEVICE\"; break;\n case ALC_INVALID_CONTEXT: errorStr = \"ALC_INVALID_CONTEXT\"; break;\n case ALC_INVALID_ENUM: errorStr = \"ALC_INVALID_ENUM\"; break;\n case ALC_INVALID_VALUE: errorStr = \"ALC_INVALID_VALUE\"; break;\n case ALC_OUT_OF_MEMORY: errorStr = \"ALC_OUT_OF_MEMORY\"; break;\n }\n\n Log(Log::Level::ERR) << \"OpenAL error: \" << errorStr << \"(\" << error << \")\";\n }\n\n return true;\n }\n\n return false;\n }\n\n bool AudioDeviceAL::checkOpenALError(bool logError)\n {\n ALenum error = alGetError();\n\n if (error != AL_NO_ERROR)\n {\n if (logError)\n {\n const char* errorStr;\n\n switch (error)\n {\n case AL_INVALID_NAME: errorStr = \"AL_INVALID_NAME\"; break;\n case AL_INVALID_ENUM: errorStr = \"AL_INVALID_ENUM\"; break;\n case AL_INVALID_VALUE: errorStr = \"AL_INVALID_VALUE\"; break;\n case AL_INVALID_OPERATION: errorStr = \"AL_INVALID_OPERATION\"; break;\n case AL_OUT_OF_MEMORY: errorStr = \"AL_OUT_OF_MEMORY\"; break;\n default: errorStr = \"Unknown error\"; break;\n }\n\n Log(Log::Level::ERR) << \"OpenAL error: \" << errorStr << \" (\" << error << \")\";\n }\n\n return true;\n }\n\n return false;\n }\n\n AudioDeviceAL::AudioDeviceAL():\n AudioDevice(Audio::Driver::OPENAL)\n {\n#if OUZEL_MULTITHREADED\n running = false;\n#endif\n\n std::fill(std::begin(buffers), std::end(buffers), 0);\n }\n\n AudioDeviceAL::~AudioDeviceAL()\n {\n#if OUZEL_MULTITHREADED\n running = false;\n if (audioThread.joinable()) audioThread.join();\n#endif\n\n if (sourceId)\n {\n alSourceStop(sourceId);\n alSourcei(sourceId, AL_BUFFER, 0);\n alDeleteSources(1, &sourceId);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to delete OpenAL source\";\n }\n }\n\n for (ALuint buffer : buffers)\n {\n if (buffer)\n {\n alDeleteBuffers(1, &buffer);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to delete OpenAL buffer\";\n }\n }\n }\n\n if (context)\n {\n alcMakeContextCurrent(nullptr);\n alcDestroyContext(context);\n }\n\n if (device)\n {\n alcCloseDevice(device);\n }\n }\n\n bool AudioDeviceAL::init(bool debugAudio)\n {\n if (!AudioDevice::init(debugAudio))\n {\n return false;\n }\n\n const ALCchar* deviceName = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER);\n\n if (deviceName)\n {\n Log(Log::Level::INFO) << \"Using \" << deviceName << \" for audio\";\n }\n\n device = alcOpenDevice(deviceName);\n\n if (!device || checkALCError())\n {\n Log(Log::Level::ERR) << \"Failed to create OpenAL device\";\n return false;\n }\n\n int capabilities[] =\n {\n ALC_FREQUENCY, 44100,\n ALC_STEREO_SOURCES, 4,\n 0, 0\n };\n\n context = alcCreateContext(device, capabilities);\n\n if (checkALCError())\n {\n Log(Log::Level::ERR) << \"Failed to create OpenAL context\";\n return false;\n }\n\n alcMakeContextCurrent(context);\n\n if (checkALCError())\n {\n Log(Log::Level::ERR) << \"Failed to make OpenAL context current\";\n return false;\n }\n\n format40 = alGetEnumValue(\"AL_FORMAT_QUAD16\");\n format51 = alGetEnumValue(\"AL_FORMAT_51CHN16\");\n format61 = alGetEnumValue(\"AL_FORMAT_61CHN16\");\n format71 = alGetEnumValue(\"AL_FORMAT_71CHN16\");\n\n if (checkOpenALError())\n {\n Log(Log::Level::WARN) << \"Failed to get OpenAL enum values\";\n }\n\n alGenSources(1, &sourceId);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to create OpenAL source\";\n return false;\n }\n\n alGenBuffers(2, buffers);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to create OpenAL buffers\";\n return false;\n }\n\n switch (channels)\n {\n case 1: sampleFormat = AL_FORMAT_MONO16; break;\n case 2: sampleFormat = AL_FORMAT_STEREO16; break;\n case 4: sampleFormat = format40; break;\n case 6: sampleFormat = format51; break;\n case 7: sampleFormat = format61; break;\n case 8: sampleFormat = format71; break;\n default:\n {\n Log(Log::Level::ERR) << \"Invalid channel count\";\n return false;\n }\n }\n\n format = Audio::Format::SINT16;\n\n getData(bufferSize \/ (channels * sizeof(int16_t)), data);\n\n alBufferData(buffers[0], sampleFormat,\n data.data(),\n static_cast(data.size()),\n static_cast(sampleRate));\n\n getData(bufferSize \/ (channels * sizeof(int16_t)), data);\n\n alBufferData(buffers[1], sampleFormat,\n data.data(),\n static_cast(data.size()),\n static_cast(sampleRate));\n\n nextBuffer = 0;\n\n alSourceQueueBuffers(sourceId, 2, buffers);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to queue OpenAL buffers\";\n return false;\n }\n\n alSourcePlay(sourceId);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to play OpenAL source\";\n return false;\n }\n\n#if OUZEL_MULTITHREADED\n running = true;\n audioThread = std::thread(&AudioDeviceAL::run, this);\n#endif\n\n return true;\n }\n\n bool AudioDeviceAL::process()\n {\n if (!AudioDevice::process())\n {\n return false;\n }\n\n alcMakeContextCurrent(context);\n\n if (checkALCError())\n {\n Log(Log::Level::ERR) << \"Failed to make OpenAL context current\";\n return false;\n }\n\n ALint buffersProcessed;\n alGetSourcei(sourceId, AL_BUFFERS_PROCESSED, &buffersProcessed);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to get processed buffer count\";\n return false;\n }\n\n \/\/ requeue all processed buffers\n for (; buffersProcessed > 0; --buffersProcessed)\n {\n alSourceUnqueueBuffers(sourceId, 1, &buffers[nextBuffer]);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to unqueue OpenAL buffer\";\n return false;\n }\n\n if (!getData(bufferSize \/ (channels * sizeof(int16_t)), data))\n {\n return false;\n }\n\n alBufferData(buffers[nextBuffer], sampleFormat,\n data.data(),\n static_cast(data.size()),\n static_cast(sampleRate));\n\n alSourceQueueBuffers(sourceId, 1, &buffers[nextBuffer]);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to queue OpenAL buffer\";\n return false;\n }\n\n ALint state;\n alGetSourcei(sourceId, AL_SOURCE_STATE, &state);\n if (state != AL_PLAYING)\n {\n alSourcePlay(sourceId);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to play OpenAL source\";\n return false;\n }\n }\n\n \/\/ swap the buffer\n nextBuffer = (nextBuffer + 1) % 2;\n }\n\n return true;\n }\n\n void AudioDeviceAL::run()\n {\n#if OUZEL_MULTITHREADED\n sharedEngine->setCurrentThreadName(\"Audio\");\n\n while (running)\n {\n if (!process())\n {\n break;\n }\n }\n#endif\n }\n } \/\/ namespace audio\n} \/\/ namespace ouzel\n\n#endif\nDon't request OpenAL enum values on Emscripten\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"core\/Setup.h\"\n\n#if OUZEL_COMPILE_OPENAL\n\n#include \"AudioDeviceAL.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"utils\/Log.hpp\"\n\nnamespace ouzel\n{\n namespace audio\n {\n bool AudioDeviceAL::checkALCError(bool logError)\n {\n ALCenum error = alcGetError(device);\n\n if (error != ALC_NO_ERROR)\n {\n if (logError)\n {\n const char* errorStr = \"Unknown error\";\n\n switch (error)\n {\n case ALC_INVALID_DEVICE: errorStr = \"ALC_INVALID_DEVICE\"; break;\n case ALC_INVALID_CONTEXT: errorStr = \"ALC_INVALID_CONTEXT\"; break;\n case ALC_INVALID_ENUM: errorStr = \"ALC_INVALID_ENUM\"; break;\n case ALC_INVALID_VALUE: errorStr = \"ALC_INVALID_VALUE\"; break;\n case ALC_OUT_OF_MEMORY: errorStr = \"ALC_OUT_OF_MEMORY\"; break;\n }\n\n Log(Log::Level::ERR) << \"OpenAL error: \" << errorStr << \"(\" << error << \")\";\n }\n\n return true;\n }\n\n return false;\n }\n\n bool AudioDeviceAL::checkOpenALError(bool logError)\n {\n ALenum error = alGetError();\n\n if (error != AL_NO_ERROR)\n {\n if (logError)\n {\n const char* errorStr;\n\n switch (error)\n {\n case AL_INVALID_NAME: errorStr = \"AL_INVALID_NAME\"; break;\n case AL_INVALID_ENUM: errorStr = \"AL_INVALID_ENUM\"; break;\n case AL_INVALID_VALUE: errorStr = \"AL_INVALID_VALUE\"; break;\n case AL_INVALID_OPERATION: errorStr = \"AL_INVALID_OPERATION\"; break;\n case AL_OUT_OF_MEMORY: errorStr = \"AL_OUT_OF_MEMORY\"; break;\n default: errorStr = \"Unknown error\"; break;\n }\n\n Log(Log::Level::ERR) << \"OpenAL error: \" << errorStr << \" (\" << error << \")\";\n }\n\n return true;\n }\n\n return false;\n }\n\n AudioDeviceAL::AudioDeviceAL():\n AudioDevice(Audio::Driver::OPENAL)\n {\n#if OUZEL_MULTITHREADED\n running = false;\n#endif\n\n std::fill(std::begin(buffers), std::end(buffers), 0);\n }\n\n AudioDeviceAL::~AudioDeviceAL()\n {\n#if OUZEL_MULTITHREADED\n running = false;\n if (audioThread.joinable()) audioThread.join();\n#endif\n\n if (sourceId)\n {\n alSourceStop(sourceId);\n alSourcei(sourceId, AL_BUFFER, 0);\n alDeleteSources(1, &sourceId);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to delete OpenAL source\";\n }\n }\n\n for (ALuint buffer : buffers)\n {\n if (buffer)\n {\n alDeleteBuffers(1, &buffer);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to delete OpenAL buffer\";\n }\n }\n }\n\n if (context)\n {\n alcMakeContextCurrent(nullptr);\n alcDestroyContext(context);\n }\n\n if (device)\n {\n alcCloseDevice(device);\n }\n }\n\n bool AudioDeviceAL::init(bool debugAudio)\n {\n if (!AudioDevice::init(debugAudio))\n {\n return false;\n }\n\n const ALCchar* deviceName = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER);\n\n if (deviceName)\n {\n Log(Log::Level::INFO) << \"Using \" << deviceName << \" for audio\";\n }\n\n device = alcOpenDevice(deviceName);\n\n if (!device || checkALCError())\n {\n Log(Log::Level::ERR) << \"Failed to create OpenAL device\";\n return false;\n }\n\n int capabilities[] =\n {\n ALC_FREQUENCY, 44100,\n ALC_STEREO_SOURCES, 4,\n 0, 0\n };\n\n context = alcCreateContext(device, capabilities);\n\n if (checkALCError())\n {\n Log(Log::Level::ERR) << \"Failed to create OpenAL context\";\n return false;\n }\n\n alcMakeContextCurrent(context);\n\n if (checkALCError())\n {\n Log(Log::Level::ERR) << \"Failed to make OpenAL context current\";\n return false;\n }\n\n#if !OUZEL_PLATFORM_EMSCRIPTEN\n format40 = alGetEnumValue(\"AL_FORMAT_QUAD16\");\n format51 = alGetEnumValue(\"AL_FORMAT_51CHN16\");\n format61 = alGetEnumValue(\"AL_FORMAT_61CHN16\");\n format71 = alGetEnumValue(\"AL_FORMAT_71CHN16\");\n#endif\n\n if (checkOpenALError())\n {\n Log(Log::Level::WARN) << \"Failed to get OpenAL enum values\";\n }\n\n alGenSources(1, &sourceId);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to create OpenAL source\";\n return false;\n }\n\n alGenBuffers(2, buffers);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to create OpenAL buffers\";\n return false;\n }\n\n switch (channels)\n {\n case 1: sampleFormat = AL_FORMAT_MONO16; break;\n case 2: sampleFormat = AL_FORMAT_STEREO16; break;\n case 4: sampleFormat = format40; break;\n case 6: sampleFormat = format51; break;\n case 7: sampleFormat = format61; break;\n case 8: sampleFormat = format71; break;\n default:\n {\n Log(Log::Level::ERR) << \"Invalid channel count\";\n return false;\n }\n }\n\n format = Audio::Format::SINT16;\n\n getData(bufferSize \/ (channels * sizeof(int16_t)), data);\n\n alBufferData(buffers[0], sampleFormat,\n data.data(),\n static_cast(data.size()),\n static_cast(sampleRate));\n\n getData(bufferSize \/ (channels * sizeof(int16_t)), data);\n\n alBufferData(buffers[1], sampleFormat,\n data.data(),\n static_cast(data.size()),\n static_cast(sampleRate));\n\n nextBuffer = 0;\n\n alSourceQueueBuffers(sourceId, 2, buffers);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to queue OpenAL buffers\";\n return false;\n }\n\n alSourcePlay(sourceId);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to play OpenAL source\";\n return false;\n }\n\n#if OUZEL_MULTITHREADED\n running = true;\n audioThread = std::thread(&AudioDeviceAL::run, this);\n#endif\n\n return true;\n }\n\n bool AudioDeviceAL::process()\n {\n if (!AudioDevice::process())\n {\n return false;\n }\n\n alcMakeContextCurrent(context);\n\n if (checkALCError())\n {\n Log(Log::Level::ERR) << \"Failed to make OpenAL context current\";\n return false;\n }\n\n ALint buffersProcessed;\n alGetSourcei(sourceId, AL_BUFFERS_PROCESSED, &buffersProcessed);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to get processed buffer count\";\n return false;\n }\n\n \/\/ requeue all processed buffers\n for (; buffersProcessed > 0; --buffersProcessed)\n {\n alSourceUnqueueBuffers(sourceId, 1, &buffers[nextBuffer]);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to unqueue OpenAL buffer\";\n return false;\n }\n\n if (!getData(bufferSize \/ (channels * sizeof(int16_t)), data))\n {\n return false;\n }\n\n alBufferData(buffers[nextBuffer], sampleFormat,\n data.data(),\n static_cast(data.size()),\n static_cast(sampleRate));\n\n alSourceQueueBuffers(sourceId, 1, &buffers[nextBuffer]);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to queue OpenAL buffer\";\n return false;\n }\n\n ALint state;\n alGetSourcei(sourceId, AL_SOURCE_STATE, &state);\n if (state != AL_PLAYING)\n {\n alSourcePlay(sourceId);\n\n if (checkOpenALError())\n {\n Log(Log::Level::ERR) << \"Failed to play OpenAL source\";\n return false;\n }\n }\n\n \/\/ swap the buffer\n nextBuffer = (nextBuffer + 1) % 2;\n }\n\n return true;\n }\n\n void AudioDeviceAL::run()\n {\n#if OUZEL_MULTITHREADED\n sharedEngine->setCurrentThreadName(\"Audio\");\n\n while (running)\n {\n if (!process())\n {\n break;\n }\n }\n#endif\n }\n } \/\/ namespace audio\n} \/\/ namespace ouzel\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include \n#include \n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nvoid bind_session_settings()\n{\n class_(\"session_settings\")\n .def_readwrite(\"user_agent\", &session_settings::user_agent)\n .def_readwrite(\"tracker_completion_timeout\", &session_settings::tracker_completion_timeout)\n .def_readwrite(\"tracker_receive_timeout\", &session_settings::tracker_receive_timeout)\n .def_readwrite(\"tracker_maximum_response_length\", &session_settings::tracker_maximum_response_length)\n .def_readwrite(\"piece_timeout\", &session_settings::piece_timeout)\n .def_readwrite(\"request_queue_time\", &session_settings::request_queue_time)\n .def_readwrite(\"max_allowed_in_request_queue\", &session_settings::max_allowed_in_request_queue)\n .def_readwrite(\"max_out_request_queue\", &session_settings::max_out_request_queue)\n .def_readwrite(\"whole_pieces_threshold\", &session_settings::whole_pieces_threshold)\n .def_readwrite(\"peer_timeout\", &session_settings::peer_timeout)\n .def_readwrite(\"urlseed_timeout\", &session_settings::urlseed_timeout)\n .def_readwrite(\"urlseed_pipeline_size\", &session_settings::urlseed_pipeline_size)\n .def_readwrite(\"file_pool_size\", &session_settings::file_pool_size)\n .def_readwrite(\"allow_multiple_connections_per_ip\", &session_settings::allow_multiple_connections_per_ip)\n .def_readwrite(\"max_failcount\", &session_settings::max_failcount)\n .def_readwrite(\"min_reconnect_time\", &session_settings::min_reconnect_time)\n .def_readwrite(\"peer_connect_timeout\", &session_settings::peer_connect_timeout)\n .def_readwrite(\"ignore_limits_on_local_network\", &session_settings::ignore_limits_on_local_network)\n .def_readwrite(\"connection_speed\", &session_settings::connection_speed)\n .def_readwrite(\"send_redundant_have\", &session_settings::send_redundant_have)\n .def_readwrite(\"lazy_bitfields\", &session_settings::lazy_bitfields)\n .def_readwrite(\"inactivity_timeout\", &session_settings::inactivity_timeout)\n .def_readwrite(\"unchoke_interval\", &session_settings::unchoke_interval)\n .def_readwrite(\"active_downloads\", &session_settings::active_downloads)\n .def_readwrite(\"active_seeds\", &session_settings::active_seeds)\n .def_readwrite(\"active_limit\", &session_settings::active_limit)\n .def_readwrite(\"auto_manage_prefer_seeds\", &session_settings::auto_manage_prefer_seeds)\n .def_readwrite(\"dont_count_slow_torrents\", &session_settings::dont_count_slow_torrents)\n .def_readwrite(\"auto_manage_interval\", &session_settings::auto_manage_interval)\n .def_readwrite(\"share_ratio_limit\", &session_settings::share_ratio_limit)\n .def_readwrite(\"seed_time_ratio_limit\", &session_settings::seed_time_ratio_limit)\n .def_readwrite(\"seed_time_limit\", &session_settings::seed_time_limit)\n .def_readwrite(\"auto_scraped_interval\", &session_settings::auto_scrape_interval)\n .def_readwrite(\"peer_tos\", &session_settings::peer_tos)\n .def_readwrite(\"rate_limit_ip_overhead\", &session_settings::rate_limit_ip_overhead)\n .def_readwrite(\"outgoing_ports\", &session_settings::outgoing_ports)\n .def_readwrite(\"cache_size\", &session_settings::cache_size)\n .def_readwrite(\"cache_expiry\", &session_settings::cache_expiry)\n#ifndef TORRENT_DISABLE_DHT\n .def_readwrite(\"use_dht_as_fallback\", &session_settings::use_dht_as_fallback)\n#endif\n ;\n\n enum_(\"proxy_type\")\n .value(\"none\", proxy_settings::none)\n .value(\"socks4\", proxy_settings::socks4)\n .value(\"socks5\", proxy_settings::socks5)\n .value(\"socks5_pw\", proxy_settings::socks5_pw)\n .value(\"http\", proxy_settings::http)\n .value(\"http_pw\", proxy_settings::http_pw)\n ;\n class_(\"proxy_settings\")\n .def_readwrite(\"hostname\", &proxy_settings::hostname)\n .def_readwrite(\"port\", &proxy_settings::port)\n .def_readwrite(\"password\", &proxy_settings::password)\n .def_readwrite(\"username\", &proxy_settings::username)\n .def_readwrite(\"type\", &proxy_settings::type)\n ;\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n enum_(\"enc_policy\")\n .value(\"forced\", pe_settings::forced)\n .value(\"enabled\", pe_settings::enabled)\n .value(\"disabled\", pe_settings::disabled)\n ;\n\n enum_(\"enc_level\")\n .value(\"rc4\", pe_settings::rc4)\n .value(\"plaintext\", pe_settings::plaintext)\n .value(\"both\", pe_settings::both)\n ;\n\n class_(\"pe_settings\")\n .def_readwrite(\"out_enc_policy\", &pe_settings::out_enc_policy)\n .def_readwrite(\"in_enc_policy\", &pe_settings::in_enc_policy)\n .def_readwrite(\"allowed_enc_level\", &pe_settings::allowed_enc_level)\n .def_readwrite(\"prefer_rc4\", &pe_settings::prefer_rc4)\n ;\n#endif\n\n}\nUpdate python bindings session_settings\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include \n#include \n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nvoid bind_session_settings()\n{\n class_(\"session_settings\")\n .def_readwrite(\"user_agent\", &session_settings::user_agent)\n .def_readwrite(\"tracker_completion_timeout\", &session_settings::tracker_completion_timeout)\n .def_readwrite(\"tracker_receive_timeout\", &session_settings::tracker_receive_timeout)\n .def_readwrite(\"stop_tracker_timeout\", &session_settings::stop_tracker_timeout)\n .def_readwrite(\"tracker_maximum_response_length\", &session_settings::tracker_maximum_response_length)\n .def_readwrite(\"piece_timeout\", &session_settings::piece_timeout)\n .def_readwrite(\"request_timeout\", &session_settings::request_timeout)\n .def_readwrite(\"request_queue_time\", &session_settings::request_queue_time)\n .def_readwrite(\"max_allowed_in_request_queue\", &session_settings::max_allowed_in_request_queue)\n .def_readwrite(\"max_out_request_queue\", &session_settings::max_out_request_queue)\n .def_readwrite(\"whole_pieces_threshold\", &session_settings::whole_pieces_threshold)\n .def_readwrite(\"peer_timeout\", &session_settings::peer_timeout)\n .def_readwrite(\"urlseed_timeout\", &session_settings::urlseed_timeout)\n .def_readwrite(\"urlseed_pipeline_size\", &session_settings::urlseed_pipeline_size)\n .def_readwrite(\"urlseed_wait_retry\", &session_settings::urlseed_wait_retry)\n .def_readwrite(\"file_pool_size\", &session_settings::file_pool_size)\n .def_readwrite(\"allow_multiple_connections_per_ip\", &session_settings::allow_multiple_connections_per_ip)\n .def_readwrite(\"max_failcount\", &session_settings::max_failcount)\n .def_readwrite(\"min_reconnect_time\", &session_settings::min_reconnect_time)\n .def_readwrite(\"peer_connect_timeout\", &session_settings::peer_connect_timeout)\n .def_readwrite(\"ignore_limits_on_local_network\", &session_settings::ignore_limits_on_local_network)\n .def_readwrite(\"connection_speed\", &session_settings::connection_speed)\n .def_readwrite(\"send_redundant_have\", &session_settings::send_redundant_have)\n .def_readwrite(\"lazy_bitfields\", &session_settings::lazy_bitfields)\n .def_readwrite(\"inactivity_timeout\", &session_settings::inactivity_timeout)\n .def_readwrite(\"unchoke_interval\", &session_settings::unchoke_interval)\n .def_readwrite(\"optimistic_unchoke_multiplier\", &session_settings::optimistic_unchoke_multiplier)\n .def_readwrite(\"num_want\", &session_settings::num_want)\n .def_readwrite(\"initial_picker_threshold\", &session_settings::initial_picker_threshold)\n .def_readwrite(\"allowed_fast_set_size\", &session_settings::allowed_fast_set_size)\n .def_readwrite(\"max_outstanding_disk_bytes_per_connection\", &session_settings::max_outstanding_disk_bytes_per_connection)\n .def_readwrite(\"handshake_timeout\", &session_settings::handshake_timeout)\n#ifndef TORRENT_DISABLE_DHT\n .def_readwrite(\"use_dht_as_fallback\", &session_settings::use_dht_as_fallback)\n#endif\n .def_readwrite(\"free_torrent_hashes\", &session_settings::free_torrent_hashes)\n .def_readwrite(\"upnp_ignore_nonrouters\", &session_settings::upnp_ignore_nonrouters)\n .def_readwrite(\"send_buffer_watermark\", &session_settings::send_buffer_watermark)\n .def_readwrite(\"auto_upload_slots\", &session_settings::auto_upload_slots)\n .def_readwrite(\"auto_upload_slots_rate_based\", &session_settings::auto_upload_slots_rate_based)\n .def_readwrite(\"use_parole_mode\", &session_settings::use_parole_mode)\n .def_readwrite(\"cache_size\", &session_settings::cache_size)\n .def_readwrite(\"cache_buffer_chunk_size\", &session_settings::cache_buffer_chunk_size)\n .def_readwrite(\"cache_expiry\", &session_settings::cache_expiry)\n .def_readwrite(\"use_read_cache\", &session_settings::use_read_cache)\n .def_readwrite(\"disk_io_write_mode\", &session_settings::disk_io_write_mode)\n .def_readwrite(\"disk_io_read_mode\", &session_settings::disk_io_read_mode)\n .def_readwrite(\"coalesce_reads\", &session_settings::coalesce_reads)\n .def_readwrite(\"coalesce_writes\", &session_settings:coalesce_writes)\n .def_readwrite(\"outgoing_ports\", &session_settings::outgoing_ports)\n .def_readwrite(\"peer_tos\", &session_settings::peer_tos)\n .def_readwrite(\"active_downloads\", &session_settings::active_downloads)\n .def_readwrite(\"active_seeds\", &session_settings::active_seeds)\n .def_readwrite(\"active_limit\", &session_settings::active_limit)\n .def_readwrite(\"auto_manage_prefer_seeds\", &session_settings::automanaged_prefer_seeds)\n .def_readwrite(\"dont_count_slow_torrents\", &session_settings::dont_count_slow_torrents)\n .def_readwrite(\"auto_manage_interval\", &session_settings::auto_manage_interval)\n .def_readwrite(\"share_ratio_limit\", &session_settings::share_ratio_limit)\n .def_readwrite(\"seed_time_ratio_limit\", &session_settings::seed_time_ratio_limit)\n .def_readwrite(\"seed_time_limit\", &session_settings::seed_time_limit)\n .def_readwrite(\"peer_turnover\", &session_settings::peer_turnover)\n .def_readwrite(\"peer_turnover_cutoff\", &session_settings::peer_turnover_cutoff)\n .def_readwrite(\"close_redundant_connections\", &session_settings::close_redundant_connections)\n .def_readwrite(\"auto_scrape_interval\", &session_settings::auto_scrape_interval)\n .def_readwrite(\"auto_scrape_min_interval\", &session_settings::auto_scrape_min_interval)\n .def_readwrite(\"max_peerlist_size\", &session_settings::max_peerlist_size)\n .def_readwrite(\"max_paused_peerlist_size\", &session_settings::max_paused_peerlist_size)\n .def_readwrite(\"min_announce_interval\", &session_settings::min_announce_interval)\n .def_readwrite(\"prioritize_partial_pieces\", &session_settings::prioritize_partial_pieces)\n .def_readwrite(\"auto_manage_startup\", &session_settings::auto_manage_startup)\n .def_readwrite(\"rate_limit_ip_overhead\", &session_settings::rate_limit_ip_overhead)\n .def_readwrite(\"announce_to_all_trackers\", &session_settings::announce_to_all_trackers)\n .def_readwrite(\"prefer_udp_trackers\", &session_settings::prefer_udp_trackers)\n .def_readwrite(\"strict_super_seeding\", &session_settings::strict_super_seeding)\n .def_readwrite(\"seeding_piece_quota\", &session_settings::seeding_piece_quota)\n .def_readwrite(\"max_sparse_regions\", &session_settings::max_sparse_regions)\n#ifndef TORRENT_DISABLE_MLOCK\n .def_readwrite(\"lock_disk_cache\", &session_settings::lock_disk_cache)\n#endif\n .def_readwrite(\"max_rejects\", &session_settings::max_rejects)\n .def_readwrite(\"recv_socket_buffer_size\", &session_settings::recv_socket_buffer_size)\n .def_readwrite(\"send_socket_buffer_size\", &session_settings::send_socket_buffer_size)\n .def_readwrite(\"optimize_hashing_for_speed\", &session_settings::optimize_hashing_for_speed)\n .def_readwrite(\"file_checks_delay_per_block\", &session_settings::file_checks_delay_per_block)\n .def_readwrite(\"disk_cache_algorithm\", &session_settings::disk_cache_algorithm)\n .def_readwrite(\"read_cache_line_size\", &session_settings::read_cache_line_size)\n .def_readwrite(\"write_cache_line_size\", &session_settings::write_cache_line_size)\n ;\n\n enum_(\"proxy_type\")\n .value(\"none\", proxy_settings::none)\n .value(\"socks4\", proxy_settings::socks4)\n .value(\"socks5\", proxy_settings::socks5)\n .value(\"socks5_pw\", proxy_settings::socks5_pw)\n .value(\"http\", proxy_settings::http)\n .value(\"http_pw\", proxy_settings::http_pw)\n ;\n \n enum_(\"proxy_settings\")\n .def_readwrite(\"hostname\", &proxy_settings::hostname)\n .def_readwrite(\"port\", &proxy_settings::port)\n .def_readwrite(\"password\", &proxy_settings::password)\n .def_readwrite(\"username\", &proxy_settings::username)\n .def_readwrite(\"type\", &proxy_settings::type)\n ;\n\n#ifndef TORRENT_DISABLE_DHT\n class_(\"dht_settings\")\n .def_readwrite(\"max_peers_reply\", dht_settings::max_peers_reply)\n .def_readwrite(\"search_branching\", dht_settings::search_branching)\n .def_readwrite(\"service_port\", dht_settings::service_port)\n .def_readwrite(\"max_fail_count\", dht_settings::max_fail_count)\n ;\n#endif\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n enum_(\"enc_policy\")\n .value(\"forced\", pe_settings::forced)\n .value(\"enabled\", pe_settings::enabled)\n .value(\"disabled\", pe_settings::disabled)\n ;\n\n enum_(\"enc_level\")\n .value(\"rc4\", pe_settings::rc4)\n .value(\"plaintext\", pe_settings::plaintext)\n .value(\"both\", pe_settings::both)\n ;\n\n class_(\"pe_settings\")\n .def_readwrite(\"out_enc_policy\", &pe_settings::out_enc_policy)\n .def_readwrite(\"in_enc_policy\", &pe_settings::in_enc_policy)\n .def_readwrite(\"allowed_enc_level\", &pe_settings::allowed_enc_level)\n .def_readwrite(\"prefer_rc4\", &pe_settings::prefer_rc4)\n ;\n#endif\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\/\n\/* dir_access_unix.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n#include \"dir_access_unix.h\"\n\n#if defined(UNIX_ENABLED) || defined(LIBC_FILEIO_ENABLED)\n\n#ifndef ANDROID_ENABLED\n#include \n#endif\n\n#include \"os\/memory.h\"\n#include \"print_string.h\"\n#include \n#include \n\nDirAccess *DirAccessUnix::create_fs() {\n\n\treturn memnew(DirAccessUnix);\n}\n\nError DirAccessUnix::list_dir_begin() {\n\n\tlist_dir_end(); \/\/close any previous dir opening!\n\n\t\/\/char real_current_dir_name[2048]; \/\/is this enough?!\n\t\/\/getcwd(real_current_dir_name,2048);\n\t\/\/chdir(curent_path.utf8().get_data());\n\tdir_stream = opendir(current_dir.utf8().get_data());\n\t\/\/chdir(real_current_dir_name);\n\tif (!dir_stream)\n\t\treturn ERR_CANT_OPEN; \/\/error!\n\n\treturn OK;\n}\n\nbool DirAccessUnix::file_exists(String p_file) {\n\n\tGLOBAL_LOCK_FUNCTION\n\n\tif (p_file.is_rel_path())\n\t\tp_file = current_dir.plus_file(p_file);\n\n\tp_file = fix_path(p_file);\n\n\tstruct stat flags;\n\tbool success = (stat(p_file.utf8().get_data(), &flags) == 0);\n\n\tif (success && S_ISDIR(flags.st_mode)) {\n\t\tsuccess = false;\n\t}\n\n\treturn success;\n}\n\nbool DirAccessUnix::dir_exists(String p_dir) {\n\n\tGLOBAL_LOCK_FUNCTION\n\n\tif (p_dir.is_rel_path())\n\t\tp_dir = get_current_dir().plus_file(p_dir);\n\n\tp_dir = fix_path(p_dir);\n\n\tstruct stat flags;\n\tbool success = (stat(p_dir.utf8().get_data(), &flags) == 0);\n\n\tif (success && S_ISDIR(flags.st_mode))\n\t\treturn true;\n\n\treturn false;\n}\n\nuint64_t DirAccessUnix::get_modified_time(String p_file) {\n\n\tif (p_file.is_rel_path())\n\t\tp_file = current_dir.plus_file(p_file);\n\n\tp_file = fix_path(p_file);\n\n\tstruct stat flags;\n\tbool success = (stat(p_file.utf8().get_data(), &flags) == 0);\n\n\tif (success) {\n\t\treturn flags.st_mtime;\n\t} else {\n\n\t\tERR_FAIL_V(0);\n\t};\n\treturn 0;\n};\n\nString DirAccessUnix::get_next() {\n\n\tif (!dir_stream)\n\t\treturn \"\";\n\tdirent *entry;\n\n\tentry = readdir(dir_stream);\n\n\tif (entry == NULL) {\n\n\t\tlist_dir_end();\n\t\treturn \"\";\n\t}\n\n\t\/\/typedef struct stat Stat;\n\tstruct stat flags;\n\n\tString fname = fix_unicode_name(entry->d_name);\n\n\tString f = current_dir.plus_file(fname);\n\n\tif (stat(f.utf8().get_data(), &flags) == 0) {\n\n\t\tif (S_ISDIR(flags.st_mode)) {\n\n\t\t\t_cisdir = true;\n\n\t\t} else {\n\n\t\t\t_cisdir = false;\n\t\t}\n\n\t} else {\n\n\t\t_cisdir = false;\n\t}\n\n\t_cishidden = (fname != \".\" && fname != \"..\" && fname.begins_with(\".\"));\n\n\treturn fname;\n}\n\nbool DirAccessUnix::current_is_dir() const {\n\n\treturn _cisdir;\n}\n\nbool DirAccessUnix::current_is_hidden() const {\n\n\treturn _cishidden;\n}\n\nvoid DirAccessUnix::list_dir_end() {\n\n\tif (dir_stream)\n\t\tclosedir(dir_stream);\n\tdir_stream = 0;\n\t_cisdir = false;\n}\n\nint DirAccessUnix::get_drive_count() {\n\n\treturn 0;\n}\nString DirAccessUnix::get_drive(int p_drive) {\n\n\treturn \"\";\n}\n\nError DirAccessUnix::make_dir(String p_dir) {\n\n\tGLOBAL_LOCK_FUNCTION\n\n\tif (p_dir.is_rel_path())\n\t\tp_dir = get_current_dir().plus_file(p_dir);\n\n\tp_dir = fix_path(p_dir);\n\n#if 1\n\n\tbool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);\n\tint err = errno;\n\n#else\n\tchar real_current_dir_name[2048];\n\tgetcwd(real_current_dir_name, 2048);\n\tchdir(current_dir.utf8().get_data()); \/\/ascii since this may be unicode or wathever the host os wants\n\n\tbool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);\n\tint err = errno;\n\n\tchdir(real_current_dir_name);\n#endif\n\tif (success) {\n\t\treturn OK;\n\t};\n\n\tif (err == EEXIST) {\n\t\treturn ERR_ALREADY_EXISTS;\n\t};\n\n\treturn ERR_CANT_CREATE;\n}\n\nError DirAccessUnix::change_dir(String p_dir) {\n\n\tGLOBAL_LOCK_FUNCTION\n\tp_dir = fix_path(p_dir);\n\n\tchar real_current_dir_name[2048];\n\tgetcwd(real_current_dir_name, 2048);\n\tString prev_dir;\n\tif (prev_dir.parse_utf8(real_current_dir_name))\n\t\tprev_dir = real_current_dir_name; \/\/no utf8, maybe latin?\n\n\tchdir(current_dir.utf8().get_data()); \/\/ascii since this may be unicode or wathever the host os wants\n\tbool worked = (chdir(p_dir.utf8().get_data()) == 0); \/\/ we can only give this utf8\n\n\tString base = _get_root_path();\n\tif (base != \"\") {\n\n\t\tgetcwd(real_current_dir_name, 2048);\n\t\tString new_dir;\n\t\tnew_dir.parse_utf8(real_current_dir_name);\n\t\tif (!new_dir.begins_with(base))\n\t\t\tworked = false;\n\t}\n\n\tif (worked) {\n\n\t\tgetcwd(real_current_dir_name, 2048);\n\t\tif (current_dir.parse_utf8(real_current_dir_name))\n\t\t\tcurrent_dir = real_current_dir_name; \/\/no utf8, maybe latin?\n\t}\n\n\tchdir(prev_dir.utf8().get_data());\n\treturn worked ? OK : ERR_INVALID_PARAMETER;\n}\n\nString DirAccessUnix::get_current_dir() {\n\n\tString base = _get_root_path();\n\tif (base != \"\") {\n\n\t\tString bd = current_dir.replace_first(base, \"\");\n\t\tif (bd.begins_with(\"\/\"))\n\t\t\treturn _get_root_string() + bd.substr(1, bd.length());\n\t\telse\n\t\t\treturn _get_root_string() + bd;\n\t}\n\treturn current_dir;\n}\n\nError DirAccessUnix::rename(String p_path, String p_new_path) {\n\n\tif (p_path.is_rel_path())\n\t\tp_path = get_current_dir().plus_file(p_path);\n\n\tp_path = fix_path(p_path);\n\n\tif (p_new_path.is_rel_path())\n\t\tp_new_path = get_current_dir().plus_file(p_new_path);\n\n\tp_new_path = fix_path(p_new_path);\n\n\treturn ::rename(p_path.utf8().get_data(), p_new_path.utf8().get_data()) == 0 ? OK : FAILED;\n}\nError DirAccessUnix::remove(String p_path) {\n\n\tif (p_path.is_rel_path())\n\t\tp_path = get_current_dir().plus_file(p_path);\n\n\tp_path = fix_path(p_path);\n\n\tstruct stat flags;\n\tif ((stat(p_path.utf8().get_data(), &flags) != 0))\n\t\treturn FAILED;\n\n\tif (S_ISDIR(flags.st_mode))\n\t\treturn ::rmdir(p_path.utf8().get_data()) == 0 ? OK : FAILED;\n\telse\n\t\treturn ::unlink(p_path.utf8().get_data()) == 0 ? OK : FAILED;\n}\n\nsize_t DirAccessUnix::get_space_left() {\n\n#ifndef NO_STATVFS\n\tstruct statvfs vfs;\n\tif (statvfs(current_dir.utf8().get_data(), &vfs) != 0) {\n\n\t\treturn 0;\n\t};\n\n\treturn vfs.f_bfree * vfs.f_bsize;\n#else\n#warning THIS IS BROKEN\n\treturn 0;\n#endif\n};\n\nDirAccessUnix::DirAccessUnix() {\n\n\tdir_stream = 0;\n\tcurrent_dir = \".\";\n\t_cisdir = false;\n\n\t\/* determine drive count *\/\n\n\tchange_dir(current_dir);\n}\n\nDirAccessUnix::~DirAccessUnix() {\n\n\tlist_dir_end();\n}\n\n#endif \/\/posix_enabled\nReworked change_dir to support symlinks\/*************************************************************************\/\n\/* dir_access_unix.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n#include \"dir_access_unix.h\"\n\n#if defined(UNIX_ENABLED) || defined(LIBC_FILEIO_ENABLED)\n\n#ifndef ANDROID_ENABLED\n#include \n#endif\n\n#include \"os\/memory.h\"\n#include \"print_string.h\"\n#include \n#include \n\nDirAccess *DirAccessUnix::create_fs() {\n\n\treturn memnew(DirAccessUnix);\n}\n\nError DirAccessUnix::list_dir_begin() {\n\n\tlist_dir_end(); \/\/close any previous dir opening!\n\n\t\/\/char real_current_dir_name[2048]; \/\/is this enough?!\n\t\/\/getcwd(real_current_dir_name,2048);\n\t\/\/chdir(curent_path.utf8().get_data());\n\tdir_stream = opendir(current_dir.utf8().get_data());\n\t\/\/chdir(real_current_dir_name);\n\tif (!dir_stream)\n\t\treturn ERR_CANT_OPEN; \/\/error!\n\n\treturn OK;\n}\n\nbool DirAccessUnix::file_exists(String p_file) {\n\n\tGLOBAL_LOCK_FUNCTION\n\n\tif (p_file.is_rel_path())\n\t\tp_file = current_dir.plus_file(p_file);\n\n\tp_file = fix_path(p_file);\n\n\tstruct stat flags;\n\tbool success = (stat(p_file.utf8().get_data(), &flags) == 0);\n\n\tif (success && S_ISDIR(flags.st_mode)) {\n\t\tsuccess = false;\n\t}\n\n\treturn success;\n}\n\nbool DirAccessUnix::dir_exists(String p_dir) {\n\n\tGLOBAL_LOCK_FUNCTION\n\n\tif (p_dir.is_rel_path())\n\t\tp_dir = get_current_dir().plus_file(p_dir);\n\n\tp_dir = fix_path(p_dir);\n\n\tstruct stat flags;\n\tbool success = (stat(p_dir.utf8().get_data(), &flags) == 0);\n\n\tif (success && S_ISDIR(flags.st_mode))\n\t\treturn true;\n\n\treturn false;\n}\n\nuint64_t DirAccessUnix::get_modified_time(String p_file) {\n\n\tif (p_file.is_rel_path())\n\t\tp_file = current_dir.plus_file(p_file);\n\n\tp_file = fix_path(p_file);\n\n\tstruct stat flags;\n\tbool success = (stat(p_file.utf8().get_data(), &flags) == 0);\n\n\tif (success) {\n\t\treturn flags.st_mtime;\n\t} else {\n\n\t\tERR_FAIL_V(0);\n\t};\n\treturn 0;\n};\n\nString DirAccessUnix::get_next() {\n\n\tif (!dir_stream)\n\t\treturn \"\";\n\tdirent *entry;\n\n\tentry = readdir(dir_stream);\n\n\tif (entry == NULL) {\n\n\t\tlist_dir_end();\n\t\treturn \"\";\n\t}\n\n\t\/\/typedef struct stat Stat;\n\tstruct stat flags;\n\n\tString fname = fix_unicode_name(entry->d_name);\n\n\tString f = current_dir.plus_file(fname);\n\n\tif (stat(f.utf8().get_data(), &flags) == 0) {\n\n\t\tif (S_ISDIR(flags.st_mode)) {\n\n\t\t\t_cisdir = true;\n\n\t\t} else {\n\n\t\t\t_cisdir = false;\n\t\t}\n\n\t} else {\n\n\t\t_cisdir = false;\n\t}\n\n\t_cishidden = (fname != \".\" && fname != \"..\" && fname.begins_with(\".\"));\n\n\treturn fname;\n}\n\nbool DirAccessUnix::current_is_dir() const {\n\n\treturn _cisdir;\n}\n\nbool DirAccessUnix::current_is_hidden() const {\n\n\treturn _cishidden;\n}\n\nvoid DirAccessUnix::list_dir_end() {\n\n\tif (dir_stream)\n\t\tclosedir(dir_stream);\n\tdir_stream = 0;\n\t_cisdir = false;\n}\n\nint DirAccessUnix::get_drive_count() {\n\n\treturn 0;\n}\nString DirAccessUnix::get_drive(int p_drive) {\n\n\treturn \"\";\n}\n\nError DirAccessUnix::make_dir(String p_dir) {\n\n\tGLOBAL_LOCK_FUNCTION\n\n\tif (p_dir.is_rel_path())\n\t\tp_dir = get_current_dir().plus_file(p_dir);\n\n\tp_dir = fix_path(p_dir);\n\n#if 1\n\n\tbool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);\n\tint err = errno;\n\n#else\n\tchar real_current_dir_name[2048];\n\tgetcwd(real_current_dir_name, 2048);\n\tchdir(current_dir.utf8().get_data()); \/\/ascii since this may be unicode or wathever the host os wants\n\n\tbool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);\n\tint err = errno;\n\n\tchdir(real_current_dir_name);\n#endif\n\tif (success) {\n\t\treturn OK;\n\t};\n\n\tif (err == EEXIST) {\n\t\treturn ERR_ALREADY_EXISTS;\n\t};\n\n\treturn ERR_CANT_CREATE;\n}\n\nError DirAccessUnix::change_dir(String p_dir) {\n\n\tGLOBAL_LOCK_FUNCTION\n\n\t\/\/ make sure current_dir is valid absolute path\n\tif (current_dir == \".\" || current_dir == \"\") {\n\t\tchar real_current_dir_name[2048];\n\t\tgetcwd(real_current_dir_name, 2048);\n\t\tcurrent_dir.parse_utf8(real_current_dir_name);\n\t}\n\n\tif (p_dir == \".\") {\n\t\treturn OK;\n\t}\n\n\tp_dir = fix_path(p_dir);\n\n\tString prev_dir = current_dir;\n\n\tif (p_dir.is_rel_path()) {\n\t\tString next_dir = current_dir + \"\/\" + p_dir;\n\t\tnext_dir = next_dir.simplify_path();\n\t\tcurrent_dir = next_dir;\n\t} else {\n\t\tcurrent_dir = p_dir;\n\t}\n\n\tbool worked = (chdir(current_dir.utf8().get_data()) == 0); \/\/ we can only give this utf8\n\tif (!worked) {\n\t\tcurrent_dir = prev_dir;\n\t\treturn ERR_INVALID_PARAMETER;\n\t}\n\n\treturn OK;\n}\n\nString DirAccessUnix::get_current_dir() {\n\n\tString base = _get_root_path();\n\tif (base != \"\") {\n\n\t\tString bd = current_dir.replace_first(base, \"\");\n\t\tif (bd.begins_with(\"\/\"))\n\t\t\treturn _get_root_string() + bd.substr(1, bd.length());\n\t\telse\n\t\t\treturn _get_root_string() + bd;\n\t}\n\treturn current_dir;\n}\n\nError DirAccessUnix::rename(String p_path, String p_new_path) {\n\n\tif (p_path.is_rel_path())\n\t\tp_path = get_current_dir().plus_file(p_path);\n\n\tp_path = fix_path(p_path);\n\n\tif (p_new_path.is_rel_path())\n\t\tp_new_path = get_current_dir().plus_file(p_new_path);\n\n\tp_new_path = fix_path(p_new_path);\n\n\treturn ::rename(p_path.utf8().get_data(), p_new_path.utf8().get_data()) == 0 ? OK : FAILED;\n}\nError DirAccessUnix::remove(String p_path) {\n\n\tif (p_path.is_rel_path())\n\t\tp_path = get_current_dir().plus_file(p_path);\n\n\tp_path = fix_path(p_path);\n\n\tstruct stat flags;\n\tif ((stat(p_path.utf8().get_data(), &flags) != 0))\n\t\treturn FAILED;\n\n\tif (S_ISDIR(flags.st_mode))\n\t\treturn ::rmdir(p_path.utf8().get_data()) == 0 ? OK : FAILED;\n\telse\n\t\treturn ::unlink(p_path.utf8().get_data()) == 0 ? OK : FAILED;\n}\n\nsize_t DirAccessUnix::get_space_left() {\n\n#ifndef NO_STATVFS\n\tstruct statvfs vfs;\n\tif (statvfs(current_dir.utf8().get_data(), &vfs) != 0) {\n\n\t\treturn 0;\n\t};\n\n\treturn vfs.f_bfree * vfs.f_bsize;\n#else\n#warning THIS IS BROKEN\n\treturn 0;\n#endif\n};\n\nDirAccessUnix::DirAccessUnix() {\n\n\tdir_stream = 0;\n\tcurrent_dir = \".\";\n\t_cisdir = false;\n\n\t\/* determine drive count *\/\n\n\tchange_dir(current_dir);\n}\n\nDirAccessUnix::~DirAccessUnix() {\n\n\tlist_dir_end();\n}\n\n#endif \/\/posix_enabled\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_ASSEMBLER_GRIDWALKER_HH\n#define DUNE_GDT_ASSEMBLER_GRIDWALKER_HH\n\n#include \n#include \n#include \n\n#include \n\nnamespace Dune {\nnamespace GDT {\nnamespace Functor {\n\n\ntemplate \nclass Codim0\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n\n virtual ~Codim0()\n {\n }\n\n virtual void prepare()\n {\n }\n\n virtual void apply_local(const EntityType& entity) = 0;\n\n virtual void finalize()\n {\n }\n}; \/\/ class Codim0\n\n\ntemplate \nclass Codim1\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual ~Codim1()\n {\n }\n\n virtual void prepare()\n {\n }\n\n virtual void apply_local(const IntersectionType& intersection) = 0;\n\n virtual void finalize()\n {\n }\n}; \/\/ class Codim1\n\n\n} \/\/ namespace Functor\nnamespace ApplyOn {\n\n\n\/**\n * \\brief Interface for functors to tell on which entity to apply.\n *\n * The derived class has to provide a method with the following signature:\n * \\code\nvirtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const\n{\n ...\n}\n\\endcode\n *\/\ntemplate \nclass WhichEntity\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n\n virtual ~WhichEntity()\n {\n }\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const EntityType& \/*entity*\/) const = 0;\n}; \/\/ class WhichEntity\n\n\n\/**\n * \\brief Selects all entities.\n *\/\ntemplate \nclass AllEntities : public WhichEntity\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const EntityType& \/*entity*\/) const DS_FINAL\n {\n return true;\n }\n}; \/\/ class AllEntities\n\n\n\/**\n * \\brief Selects entities which have a boundary intersection.\n *\/\ntemplate \nclass BoundaryEntities : public WhichEntity\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const EntityType& entity) const DS_FINAL\n {\n return entity.hasBoundaryIntersections();\n }\n}; \/\/ class BoundaryEntities\n\n\n\/**\n * \\brief Interface for functors to tell on which intersection to apply.\n *\n * The derived class has to provide a method with the following signature:\n * \\code\nvirtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const\n{\n ...\n}\n\\endcode\n *\/\ntemplate \nclass WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual ~WhichIntersection()\n {\n }\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const IntersectionType& \/*intersection*\/) const = 0;\n}; \/\/ class WhichIntersection< GridViewImp >\n\n\n\/**\n * \\brief Selects all intersections.\n *\/\ntemplate \nclass AllIntersections : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const IntersectionType& \/*intersection*\/) const DS_FINAL\n {\n return true;\n }\n}; \/\/ class AllIntersections\n\n\n\/**\n * \\brief Selects each inner intersection.\n *\n * To decide if this in an inner intersection,\n\\code\nintersection.neighbor() && !intersection.boundary()\n\\endcode\n * is used.\n *\/\ntemplate \nclass InnerIntersections : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const IntersectionType& intersection) const DS_FINAL\n {\n return intersection.neighbor() && !intersection.boundary();\n }\n}; \/\/ class InnerIntersections\n\n\n\/**\n * \\brief Selects each inner intersection only once.\n *\n * To decide if this in an inner intersection,\n\\code\nintersection.neighbor() && !intersection.boundary()\n\\endcode\n * is used, and true is returned, if the index of the inside() entity is smaller than the index of the outside()\n * entity.\n *\/\ntemplate \nclass InnerIntersectionsPrimally : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_FINAL\n {\n if (intersection.neighbor() && !intersection.boundary()) {\n const auto insideEntityPtr = intersection.inside();\n const auto& insideEntity = *insideEntityPtr;\n const auto outsideNeighborPtr = intersection.outside();\n const auto& outsideNeighbor = *outsideNeighborPtr;\n return grid_view.indexSet().index(insideEntity) < grid_view.indexSet().index(outsideNeighbor);\n } else\n return false;\n }\n}; \/\/ class InnerIntersections\n\n\ntemplate \nclass BoundaryIntersections : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const IntersectionType& intersection) const DS_FINAL\n {\n return intersection.boundary();\n }\n}; \/\/ class BoundaryIntersections\n\n\ntemplate \nclass DirichletIntersections : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n typedef Stuff::GridboundaryInterface BoundaryInfoType;\n\n DirichletIntersections(const BoundaryInfoType& boundary_info)\n : boundary_info_(boundary_info)\n {\n }\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const IntersectionType& intersection) const DS_FINAL\n {\n return boundary_info_.dirichlet(intersection);\n }\n\nprivate:\n const BoundaryInfoType& boundary_info_;\n}; \/\/ class DirichletIntersections\n\n\ntemplate \nclass NeumannIntersections : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n typedef Stuff::GridboundaryInterface BoundaryInfoType;\n\n NeumannIntersections(const BoundaryInfoType& boundary_info)\n : boundary_info_(boundary_info)\n {\n }\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const IntersectionType& intersection) const DS_FINAL\n {\n return boundary_info_.neumann(intersection);\n }\n\nprivate:\n const BoundaryInfoType& boundary_info_;\n}; \/\/ class NeumannIntersections\n\n\n} \/\/ namespace ApplyOn\n\n\ntemplate \nclass GridWalker\n{\n typedef GridWalker ThisType;\n\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n typedef typename GridViewType::Intersection IntersectionType;\n\nprotected:\n typedef Stuff::GridboundaryInterface BoundaryInfoType;\n\n class Codim0Object : public Functor::Codim0\n {\n public:\n ~Codim0Object()\n {\n }\n virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const = 0;\n };\n\n\n template \n class Codim0FunctorWrapper : public Codim0Object\n {\n public:\n Codim0FunctorWrapper(Codim0FunctorType& wrapped_functor, const ApplyOn::WhichEntity* where)\n : wrapped_functor_(wrapped_functor)\n , where_(where)\n {\n }\n\n virtual ~Codim0FunctorWrapper()\n {\n }\n\n virtual void prepare() DS_FINAL\n {\n wrapped_functor_.prepare();\n }\n\n virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_FINAL\n {\n return where_->apply_on(grid_view, entity);\n }\n\n virtual void apply_local(const EntityType& entity) DS_FINAL\n {\n wrapped_functor_.apply_local(entity);\n }\n\n virtual void finalize() DS_FINAL\n {\n wrapped_functor_.finalize();\n }\n\n private:\n Codim0FunctorType& wrapped_functor_;\n std::unique_ptr> where_;\n }; \/\/ class Codim0FunctorWrapper\n\n\n class Codim1Object : public Functor::Codim1\n {\n public:\n ~Codim1Object()\n {\n }\n virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const = 0;\n };\n\n\n template \n class Codim1FunctorWrapper : public Codim1Object\n {\n public:\n Codim1FunctorWrapper(Codim1FunctorType& wrapped_functor, const ApplyOn::WhichIntersection* where)\n : wrapped_functor_(wrapped_functor)\n , where_(where)\n {\n }\n\n virtual void prepare() DS_FINAL\n {\n wrapped_functor_.prepare();\n }\n\n virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_FINAL\n {\n return where_->apply_on(grid_view, intersection);\n }\n\n virtual void apply_local(const IntersectionType& intersection) DS_FINAL\n {\n wrapped_functor_.apply_local(intersection);\n }\n\n virtual void finalize() DS_FINAL\n {\n wrapped_functor_.finalize();\n }\n\n private:\n Codim1FunctorType& wrapped_functor_;\n std::unique_ptr> where_;\n }; \/\/ class Codim1FunctorWrapper\n\npublic:\n GridWalker(const GridViewType& grid_view)\n : grid_view_(grid_view)\n {\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n void add(Functor::Codim0& functor,\n const ApplyOn::WhichEntity* where = new ApplyOn::AllEntities())\n {\n codim0_functors_.emplace_back(new Codim0FunctorWrapper>(functor, where));\n }\n\n void add(Functor::Codim1& functor,\n const ApplyOn::WhichIntersection* where = new ApplyOn::AllIntersections())\n {\n codim1_functors_.emplace_back(new Codim1FunctorWrapper>(functor, where));\n }\n\n void walk(const bool clear_stack = true)\n {\n \/\/ prepare functors\n for (auto& functor : codim0_functors_)\n functor->prepare();\n for (auto& functor : codim1_functors_)\n functor->prepare();\n\n \/\/ only do something, if we have to\n if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {\n \/\/ walk the grid\n const auto entity_it_end = grid_view_.template end<0>();\n for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {\n const EntityType& entity = *entity_it;\n\n \/\/ apply codim0 functors\n for (auto& functor : codim0_functors_)\n if (functor->apply_on(grid_view_, entity))\n functor->apply_local(entity);\n\n \/\/ only walk the intersections, if there are codim1 functors present\n if (codim1_functors_.size() > 0) {\n \/\/ walk the intersections\n const auto intersection_it_end = grid_view_.iend(entity);\n for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end;\n ++intersection_it) {\n const auto& intersection = *intersection_it;\n\n \/\/ apply codim1 functors\n for (auto& functor : codim1_functors_)\n if (functor->apply_on(grid_view_, intersection))\n functor->apply_local(intersection);\n\n } \/\/ walk the intersections\n } \/\/ only walk the intersections, if there are codim1 functors present\n } \/\/ walk the grid\n } \/\/ only do something, if we have to\n\n \/\/ finalize functors\n for (auto& functor : codim0_functors_)\n functor->finalize();\n for (auto& functor : codim1_functors_)\n functor->finalize();\n\n \/\/ clear the stack of functors\n if (clear_stack)\n clear();\n } \/\/ ... walk()\n\n void clear()\n {\n codim0_functors_ = std::vector>();\n codim1_functors_ = std::vector>();\n }\n\nprotected:\n const GridViewType& grid_view_;\n std::vector> codim0_functors_;\n std::vector> codim1_functors_;\n}; \/\/ class GridWalker\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_ASSEMBLER_GRIDWALKER_HH\n[assembler.gridwalker] added override and final keywords\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_ASSEMBLER_GRIDWALKER_HH\n#define DUNE_GDT_ASSEMBLER_GRIDWALKER_HH\n\n#include \n#include \n#include \n\n#include \n\nnamespace Dune {\nnamespace GDT {\nnamespace Functor {\n\n\ntemplate \nclass Codim0\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n\n virtual ~Codim0()\n {\n }\n\n virtual void prepare()\n {\n }\n\n virtual void apply_local(const EntityType& entity) = 0;\n\n virtual void finalize()\n {\n }\n}; \/\/ class Codim0\n\n\ntemplate \nclass Codim1\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual ~Codim1()\n {\n }\n\n virtual void prepare()\n {\n }\n\n virtual void apply_local(const IntersectionType& intersection) = 0;\n\n virtual void finalize()\n {\n }\n}; \/\/ class Codim1\n\n\n} \/\/ namespace Functor\nnamespace ApplyOn {\n\n\n\/**\n * \\brief Interface for functors to tell on which entity to apply.\n *\n * The derived class has to provide a method with the following signature:\n * \\code\nvirtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const\n{\n ...\n}\n\\endcode\n *\/\ntemplate \nclass WhichEntity\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n\n virtual ~WhichEntity()\n {\n }\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const EntityType& \/*entity*\/) const = 0;\n}; \/\/ class WhichEntity\n\n\n\/**\n * \\brief Selects all entities.\n *\/\ntemplate \nclass AllEntities : public WhichEntity\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const EntityType& \/*entity*\/) const DS_OVERRIDE DS_FINAL\n {\n return true;\n }\n}; \/\/ class AllEntities\n\n\n\/**\n * \\brief Selects entities which have a boundary intersection.\n *\/\ntemplate \nclass BoundaryEntities : public WhichEntity\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const EntityType& entity) const DS_OVERRIDE DS_FINAL\n {\n return entity.hasBoundaryIntersections();\n }\n}; \/\/ class BoundaryEntities\n\n\n\/**\n * \\brief Interface for functors to tell on which intersection to apply.\n *\n * The derived class has to provide a method with the following signature:\n * \\code\nvirtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const\n{\n ...\n}\n\\endcode\n *\/\ntemplate \nclass WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual ~WhichIntersection()\n {\n }\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/, const IntersectionType& \/*intersection*\/) const = 0;\n}; \/\/ class WhichIntersection< GridViewImp >\n\n\n\/**\n * \\brief Selects all intersections.\n *\/\ntemplate \nclass AllIntersections : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/,\n const IntersectionType& \/*intersection*\/) const DS_OVERRIDE DS_FINAL\n {\n return true;\n }\n}; \/\/ class AllIntersections\n\n\n\/**\n * \\brief Selects each inner intersection.\n *\n * To decide if this in an inner intersection,\n\\code\nintersection.neighbor() && !intersection.boundary()\n\\endcode\n * is used.\n *\/\ntemplate \nclass InnerIntersections : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/,\n const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL\n {\n return intersection.neighbor() && !intersection.boundary();\n }\n}; \/\/ class InnerIntersections\n\n\n\/**\n * \\brief Selects each inner intersection only once.\n *\n * To decide if this in an inner intersection,\n\\code\nintersection.neighbor() && !intersection.boundary()\n\\endcode\n * is used, and true is returned, if the index of the inside() entity is smaller than the index of the outside()\n * entity.\n *\/\ntemplate \nclass InnerIntersectionsPrimally : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL\n {\n if (intersection.neighbor() && !intersection.boundary()) {\n const auto insideEntityPtr = intersection.inside();\n const auto& insideEntity = *insideEntityPtr;\n const auto outsideNeighborPtr = intersection.outside();\n const auto& outsideNeighbor = *outsideNeighborPtr;\n return grid_view.indexSet().index(insideEntity) < grid_view.indexSet().index(outsideNeighbor);\n } else\n return false;\n }\n}; \/\/ class InnerIntersections\n\n\ntemplate \nclass BoundaryIntersections : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/,\n const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL\n {\n return intersection.boundary();\n }\n}; \/\/ class BoundaryIntersections\n\n\ntemplate \nclass DirichletIntersections : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n typedef Stuff::GridboundaryInterface BoundaryInfoType;\n\n DirichletIntersections(const BoundaryInfoType& boundary_info)\n : boundary_info_(boundary_info)\n {\n }\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/,\n const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL\n {\n return boundary_info_.dirichlet(intersection);\n }\n\nprivate:\n const BoundaryInfoType& boundary_info_;\n}; \/\/ class DirichletIntersections\n\n\ntemplate \nclass NeumannIntersections : public WhichIntersection\n{\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::Intersection IntersectionType;\n typedef Stuff::GridboundaryInterface BoundaryInfoType;\n\n NeumannIntersections(const BoundaryInfoType& boundary_info)\n : boundary_info_(boundary_info)\n {\n }\n\n virtual bool apply_on(const GridViewType& \/*grid_view*\/,\n const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL\n {\n return boundary_info_.neumann(intersection);\n }\n\nprivate:\n const BoundaryInfoType& boundary_info_;\n}; \/\/ class NeumannIntersections\n\n\n} \/\/ namespace ApplyOn\n\n\ntemplate \nclass GridWalker\n{\n typedef GridWalker ThisType;\n\npublic:\n typedef GridViewImp GridViewType;\n typedef typename GridViewType::template Codim<0>::Entity EntityType;\n typedef typename GridViewType::Intersection IntersectionType;\n\nprotected:\n typedef Stuff::GridboundaryInterface BoundaryInfoType;\n\n class Codim0Object : public Functor::Codim0\n {\n public:\n ~Codim0Object()\n {\n }\n virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const = 0;\n };\n\n\n template \n class Codim0FunctorWrapper : public Codim0Object\n {\n public:\n Codim0FunctorWrapper(Codim0FunctorType& wrapped_functor, const ApplyOn::WhichEntity* where)\n : wrapped_functor_(wrapped_functor)\n , where_(where)\n {\n }\n\n virtual ~Codim0FunctorWrapper()\n {\n }\n\n virtual void prepare() DS_OVERRIDE DS_FINAL\n {\n wrapped_functor_.prepare();\n }\n\n virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL\n {\n return where_->apply_on(grid_view, entity);\n }\n\n virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL\n {\n wrapped_functor_.apply_local(entity);\n }\n\n virtual void finalize() DS_OVERRIDE DS_FINAL\n {\n wrapped_functor_.finalize();\n }\n\n private:\n Codim0FunctorType& wrapped_functor_;\n std::unique_ptr> where_;\n }; \/\/ class Codim0FunctorWrapper\n\n\n class Codim1Object : public Functor::Codim1\n {\n public:\n ~Codim1Object()\n {\n }\n virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const = 0;\n };\n\n\n template \n class Codim1FunctorWrapper : public Codim1Object\n {\n public:\n Codim1FunctorWrapper(Codim1FunctorType& wrapped_functor, const ApplyOn::WhichIntersection* where)\n : wrapped_functor_(wrapped_functor)\n , where_(where)\n {\n }\n\n virtual void prepare() DS_OVERRIDE DS_FINAL\n {\n wrapped_functor_.prepare();\n }\n\n virtual bool apply_on(const GridViewType& grid_view,\n const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL\n {\n return where_->apply_on(grid_view, intersection);\n }\n\n virtual void apply_local(const IntersectionType& intersection) DS_OVERRIDE DS_FINAL\n {\n wrapped_functor_.apply_local(intersection);\n }\n\n virtual void finalize() DS_OVERRIDE DS_FINAL\n {\n wrapped_functor_.finalize();\n }\n\n private:\n Codim1FunctorType& wrapped_functor_;\n std::unique_ptr> where_;\n }; \/\/ class Codim1FunctorWrapper\n\npublic:\n GridWalker(const GridViewType& grid_view)\n : grid_view_(grid_view)\n {\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n void add(Functor::Codim0& functor,\n const ApplyOn::WhichEntity* where = new ApplyOn::AllEntities())\n {\n codim0_functors_.emplace_back(new Codim0FunctorWrapper>(functor, where));\n }\n\n void add(Functor::Codim1& functor,\n const ApplyOn::WhichIntersection* where = new ApplyOn::AllIntersections())\n {\n codim1_functors_.emplace_back(new Codim1FunctorWrapper>(functor, where));\n }\n\n void walk(const bool clear_stack = true)\n {\n \/\/ prepare functors\n for (auto& functor : codim0_functors_)\n functor->prepare();\n for (auto& functor : codim1_functors_)\n functor->prepare();\n\n \/\/ only do something, if we have to\n if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {\n \/\/ walk the grid\n const auto entity_it_end = grid_view_.template end<0>();\n for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {\n const EntityType& entity = *entity_it;\n\n \/\/ apply codim0 functors\n for (auto& functor : codim0_functors_)\n if (functor->apply_on(grid_view_, entity))\n functor->apply_local(entity);\n\n \/\/ only walk the intersections, if there are codim1 functors present\n if (codim1_functors_.size() > 0) {\n \/\/ walk the intersections\n const auto intersection_it_end = grid_view_.iend(entity);\n for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end;\n ++intersection_it) {\n const auto& intersection = *intersection_it;\n\n \/\/ apply codim1 functors\n for (auto& functor : codim1_functors_)\n if (functor->apply_on(grid_view_, intersection))\n functor->apply_local(intersection);\n\n } \/\/ walk the intersections\n } \/\/ only walk the intersections, if there are codim1 functors present\n } \/\/ walk the grid\n } \/\/ only do something, if we have to\n\n \/\/ finalize functors\n for (auto& functor : codim0_functors_)\n functor->finalize();\n for (auto& functor : codim1_functors_)\n functor->finalize();\n\n \/\/ clear the stack of functors\n if (clear_stack)\n clear();\n } \/\/ ... walk(...)\n\n void clear()\n {\n codim0_functors_ = std::vector>();\n codim1_functors_ = std::vector>();\n } \/\/ ... clear()\n\nprotected:\n const GridViewType& grid_view_;\n std::vector> codim0_functors_;\n std::vector> codim1_functors_;\n}; \/\/ class GridWalker\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_ASSEMBLER_GRIDWALKER_HH\n<|endoftext|>"} {"text":"\/\/ dune-multiscale\n\/\/ Copyright Holders: Patrick Henning, Rene Milk\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_MULTISCALE_COMMON_TRAITS_HH\n#define DUNE_MULTISCALE_COMMON_TRAITS_HH\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace Dune {\n\ntemplate \nstruct GridPtr;\n\nnamespace PDELab {\n\nclass NoConstraints;\n\/\/class ConformingDirichletConstraints;\n\n} \/\/namespace PDELab\n\nnamespace Fem {\ntemplate \nclass GridFunctionAdapter;\ntemplate \nclass DataOutput;\ntemplate \nclass DataWriter;\ntemplate \nclass AdaptationManager;\n} \/\/ namespace Fem\n\nnamespace Stuff {\ntemplate \nclass GlobalFunction;\ntemplate \nclass GlobalConstantFunction;\n}\nnamespace Multiscale {\nnamespace Problem {\n\nstruct DiffusionBase;\nstruct LowerOrderBase;\nclass NeumannDataBase;\nclass DirichletDataBase;\nclass IModelProblemData;\n\n} \/\/ namespace Problem\n\n\/\/! type construction for the HMM algorithm\nstruct CommonTraits {\n static constexpr int world_dim = 2;\n\/\/ typedef Dune::GridSelector::GridType GridType;\n typedef Dune::SGrid GridType;\n\/\/ typedef Dune::YaspGrid GridType;\n typedef GridType::Codim<0>::Entity EntityType;\n typedef Dune::Fem::AdaptiveLeafGridPart GridPartType;\n typedef Dune::GridPtr GridPointerType;\n typedef double FieldType;\n typedef Dune::Fem::FunctionSpace FunctionSpaceType;\n\n typedef Dune::Stuff::GlobalFunction FunctionBaseType;\n\n typedef Dune::Stuff::GlobalConstantFunction ConstantFunctionBaseType;\n\n typedef Problem::IModelProblemData ModelProblemDataType;\n \/\/! type of first source term (right hand side of differential equation or type of 'f')\n typedef FunctionBaseType FirstSourceType;\n \/\/! type of second source term 'G' (second right hand side of differential equation 'div G')\n typedef FunctionBaseType SecondSourceType;\n \/\/! type of (possibly non-linear) diffusion term (i.e. 'A^{\\epsilon}')\n typedef Problem::DiffusionBase DiffusionType;\n \/\/! type of (possibly non-linear) lower order term F( x, u(x), grad u(x) )\n typedef Problem::LowerOrderBase LowerOrderTermType;\n \/\/! type of inhomogeneous Dirichlet boundary condition\n typedef FunctionBaseType DirichletBCType;\n \/\/! type of inhomogeneous Neumann boundary condition\n typedef FunctionBaseType NeumannBCType;\n \/\/! type of dirichlet data\n typedef Problem::DirichletDataBase DirichletDataType;\n \/\/! type of neumann data\n typedef Problem::NeumannDataBase NeumannDataType;\n \/\/! type of mass (or reaction) term (i.e. 'm' or 'c')\n typedef FunctionBaseType MassTermType;\n \/\/! default type for any missing coefficient function (e.g. advection,...)\n typedef FunctionBaseType DefaultDummyFunctionType;\n\n \/\/! type of exact solution (in general unknown)\n typedef FunctionBaseType ExactSolutionType;\n static constexpr unsigned int exact_solution_space_order = 3 * st_lagrangespace_order;\n\n typedef FunctionSpaceType::DomainType DomainType;\n \/\/! define the type of elements of the codomain v(\\Omega) (typically a subset of \\R)\n typedef FunctionSpaceType::RangeType RangeType;\n \/\/! defines the function space to which the numerical solution belongs to\n \/\/! see dune\/fem\/lagrangebase.hh\n typedef Dune::Fem::LagrangeDiscreteFunctionSpace\n DiscreteFunctionSpaceType;\n typedef DiscreteFunctionSpaceType::DomainFieldType TimeType;\n typedef DiscreteFunctionSpaceType::JacobianRangeType JacobianRangeType;\n\n typedef GridPartType::IntersectionType FaceType;\n typedef GridType::Codim<0>::EntityPointer EntityPointerType;\n typedef GridType::Codim<0>::Geometry EntityGeometryType;\n typedef GridType::Codim<1>::Geometry FaceGeometryType;\n \/\/!TODO carry the rename over to the type def'ed name\n typedef DiscreteFunctionSpaceType::BasisFunctionSetType BasisFunctionSetType;\n typedef DiscreteFunctionSpaceType::RangeFieldType RangeFieldType;\n\n typedef BackendChooser::DiscreteFunctionType DiscreteFunctionType;\n typedef std::shared_ptr DiscreteFunction_ptr;\n typedef BackendChooser::LinearOperatorType LinearOperatorType;\n\n typedef std::vector RangeVector;\n typedef std::vector RangeVectorVector;\n\n static constexpr int polynomial_order = DiscreteFunctionSpaceType::polynomialOrder;\n static constexpr int quadrature_order = 2 * polynomial_order + 2;\n\n typedef PDELab::QkLocalFiniteElementMap\n FEMapType;\n typedef BackendChooser::VectorBackendType VectorBackendType;\n typedef PDELab::GridFunctionSpace GridFunctionSpaceType;\n typedef typename PDELab::BackendVectorSelector::Type PdelabVectorType;\n\n};\n\ntemplate \nstd::shared_ptr make_df_ptr(const std::string name, const typename T::DiscreteFunctionSpaceType& space) {\n return std::make_shared(name, space);\n \/\/ return DSC::make_unique(name, space);\n}\n\n} \/\/ namespace Multiscale\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_MULTISCALE_COMMON_TRAITS_HH\n[common.traits] updated stuff.function.global signature\/\/ dune-multiscale\n\/\/ Copyright Holders: Patrick Henning, Rene Milk\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_MULTISCALE_COMMON_TRAITS_HH\n#define DUNE_MULTISCALE_COMMON_TRAITS_HH\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace Dune {\n\ntemplate \nstruct GridPtr;\n\nnamespace PDELab {\n\nclass NoConstraints;\n\/\/class ConformingDirichletConstraints;\n\n} \/\/namespace PDELab\n\nnamespace Fem {\ntemplate \nclass GridFunctionAdapter;\ntemplate \nclass DataOutput;\ntemplate \nclass DataWriter;\ntemplate \nclass AdaptationManager;\n} \/\/ namespace Fem\n\nnamespace Stuff {\ntemplate \nclass GlobalFunction;\ntemplate \nclass GlobalConstantFunction;\n}\nnamespace Multiscale {\nnamespace Problem {\n\nstruct DiffusionBase;\nstruct LowerOrderBase;\nclass NeumannDataBase;\nclass DirichletDataBase;\nclass IModelProblemData;\n\n} \/\/ namespace Problem\n\n\/\/! type construction for the HMM algorithm\nstruct CommonTraits {\n static constexpr int world_dim = 2;\n\/\/ typedef Dune::GridSelector::GridType GridType;\n typedef Dune::SGrid GridType;\n\/\/ typedef Dune::YaspGrid GridType;\n typedef GridType::Codim<0>::Entity EntityType;\n typedef Dune::Fem::AdaptiveLeafGridPart GridPartType;\n typedef Dune::GridPtr GridPointerType;\n typedef double FieldType;\n typedef Dune::Fem::FunctionSpace FunctionSpaceType;\n\n typedef Dune::Stuff::GlobalFunction FunctionBaseType;\n\n typedef Dune::Stuff::GlobalConstantFunction ConstantFunctionBaseType;\n\n typedef Problem::IModelProblemData ModelProblemDataType;\n \/\/! type of first source term (right hand side of differential equation or type of 'f')\n typedef FunctionBaseType FirstSourceType;\n \/\/! type of second source term 'G' (second right hand side of differential equation 'div G')\n typedef FunctionBaseType SecondSourceType;\n \/\/! type of (possibly non-linear) diffusion term (i.e. 'A^{\\epsilon}')\n typedef Problem::DiffusionBase DiffusionType;\n \/\/! type of (possibly non-linear) lower order term F( x, u(x), grad u(x) )\n typedef Problem::LowerOrderBase LowerOrderTermType;\n \/\/! type of inhomogeneous Dirichlet boundary condition\n typedef FunctionBaseType DirichletBCType;\n \/\/! type of inhomogeneous Neumann boundary condition\n typedef FunctionBaseType NeumannBCType;\n \/\/! type of dirichlet data\n typedef Problem::DirichletDataBase DirichletDataType;\n \/\/! type of neumann data\n typedef Problem::NeumannDataBase NeumannDataType;\n \/\/! type of mass (or reaction) term (i.e. 'm' or 'c')\n typedef FunctionBaseType MassTermType;\n \/\/! default type for any missing coefficient function (e.g. advection,...)\n typedef FunctionBaseType DefaultDummyFunctionType;\n\n \/\/! type of exact solution (in general unknown)\n typedef FunctionBaseType ExactSolutionType;\n static constexpr unsigned int exact_solution_space_order = 3 * st_lagrangespace_order;\n\n typedef FunctionSpaceType::DomainType DomainType;\n \/\/! define the type of elements of the codomain v(\\Omega) (typically a subset of \\R)\n typedef FunctionSpaceType::RangeType RangeType;\n \/\/! defines the function space to which the numerical solution belongs to\n \/\/! see dune\/fem\/lagrangebase.hh\n typedef Dune::Fem::LagrangeDiscreteFunctionSpace\n DiscreteFunctionSpaceType;\n typedef DiscreteFunctionSpaceType::DomainFieldType TimeType;\n typedef DiscreteFunctionSpaceType::JacobianRangeType JacobianRangeType;\n\n typedef GridPartType::IntersectionType FaceType;\n typedef GridType::Codim<0>::EntityPointer EntityPointerType;\n typedef GridType::Codim<0>::Geometry EntityGeometryType;\n typedef GridType::Codim<1>::Geometry FaceGeometryType;\n \/\/!TODO carry the rename over to the type def'ed name\n typedef DiscreteFunctionSpaceType::BasisFunctionSetType BasisFunctionSetType;\n typedef DiscreteFunctionSpaceType::RangeFieldType RangeFieldType;\n\n typedef BackendChooser::DiscreteFunctionType DiscreteFunctionType;\n typedef std::shared_ptr DiscreteFunction_ptr;\n typedef BackendChooser::LinearOperatorType LinearOperatorType;\n\n typedef std::vector RangeVector;\n typedef std::vector RangeVectorVector;\n\n static constexpr int polynomial_order = DiscreteFunctionSpaceType::polynomialOrder;\n static constexpr int quadrature_order = 2 * polynomial_order + 2;\n\n typedef PDELab::QkLocalFiniteElementMap\n FEMapType;\n typedef BackendChooser::VectorBackendType VectorBackendType;\n typedef PDELab::GridFunctionSpace GridFunctionSpaceType;\n typedef typename PDELab::BackendVectorSelector::Type PdelabVectorType;\n\n};\n\ntemplate \nstd::shared_ptr make_df_ptr(const std::string name, const typename T::DiscreteFunctionSpaceType& space) {\n return std::make_shared(name, space);\n \/\/ return DSC::make_unique(name, space);\n}\n\n} \/\/ namespace Multiscale\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_MULTISCALE_COMMON_TRAITS_HH\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_COMMON_FVECTOR_HH\n#define DUNE_STUFF_COMMON_FVECTOR_HH\n\n#include \n#include \n\n#include \n# include \n#include \n\n#include \n#include \n\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\ntemplate< class K, int SIZE >\nclass FieldVector\n : public Dune::FieldVector< K, SIZE >\n{\n typedef Dune::FieldVector< K, SIZE > BaseType;\n typedef FieldVector< K, SIZE > ThisType;\n\npublic:\n FieldVector(const K kk = K(0))\n : BaseType(kk)\n {}\n\n FieldVector(const size_t UNUSED_UNLESS_DEBUG(sz), const K kk)\n : BaseType(kk)\n {\n#ifndef NDEBUG\n if (sz != SIZE)\n DUNE_THROW(Exceptions::wrong_input_given,\n \"You are trying to construct a FieldVector< ..., \" << SIZE << \" > (of \" << \"static size) with \" << sz\n << \" elements!\");\n#endif \/\/ NDEBUG\n } \/\/ ... FieldVector(...)\n\n FieldVector(const BaseType& other)\n : BaseType(other)\n {}\n\n FieldVector(const std::vector< K >& vec)\n : BaseType(K(0))\n {\n#ifndef NDEBUG\n if (vec.size() != SIZE)\n DUNE_THROW(Exceptions::wrong_input_given,\n \"You are trying to construct a FieldVector< ..., \" << SIZE << \" > (of \"\n << \"static size) from a vector of size \" << vec.size() << \"!\");\n#endif \/\/ NDEBUG\n for (size_t ii = 0; ii < SIZE; ++ii)\n this->operator[](ii) = vec[ii];\n } \/\/ FieldVector(...)\n\n FieldVector(std::initializer_list< K > list)\n : BaseType(K(0))\n {\n#ifndef NDEBUG\n if (list.size() != SIZE)\n DUNE_THROW(Exceptions::wrong_input_given,\n \"You are trying to construct a FieldVector< ..., \" << SIZE << \" > (of \"\n << \"static size) from a list of size \" << list.size() << \"!\");\n#endif \/\/ NDEBUG\n size_t ii = 0;\n for (auto element : list) {\n this->operator[](ii) = element;\n ++ii;\n }\n } \/\/ FieldVector(...)\n\n ThisType& operator=(const BaseType& other)\n {\n return BaseType::operator=(other);\n }\n}; \/\/ class FieldVector\n\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_COMMON_FVECTOR_HH\n[common.fvector] fixed operator=\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_COMMON_FVECTOR_HH\n#define DUNE_STUFF_COMMON_FVECTOR_HH\n\n#include \n#include \n\n#include \n# include \n#include \n\n#include \n#include \n\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\ntemplate< class K, int SIZE >\nclass FieldVector\n : public Dune::FieldVector< K, SIZE >\n{\n typedef Dune::FieldVector< K, SIZE > BaseType;\n typedef FieldVector< K, SIZE > ThisType;\n\npublic:\n FieldVector(const K kk = K(0))\n : BaseType(kk)\n {}\n\n FieldVector(const size_t UNUSED_UNLESS_DEBUG(sz), const K kk)\n : BaseType(kk)\n {\n#ifndef NDEBUG\n if (sz != SIZE)\n DUNE_THROW(Exceptions::wrong_input_given,\n \"You are trying to construct a FieldVector< ..., \" << SIZE << \" > (of \" << \"static size) with \" << sz\n << \" elements!\");\n#endif \/\/ NDEBUG\n } \/\/ ... FieldVector(...)\n\n FieldVector(const BaseType& other)\n : BaseType(other)\n {}\n\n FieldVector(const std::vector< K >& vec)\n : BaseType(K(0))\n {\n#ifndef NDEBUG\n if (vec.size() != SIZE)\n DUNE_THROW(Exceptions::wrong_input_given,\n \"You are trying to construct a FieldVector< ..., \" << SIZE << \" > (of \"\n << \"static size) from a vector of size \" << vec.size() << \"!\");\n#endif \/\/ NDEBUG\n for (size_t ii = 0; ii < SIZE; ++ii)\n this->operator[](ii) = vec[ii];\n } \/\/ FieldVector(...)\n\n FieldVector(std::initializer_list< K > list)\n : BaseType(K(0))\n {\n#ifndef NDEBUG\n if (list.size() != SIZE)\n DUNE_THROW(Exceptions::wrong_input_given,\n \"You are trying to construct a FieldVector< ..., \" << SIZE << \" > (of \"\n << \"static size) from a list of size \" << list.size() << \"!\");\n#endif \/\/ NDEBUG\n size_t ii = 0;\n for (auto element : list) {\n this->operator[](ii) = element;\n ++ii;\n }\n } \/\/ FieldVector(...)\n\n ThisType& operator=(const BaseType& other)\n {\n BaseType::operator=(other);\n return *this;\n }\n}; \/\/ class FieldVector\n\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_COMMON_FVECTOR_HH\n<|endoftext|>"} {"text":"\/**\n * \\file stuff.hh\n * \\brief contains some stuff\n **\/\n#ifndef DUNE_STUFF_COMMON_STRING_HH\n#define DUNE_STUFF_COMMON_STRING_HH\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\/\/! simple and dumb std::string to anything conversion\ntemplate< class ReturnType >\ninline ReturnType fromString(const std::string& s) {\n return boost::lexical_cast(s);\n} \/\/ fromString\n\n\/\/! simple and dumb anything to std::string conversion\ntemplate< class ReturnType >\ninline std::string toString(const ReturnType& s) {\n return boost::lexical_cast(s);\n} \/\/ toString\n\n\/**\n \\brief Returns a string of lengths s' whitespace (or c chars).\n \\param[in] s\n std::string, defines the length of the return string\n \\param[in] whitespace\n char, optional argument, defines entries of return string\n \\return std::string\n Returns a string of lengths s' whitespace (or c chars).\n **\/\ntemplate< class T >\nstd::string whitespaceify(const T& t, const char whitespace = ' ')\n{\n const std::string s = toString< T >(t);\n std::string ret = \"\";\n for (unsigned int i = 0; i < s.size(); ++i) {\n ret += whitespace;\n }\n return ret;\n} \/\/ std::string whitespaceify(const std::string s, const char whitespace = ' ')\n\n\/** \\brief convenience wrapper around boost::algorithm::split to split one string into a vector of strings\n * \\param msg the spring to be split\n * \\param seperators a list of seperaors, duh\n * \\param mode token_compress_off --> potentially empty strings in return,\n token_compress_on --> empty tokens are discarded\n * \\return all tokens in a vector, if msg contains no seperators, this'll contain msg as its only element\n **\/\ntemplate < class T = std::string >\ninline std::vector tokenize( const std::string& msg,\n const std::string& seperators,\n const boost::algorithm::token_compress_mode_type mode = boost::algorithm::token_compress_off )\n{\n std::vector strings;\n boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),\n mode );\n std::vector ret(strings.size());\n size_t i = 0;\n \/\/special case for empty strings to avoid non-default init\n std::generate(std::begin(ret), std::end(ret), [&] (){ return strings[i++].empty() ? T() : fromString(strings[i-1]); });\n return ret;\n}\n\ntemplate < >\ninline std::vector tokenize( const std::string& msg,\n const std::string& seperators,\n const boost::algorithm::token_compress_mode_type mode )\n{\n std::vector strings;\n boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),\n mode );\n return strings;\n}\n\n\n\/\/! returns string with local time in current locale's format\ninline std::string stringFromTime(time_t cur_time = time(NULL)) {\n return ctime(&cur_time);\n}\n\n\/\/! helper struct for lexical cast\ntemplate \nstruct HexToString {\n \/\/ see http:\/\/stackoverflow.com\/a\/2079728\n ElemT value;\n operator ElemT() const {return value;}\n friend std::istream& operator>>(std::istream& in, HexToString& out) {\n in >> std::hex >> out.value;\n return in;\n }\n};\n\n\/\/ some legacy stuff I'd like to keep for a while\nnamespace String {\n\ntemplate< class T >\nDUNE_DEPRECATED_MSG(\"use DSC::fromString instead, removal with stuff 2.3\") T from(const std::string& s)\n{\n std::stringstream ss;\n ss << s;\n T t;\n ss >> t;\n return t;\n}\n\ntemplate< class T >\nDUNE_DEPRECATED_MSG(\"use DSC::toString instead, removal with stuff 2.3\") std::string to(const T& t)\n{\n std::stringstream ss;\n ss << t;\n std::string s;\n ss >> s;\n return s;\n}\n\nDUNE_DEPRECATED_MSG(\"use the constructor call directly\")\ninline std::vector< std::string > mainArgsToVector(int argc, char** argv)\n{\n return std::vector< std::string >(argv, argv + argc);\n}\n\ninline char** vectorToMainArgs(const std::vector< std::string > args)\n{\n char** argv = new char* [args.size()];\n for (unsigned int ii = 0; ii < args.size(); ++ii) {\n argv[ii] = new char[args[ii].length() + 1];\n strcpy(argv[ii], args[ii].c_str());\n }\n return argv;\n} \/\/ char** vectorToMainArgs(const std::vector< std::string > args)\n\n} \/\/ namespace String\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_COMMON_STRING_HH\n\n\/** Copyright (c) 2012, Rene Milk , Sven Kaulmann\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the FreeBSD Project.\n **\/\n[common] rewire to\/from string\/**\n * \\file stuff.hh\n * \\brief contains some stuff\n **\/\n#ifndef DUNE_STUFF_COMMON_STRING_HH\n#define DUNE_STUFF_COMMON_STRING_HH\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\/\/! simple and dumb std::string to anything conversion\ntemplate< class ReturnType >\ninline ReturnType fromString(const std::string s) {\n return boost::lexical_cast(s);\n} \/\/ fromString\n\n\ninline std::string toString(const char* s) {\n return std::string(s);\n} \/\/ toString\n\ninline std::string toString(const std::string s) {\n return std::string(s);\n} \/\/ toString\n\n\/\/! simple and dumb anything to std::string conversion\ntemplate< class ReturnType >\ninline std::string toString(const ReturnType& s) {\n return std::to_string(s);\n} \/\/ toString\n\n\n#define DSC_TOSTR(tn,tns) \\\ntemplate<> \\\ninline tn fromString(const std::string s) { \\\n return std::sto##tns(s); \\\n}\n\nDSC_TOSTR(int, i)\nDSC_TOSTR(long, l)\nDSC_TOSTR(long long, ll)\nDSC_TOSTR(unsigned long, ul)\nDSC_TOSTR(unsigned long long, ull)\nDSC_TOSTR(float,f)\nDSC_TOSTR(double,d)\nDSC_TOSTR(long double,ld)\n\n#undef DSC_TOSTR\n\n\n\n\/**\n \\brief Returns a string of lengths s' whitespace (or c chars).\n \\param[in] s\n std::string, defines the length of the return string\n \\param[in] whitespace\n char, optional argument, defines entries of return string\n \\return std::string\n Returns a string of lengths s' whitespace (or c chars).\n **\/\ntemplate< class T >\nstd::string whitespaceify(const T& t, const char whitespace = ' ')\n{\n const std::string s = toString< T >(t);\n std::string ret = \"\";\n for (unsigned int i = 0; i < s.size(); ++i) {\n ret += whitespace;\n }\n return ret;\n} \/\/ std::string whitespaceify(const std::string s, const char whitespace = ' ')\n\n\/** \\brief convenience wrapper around boost::algorithm::split to split one string into a vector of strings\n * \\param msg the spring to be split\n * \\param seperators a list of seperaors, duh\n * \\param mode token_compress_off --> potentially empty strings in return,\n token_compress_on --> empty tokens are discarded\n * \\return all tokens in a vector, if msg contains no seperators, this'll contain msg as its only element\n **\/\ntemplate < class T = std::string >\ninline std::vector tokenize( const std::string& msg,\n const std::string& seperators,\n const boost::algorithm::token_compress_mode_type mode = boost::algorithm::token_compress_off )\n{\n std::vector strings;\n boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),\n mode );\n std::vector ret(strings.size());\n size_t i = 0;\n \/\/special case for empty strings to avoid non-default init\n std::generate(std::begin(ret), std::end(ret), [&] (){ return strings[i++].empty() ? T() : fromString(strings[i-1]); });\n return ret;\n}\n\ntemplate < >\ninline std::vector tokenize( const std::string& msg,\n const std::string& seperators,\n const boost::algorithm::token_compress_mode_type mode )\n{\n std::vector strings;\n boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),\n mode );\n return strings;\n}\n\n\n\/\/! returns string with local time in current locale's format\ninline std::string stringFromTime(time_t cur_time = time(NULL)) {\n return ctime(&cur_time);\n}\n\n\/\/! helper struct for lexical cast\ntemplate \nstruct HexToString {\n \/\/ see http:\/\/stackoverflow.com\/a\/2079728\n ElemT value;\n operator ElemT() const {return value;}\n friend std::istream& operator>>(std::istream& in, HexToString& out) {\n in >> std::hex >> out.value;\n return in;\n }\n};\n\n\/\/ some legacy stuff I'd like to keep for a while\nnamespace String {\n\ntemplate< class T >\nDUNE_DEPRECATED_MSG(\"use DSC::fromString instead, removal with stuff 2.3\") T from(const std::string& s)\n{\n std::stringstream ss;\n ss << s;\n T t;\n ss >> t;\n return t;\n}\n\ntemplate< class T >\nDUNE_DEPRECATED_MSG(\"use DSC::toString instead, removal with stuff 2.3\") std::string to(const T& t)\n{\n std::stringstream ss;\n ss << t;\n std::string s;\n ss >> s;\n return s;\n}\n\nDUNE_DEPRECATED_MSG(\"use the constructor call directly\")\ninline std::vector< std::string > mainArgsToVector(int argc, char** argv)\n{\n return std::vector< std::string >(argv, argv + argc);\n}\n\ninline char** vectorToMainArgs(const std::vector< std::string > args)\n{\n char** argv = new char* [args.size()];\n for (unsigned int ii = 0; ii < args.size(); ++ii) {\n argv[ii] = new char[args[ii].length() + 1];\n strcpy(argv[ii], args[ii].c_str());\n }\n return argv;\n} \/\/ char** vectorToMainArgs(const std::vector< std::string > args)\n\n} \/\/ namespace String\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_COMMON_STRING_HH\n\n\/** Copyright (c) 2012, Rene Milk , Sven Kaulmann\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the FreeBSD Project.\n **\/\n<|endoftext|>"} {"text":"#ifndef DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH\n#define DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH\n\n#include \n\n\/\/ dune-common\n#include \n\nnamespace Dune {\n\nnamespace Stuff {\n\nnamespace Common {\n\n\/\/template< class T, class stream = std::ostream >\n\/\/void print(const T& arg, stream& out = std::cout, std::string name = \"\", std::string prefix = \"\") {\n\/\/ out << prefix;\n\/\/ if (!name.empty())\n\/\/ out << name << \" = \";\n\/\/ out << \"[\";\n\/\/ for (unsigned int i = 0; i < (arg.size() - 1); ++i)\n\/\/ {\n\/\/ out << arg[i] << \", \";\n\/\/ }\n\/\/ out << arg[arg.size() - 1] << \"]\" << std::endl;\n\/\/}\n\ntemplate< class VectorImp >\nvoid clear(Dune::DenseVector< VectorImp >& vector)\n{\n vector = typename Dune::DenseVector< VectorImp >::value_type(0);\n\/\/ typedef typename DenseVectorType::value_type\n\/\/ ValueType;\n\n\/\/ const unsigned int size = vector.size();\n\/\/ for( unsigned int i = 0; i < size; ++i )\n\/\/ {\n\/\/ vector[i] = ValueType(0.0);\n\/\/ }\n} \/\/ void clear( DenseVectorType& vector )\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH\n[common.vector] added resize() for Dune::DynamicVector#ifndef DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH\n#define DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH\n\n#include \n\n\/\/ dune-common\n#include \n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\n\/\/template< class T, class stream = std::ostream >\n\/\/void print(const T& arg, stream& out = std::cout, std::string name = \"\", std::string prefix = \"\") {\n\/\/ out << prefix;\n\/\/ if (!name.empty())\n\/\/ out << name << \" = \";\n\/\/ out << \"[\";\n\/\/ for (unsigned int i = 0; i < (arg.size() - 1); ++i)\n\/\/ {\n\/\/ out << arg[i] << \", \";\n\/\/ }\n\/\/ out << arg[arg.size() - 1] << \"]\" << std::endl;\n\/\/}\n\n\ntemplate< class VectorImp >\nvoid clear(Dune::DenseVector< VectorImp >& vector)\n{\n vector = typename Dune::DenseVector< VectorImp >::value_type(0);\n\/\/ typedef typename DenseVectorType::value_type\n\/\/ ValueType;\n\n\/\/ const unsigned int size = vector.size();\n\/\/ for( unsigned int i = 0; i < size; ++i )\n\/\/ {\n\/\/ vector[i] = ValueType(0.0);\n\/\/ }\n} \/\/ void clear( DenseVectorType& vector )\n\n\ntemplate< class T >\nDune::DynamicVector< T > resize(const Dune::DynamicVector< T >& inVector,\n const size_t newSize,\n const T fill = T(0))\n{\n Dune::DynamicVector< T > outVector(newSize);\n for (size_t ii = 0; ii < std::min(inVector.size(), newSize); ++ii)\n outVector[ii] = inVector[ii];\n for (size_t ii = std::min(inVector.size(), newSize); ii < newSize; ++ii)\n outVector[ii] = fill;\n return outVector;\n}\n\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_TOOLS_COMMON_VEECTOR_HH\n<|endoftext|>"} {"text":"#ifndef DUNE_STUFF_GRID_PROVIDER_HH\n#define DUNE_STUFF_GRID_PROVIDER_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#if HAVE_DUNE_GRID\n\n#include \"provider\/interface.hh\"\n#include \"provider\/cube.hh\"\n#include \"provider\/gmsh.hh\"\n#include \"provider\/starcd.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Grid {\nnamespace Provider {\n\n\nstd::vector< std::string > types()\n{\n std::vector< std::string > ret;\n ret.push_back(\"stuff.grid.provider.cube\");\n#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n ret.push_back(\"stuff.grid.provider.gmsh\");\n#endif \/\/ defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n#endif \/\/ HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n ret.push_back(\"stuff.grid.provider.starcd\");\n return ret;\n} \/\/ std::vector< const std::string > types()\n\n\n#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\ntemplate< class GridType = Dune::GridSelector::GridType >\n#else \/\/ defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\ntemplate< class GridType = Dune::SGrid< 2, 2 > >\n#endif \/\/ defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\nDune::ParameterTree createSampleDescription(const std::string type)\n{\n if (type == \"stuff.grid.provider.cube\") {\n typedef Dune::Stuff::Grid::Provider::Cube< GridType > ProviderType;\n return ProviderType::createSampleDescription();\n#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n } else if (type == \"stuff.grid.provider.gmsh\") {\n typedef Dune::Stuff::Grid::Provider::Gmsh< GridType > ProviderType;\n return ProviderType::createSampleDescription();\n#endif \/\/ defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n#endif \/\/ HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n } else if (type == \"stuff.grid.provider.starcd\") {\n typedef Dune::Stuff::Grid::Provider::StarCD< GridType > ProviderType;\n return ProviderType::createSampleDescription();\n } else\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" unknown grid provider '\" << type << \"' requested!\");\n} \/\/ ... create(...)\n\n\n#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\ntemplate< class GridType = Dune::GridSelector::GridType >\n#else \/\/ defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\ntemplate< class GridType = Dune::SGrid< 2, 2 > >\n#endif \/\/ defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\nInterface< GridType >* create(const std::string& type = \"stuff.grid.provider.cube\", const Dune::ParameterTree paramTree = Dune::ParameterTree())\n{\n \/\/ choose provider\n if (type == \"stuff.grid.provider.cube\") {\n typedef Dune::Stuff::Grid::Provider::Cube< GridType > CubeProviderType;\n CubeProviderType* cubeProvider = new CubeProviderType(CubeProviderType::createFromDescription(paramTree));\n return cubeProvider;\n#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n } else if (type == \"stuff.grid.provider.gmsh\") {\n typedef Dune::Stuff::Grid::Provider::Gmsh< GridType > GmshProviderType;\n GmshProviderType* gmshProvider = new GmshProviderType(GmshProviderType::createFromDescription(paramTree));\n return gmshProvider;\n#endif \/\/ defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n#endif \/\/ HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n } else if (type == \"stuff.grid.provider.starcd\") {\n typedef Dune::Stuff::Grid::Provider::StarCD< GridType > StarCDProviderType;\n StarCDProviderType* starCDProvider = new StarCDProviderType(StarCDProviderType::createFromDescription(paramTree));\n return starCDProvider;\n } else\n DUNE_THROW(Dune::RangeError,\n \"\\nERROR: unknown grid provider '\" << type << \"' requested!\");\n} \/\/ Interface< GridImp >* create(const std::string& type, const Dune::ParameterTree paramTree = Dune::ParameterTree())\n\n} \/\/ namespace Provider\n} \/\/ namespace Grid\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ HAVE_DUNE_GRID\n\n#endif \/\/ DUNE_STUFF_GRID_PROVIDER_HH\n[grid] cleanup\/simplify provider.hh#ifndef DUNE_STUFF_GRID_PROVIDER_HH\n#define DUNE_STUFF_GRID_PROVIDER_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#if HAVE_DUNE_GRID\n\n#include \n#include \n#include \n\n#include \"provider\/interface.hh\"\n#include \"provider\/cube.hh\"\n#include \"provider\/gmsh.hh\"\n#include \"provider\/starcd.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Grid {\nnamespace Provider {\n\n\nstd::vector< std::string > types()\n{\n std::vector< std::string > ret;\n ret.push_back(\"stuff.grid.provider.cube\");\n#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n ret.push_back(\"stuff.grid.provider.gmsh\");\n#endif \/\/ defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n#endif \/\/ HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n ret.push_back(\"stuff.grid.provider.starcd\");\n return ret;\n} \/\/ std::vector< const std::string > types()\n\n\n#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\ntemplate< class GridType = Dune::GridSelector::GridType >\n#else \/\/ defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\ntemplate< class GridType = Dune::SGrid< 2, 2 > >\n#endif \/\/ defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\nDune::ParameterTree createSampleDescription(const std::string type)\n{\n if (type == \"stuff.grid.provider.cube\") {\n typedef Dune::Stuff::Grid::Provider::Cube< GridType > ProviderType;\n return ProviderType::createSampleDescription();\n#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n } else if (type == \"stuff.grid.provider.gmsh\") {\n typedef Dune::Stuff::Grid::Provider::Gmsh< GridType > ProviderType;\n return ProviderType::createSampleDescription();\n#endif \/\/ defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n#endif \/\/ HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n } else if (type == \"stuff.grid.provider.starcd\") {\n typedef Dune::Stuff::Grid::Provider::StarCD< GridType > ProviderType;\n return ProviderType::createSampleDescription();\n } else\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" unknown grid provider '\" << type << \"' requested!\");\n} \/\/ ... create(...)\n\n\n#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\ntemplate< class GridType = Dune::GridSelector::GridType >\n#else \/\/ defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\ntemplate< class GridType = Dune::SGrid< 2, 2 > >\n#endif \/\/ defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\nInterface< GridType >* create(const std::string& type = \"stuff.grid.provider.cube\", const Dune::ParameterTree paramTree = Dune::ParameterTree())\n{\n using namespace DSG::Provider;\n typedef std::map::Type>> MapType;\n\n MapType ptr_map = { {\"stuff.grid.provider.cube\", DSGP_MAKE(GenericCube)},\n#ifdef HAVE_UNSTRUCTURED_GRIDFACTORY\n {\"stuff.grid.provider.gmsh\", DSGP_MAKE(Gmsh)},\n#endif\n {\"stuff.grid.provider.starcd\",DSGP_MAKE(StarCD)}};\n auto id_func_it = ptr_map.find(type);\n if(id_func_it == ptr_map.end())\n DUNE_THROW(Dune::RangeError, \"\\nERROR: unknown grid provider '\" << type << \"' requested!\");\n auto id_func = id_func_it->second;\n return id_func.second(id_func.first);\n} \/\/ Interface< GridImp >* create(const std::string& type, const Dune::ParameterTree paramTree = Dune::ParameterTree())\n\n} \/\/ namespace Provider\n} \/\/ namespace Grid\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ HAVE_DUNE_GRID\n\n#endif \/\/ DUNE_STUFF_GRID_PROVIDER_HH\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2015 SRG Technology, LLC\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"anyrpc\/api.h\"\n#include \"anyrpc\/logger.h\"\n#include \"anyrpc\/error.h\"\n#include \"anyrpc\/value.h\"\n#include \"anyrpc\/stream.h\"\n#include \"anyrpc\/handler.h\"\n#include \"anyrpc\/reader.h\"\n#include \"anyrpc\/document.h\"\n#include \"anyrpc\/method.h\"\n#include \"anyrpc\/socket.h\"\n#include \"anyrpc\/client.h\"\n#include \"anyrpc\/internal\/time.h\"\n\nnamespace anyrpc\n{\n\n#if defined(ANYRPC_THREADING)\nstd::atomic ClientHandler::nextId_(1);\n#else\nunsigned ClientHandler::nextId_ = 1;\n#endif \/\/ defined(ANYRPC_THREADING)\n\nint ClientHandler::GetNextId()\n{\n return nextId_++;\n}\n\nvoid ClientHandler::GenerateFaultResult(int errorCode, std::string const& errorMsg, Value& result)\n{\n result[\"code\"] = errorCode;\n result[\"message\"] = errorMsg;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClient::Client(ClientHandler* handler)\n{\n handler_ = handler;\n port_ = 0;\n timeout_ = 60000;\n responseAllocated_ = false;\n responseProcessed_ = false;\n ResetReceiveBuffer();\n ResetTransaction();\n}\n\nClient::Client(ClientHandler* handler, const char* host, int port)\n{\n handler_ = handler;\n host_ = host;\n port_ = port;\n timeout_ = 60000;\n responseAllocated_ = false;\n responseProcessed_ = false;\n ResetReceiveBuffer();\n ResetTransaction();\n}\n\nClient::~Client()\n{\n if (responseAllocated_)\n free(response_);\n Close();\n}\n\nbool Client::Call(const char* method, Value& params, Value& result)\n{\n log_trace();\n gettimeofday( &startTime_, 0 );\n result.SetInvalid();\n\n PreserveReceiveBuffer();\n ResetTransaction();\n\n if (Connect(result) &&\n GenerateRequest(method, params) &&\n GenerateHeader())\n {\n if (!WriteRequest(result))\n {\n \/\/ retry the connection\n Close();\n if (!Connect(result) ||\n !WriteRequest(result))\n {\n Reset();\n return false;\n }\n }\n \/\/ continue with the processing\n if (ReadHeader(result) &&\n ReadResponse(result))\n {\n switch (ProcessResponse(result))\n {\n case ProcessResponseSuccess : return true;\n case ProcessResponseErrorKeepOpen : return false;\n }\n }\n }\n Reset();\n return false;\n}\n\nbool Client::Post(const char* method, Value& params, Value& result)\n{\n log_trace();\n gettimeofday( &startTime_, 0 );\n result.SetInvalid();\n\n PreserveReceiveBuffer();\n ResetTransaction();\n\n if (Connect(result) &&\n GenerateRequest(method, params) &&\n GenerateHeader())\n {\n if (!WriteRequest(result))\n {\n \/\/ retry the connection\n Close();\n if (!Connect(result) ||\n !WriteRequest(result))\n {\n Reset();\n return false;\n }\n }\n return true;\n }\n Reset();\n return false;\n}\n\nbool Client::GetPostResult(Value& result)\n{\n log_trace();\n gettimeofday( &startTime_, 0 );\n result.SetInvalid();\n\n if (responseProcessed_)\n {\n PreserveReceiveBuffer();\n ResetTransaction();\n }\n\n if (socket_.IsConnected(0) &&\n ReadHeader(result) &&\n ReadResponse(result))\n {\n switch (ProcessResponse(result))\n {\n case ProcessResponseSuccess : return true;\n case ProcessResponseErrorKeepOpen : return false;\n }\n }\n\n Reset();\n return false;\n}\n\nbool Client::Notify(const char* method, Value& params, Value& result)\n{\n log_trace();\n gettimeofday( &startTime_, 0 );\n result.SetInvalid();\n\n PreserveReceiveBuffer();\n ResetTransaction();\n\n if (Connect(result) &&\n GenerateRequest(method, params, true) &&\n GenerateHeader())\n {\n if (!WriteRequest(result))\n {\n \/\/ retry the connection\n Close();\n if (!Connect(result) ||\n !WriteRequest(result))\n {\n Reset();\n return false;\n }\n }\n \/\/ Not all notification require a response\n if (!TransportHasNotifyResponse())\n {\n requestId_.pop_front();\n return true;\n }\n \/\/ continue with the processing response\n if (ReadHeader(result) &&\n ReadResponse(result))\n {\n \/\/ don't process the response for a notification\n requestId_.pop_front();\n result.SetNull();\n return true;\n }\n }\n Reset();\n return false;\n}\n\nvoid Client::Reset()\n{\n Close();\n ResetReceiveBuffer();\n ResetTransaction();\n requestId_.clear();\n}\n\nvoid Client::ResetTransaction()\n{\n contentLength_ = 0;\n if (responseAllocated_)\n free(response_);\n response_ = 0;\n responseAllocated_ = false;\n responseProcessed_ = false;\n contentAvail_ = 0;\n header_.Clear();\n request_.Clear();\n}\n\nvoid Client::PreserveReceiveBuffer()\n{\n \/\/ only need to consider preserving data if we didn't need to allocate a new buffer\n \/\/ if a new buffer was allocated, then only the required data would be read\n if (!responseAllocated_)\n {\n if (response_ != 0)\n {\n \/\/ a response was processed so there might be data left in the buffer\n if (contentAvail_ > contentLength_)\n {\n \/\/ there is data left in the buffer move it to the start of the buffer\n char* responseEnd = response_ + contentLength_;\n size_t dataRemaining = contentAvail_ - contentLength_;\n log_debug(\"PreserveReceiveBuffer: Preserve data: \" << dataRemaining << \" bytes\");\n memmove(buffer_, responseEnd, dataRemaining);\n bufferLength_ = dataRemaining;\n }\n else\n {\n log_debug(\"PreserveReceiveBuffer: No data to preserve\");\n bufferLength_ = 0;\n }\n }\n else\n log_debug(\"PreserveReceiveBuffer: Keep any previous data: \" << bufferLength_ << \" bytes\");\n }\n else\n {\n log_debug(\"PreserveReceiveBuffer: Reset buffer\");\n bufferLength_ = 0;\n }\n responseProcessed_ = true;\n}\n\nunsigned Client::GetTimeLeft()\n{\n struct timeval currentTime;\n gettimeofday( ¤tTime, 0 );\n\n int timeUsed = MilliTimeDiff(currentTime,startTime_);\n\n int timeLeft = std::max(0,(int)timeout_ - timeUsed);\n\n log_debug(\"GetTimeLeft: timeout=\" << timeout_ << \", timeLeft=\" << timeLeft << \", timeUsed=\" << timeUsed);\n return timeLeft;\n}\n\nbool Client::Connect(Value& result)\n{\n log_trace();\n if (socket_.IsConnected(0))\n {\n log_debug(\"Already connected\");\n return true;\n }\n \/\/ Close the connection but keep any data that has been setup for the next message\n Close();\n ResetReceiveBuffer();\n\n log_debug(\"Create a new connection\");\n socket_.Create();\n socket_.SetNonBlocking();\n\n socket_.Connect(host_.c_str(), port_);\n\n socket_.SetKeepAlive();\n socket_.SetTcpNoDelay();\n\n if (!socket_.IsConnected(GetTimeLeft()))\n {\n socket_.Close();\n return false;\n }\n return true;\n}\n\nbool Client::GenerateRequest(const char* method, Value& params, bool notification)\n{\n int requestId;\n\n bool result = handler_->GenerateRequest(method,params,request_,requestId,notification);\n requestId_.push_back(requestId);\n return result;\n}\n\nbool Client::WriteRequest(Value& result)\n{\n log_trace();\n\n size_t bytesWritten;\n size_t bytesToSend;\n\n \/\/ write the header - it make be in several segments\n size_t headerBytesWritten = 0;\n while (headerBytesWritten < header_.Length())\n {\n const char* buffer = header_.GetBuffer(headerBytesWritten, bytesToSend);\n if (!socket_.Send(buffer, bytesToSend, bytesWritten, GetTimeLeft()))\n return false;\n\n headerBytesWritten += bytesWritten;\n\n if (bytesToSend < bytesWritten)\n return false; \/\/ timeout\n }\n\n \/\/ write the request - it make be in several segments\n size_t requestBytesWritten = 0;\n while (requestBytesWritten < request_.Length())\n {\n const char* buffer = request_.GetBuffer(requestBytesWritten, bytesToSend);\n if (!socket_.Send(buffer, bytesToSend, bytesWritten, GetTimeLeft()))\n return false;\n\n requestBytesWritten += bytesWritten;\n\n if (bytesToSend < bytesWritten)\n return false; \/\/ timeout\n }\n\n return true;\n}\n\nbool Client::ReadHeader(Value& result)\n{\n log_trace();\n \/\/ Read available data\n socket_.SetTimeout(0);\n while (true)\n {\n int bytesRead;\n bool eof;\n socket_.Receive(buffer_+bufferLength_, MaxBufferLength-bufferLength_, bytesRead, eof, 0);\n if (socket_.FatalError())\n {\n log_warn(\"error while reading header: \" << socket_.GetLastError() << \", bytesRead=\" << bytesRead);\n return false;\n }\n bufferLength_ += bytesRead;\n log_info(\"read=\" << bytesRead << \", total=\" << bufferLength_);\n\n switch (ProcessHeader(eof))\n {\n case HEADER_COMPLETE : return true;\n case HEADER_FAULT : return false;\n }\n unsigned timeLeft = GetTimeLeft();\n if (timeLeft == 0)\n {\n handler_->GenerateFaultResult(AnyRpcErrorTransportError,\"Timeout reading response header\",result);\n break;\n }\n socket_.WaitReadable(timeLeft);\n }\n return false;\n}\n\nbool Client::ReadResponse(Value& result)\n{\n log_trace();\n if (contentAvail_ >= contentLength_)\n return true;\n\n int bytesRead;\n bool eof;\n bool receiveResult = socket_.Receive(response_+contentAvail_, contentLength_-contentAvail_, bytesRead, eof, GetTimeLeft());\n contentAvail_ += bytesRead;\n response_[contentAvail_] = 0;\n if (!receiveResult)\n handler_->GenerateFaultResult(AnyRpcErrorTransportError,\"Failed reading response\",result);\n return receiveResult;\n}\n\nProcessResponseEnum Client::ProcessResponse(Value& result, bool notification)\n{\n int requestId = requestId_.front();\n requestId_.pop_front();\n responseProcessed_ = true;\n return handler_->ProcessResponse(response_,contentLength_,result,requestId,notification);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool HttpClient::GenerateHeader()\n{\n log_trace();\n header_ << \"POST \/RPC2 HTTP\/1.1\\r\\n\";\n header_ << \"User-Agent: \" << ANYRPC_APP_NAME << \" v\" << ANYRPC_VERSION_STRING << \"\\r\\n\";\n header_ << \"Host: \" << host_ << \":\" << port_ << \"\\r\\n\";\n header_ << \"Content-Type: \" << contentType_ << \"\\r\\n\";\n header_ << \"Accept: \" << contentType_ << \"\\r\\n\";\n header_ << \"Content-length: \" << request_.Length() << \"\\r\\n\";\n header_ << \"\\r\\n\";\n\n return true;\n}\n\nint HttpClient::ProcessHeader(bool eof)\n{\n log_trace();\n switch (httpResponseState_.ProcessHeaderData(buffer_, bufferLength_, eof))\n {\n case internal::HttpHeader::HEADER_FAULT : return HEADER_FAULT;\n case internal::HttpHeader::HEADER_INCOMPLETE : return HEADER_INCOMPLETE;\n }\n\n size_t bodyStartPos = httpResponseState_.GetBodyStartPos();\n size_t bufferSpaceAvail = MaxBufferLength - bodyStartPos;\n\n contentLength_ = httpResponseState_.GetContentLength();\n contentAvail_ = bufferLength_ - bodyStartPos;\n \/\/keepAlive_ = httpResponseState_.GetKeepAlive();\n\n if (contentLength_ > MaxContentLength)\n {\n log_warn(\"Content-length too large=\" << contentLength_ << \", max allowed=\" << MaxContentLength);\n return HEADER_FAULT;\n }\n if (contentLength_ > (int)bufferSpaceAvail)\n {\n \/\/ try to malloc the buffer space needed\n response_ = static_cast(malloc(contentLength_+1));\n if (response_ == 0)\n {\n log_warn(\"Could not allocate space=\" << contentLength_);\n return HEADER_FAULT;\n }\n \/\/ copy the content that was already read to the new space\n memcpy(response_,buffer_+bodyStartPos,contentAvail_);\n responseAllocated_ = true;\n }\n else\n {\n responseAllocated_ = false;\n response_ = buffer_ + bodyStartPos;\n }\n response_[contentAvail_] = 0;\n\n log_info(\"specified content length is \" << contentLength_);\n\n return HEADER_COMPLETE;\n}\n\nProcessResponseEnum HttpClient::ProcessResponse(Value& result, bool notification)\n{\n log_trace();\n int requestId = requestId_.front();\n requestId_.pop_front();\n responseProcessed_ = true;\n ProcessResponseEnum processResult = handler_->ProcessResponse(response_,contentLength_,result,requestId,notification);\n if (!httpResponseState_.GetKeepAlive())\n {\n log_info(\"Http response header indicates to close connection\");\n Close();\n }\n return processResult;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool TcpClient::GenerateHeader()\n{\n log_trace();\n header_ << request_.Length() << \":\";\n log_debug(\"Request length=\" << request_.Length());\n\n \/\/ add the comma separator to the request buffer\n request_ << ',';\n\n return true;\n}\n\nint TcpClient::ProcessHeader(bool eof)\n{\n \/\/ search for the length\/body separator, ':'\n char* body = 0;\n char* header = buffer_;\n char* end = buffer_ + bufferLength_;\n for (char* current = buffer_; current < end; current++)\n {\n if (*current == ':')\n {\n body = current + 1;\n break;\n }\n }\n\n \/\/ If we haven't gotten the entire header yet, return (keep reading)\n if (body == 0)\n {\n \/\/ EOF in the middle of a request is an error, otherwise its ok\n if (eof)\n {\n log_warn(\"EOF while reading header\");\n return HEADER_FAULT;\n }\n return HEADER_INCOMPLETE; \/\/ Keep reading\n }\n\n \/\/ check for comma separator\n if (commaExpected_)\n {\n if (*header != ',')\n {\n log_warn(\"Expected comma to separate messages\");\n log_warn(\"bufferLength=\" << bufferLength_ << \", buffer=\" << buffer_);\n return HEADER_FAULT;\n }\n header++;\n }\n\n contentLength_ = atoi(header);\n if (contentLength_ <= 0)\n {\n log_warn(\"Invalid string length specified \" << contentLength_);\n log_warn(\"bufferLength=\" << bufferLength_ << \", buffer=\" << buffer_);\n return HEADER_FAULT;\n }\n\n int bufferSpaceAvail = buffer_ + MaxBufferLength - body;\n contentAvail_ = end - body;\n\n if (contentLength_ > MaxContentLength)\n {\n log_warn(\"String length too large=\" << contentLength_ << \", max allowed=\" << MaxContentLength);\n return HEADER_FAULT;\n }\n if (contentLength_ > bufferSpaceAvail)\n {\n \/\/ try to malloc the buffer space needed\n response_ = static_cast(malloc(contentLength_+1));\n if (response_ == 0)\n {\n log_warn(\"Could not allocate space=\" << contentLength_);\n return HEADER_FAULT;\n }\n \/\/ copy the content that was already read to the new space\n memcpy(response_,body,contentAvail_);\n responseAllocated_ = true;\n }\n else\n {\n responseAllocated_ = false;\n response_ = body;\n }\n response_[contentAvail_] = 0;\n log_info(\"specified content length is \" << contentLength_);\n\n \/\/ a comma is expected to separate the next message\n commaExpected_ = true;\n\n return HEADER_COMPLETE;\n}\n\n} \/\/ namespace anyrpc\nFixed two crash bugs: If the response is NULL for some reasons anyrpc will crashs\/\/ Copyright (C) 2015 SRG Technology, LLC\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"anyrpc\/api.h\"\n#include \"anyrpc\/logger.h\"\n#include \"anyrpc\/error.h\"\n#include \"anyrpc\/value.h\"\n#include \"anyrpc\/stream.h\"\n#include \"anyrpc\/handler.h\"\n#include \"anyrpc\/reader.h\"\n#include \"anyrpc\/document.h\"\n#include \"anyrpc\/method.h\"\n#include \"anyrpc\/socket.h\"\n#include \"anyrpc\/client.h\"\n#include \"anyrpc\/internal\/time.h\"\n\nnamespace anyrpc\n{\n\n#if defined(ANYRPC_THREADING)\nstd::atomic ClientHandler::nextId_(1);\n#else\nunsigned ClientHandler::nextId_ = 1;\n#endif \/\/ defined(ANYRPC_THREADING)\n\nint ClientHandler::GetNextId()\n{\n return nextId_++;\n}\n\nvoid ClientHandler::GenerateFaultResult(int errorCode, std::string const& errorMsg, Value& result)\n{\n result[\"code\"] = errorCode;\n result[\"message\"] = errorMsg;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClient::Client(ClientHandler* handler)\n{\n handler_ = handler;\n port_ = 0;\n timeout_ = 60000;\n responseAllocated_ = false;\n responseProcessed_ = false;\n ResetReceiveBuffer();\n ResetTransaction();\n}\n\nClient::Client(ClientHandler* handler, const char* host, int port)\n{\n handler_ = handler;\n host_ = host;\n port_ = port;\n timeout_ = 60000;\n responseAllocated_ = false;\n responseProcessed_ = false;\n ResetReceiveBuffer();\n ResetTransaction();\n}\n\nClient::~Client()\n{\n if (responseAllocated_)\n free(response_);\n Close();\n}\n\nbool Client::Call(const char* method, Value& params, Value& result)\n{\n log_trace();\n gettimeofday( &startTime_, 0 );\n result.SetInvalid();\n\n PreserveReceiveBuffer();\n ResetTransaction();\n\n if (Connect(result) &&\n GenerateRequest(method, params) &&\n GenerateHeader())\n {\n if (!WriteRequest(result))\n {\n \/\/ retry the connection\n Close();\n if (!Connect(result) ||\n !WriteRequest(result))\n {\n Reset();\n return false;\n }\n }\n \/\/ continue with the processing\n if (ReadHeader(result) &&\n ReadResponse(result))\n {\n switch (ProcessResponse(result))\n {\n case ProcessResponseSuccess : return true;\n case ProcessResponseErrorKeepOpen : return false;\n }\n }\n }\n Reset();\n return false;\n}\n\nbool Client::Post(const char* method, Value& params, Value& result)\n{\n log_trace();\n gettimeofday( &startTime_, 0 );\n result.SetInvalid();\n\n PreserveReceiveBuffer();\n ResetTransaction();\n\n if (Connect(result) &&\n GenerateRequest(method, params) &&\n GenerateHeader())\n {\n if (!WriteRequest(result))\n {\n \/\/ retry the connection\n Close();\n if (!Connect(result) ||\n !WriteRequest(result))\n {\n Reset();\n return false;\n }\n }\n return true;\n }\n Reset();\n return false;\n}\n\nbool Client::GetPostResult(Value& result)\n{\n log_trace();\n gettimeofday( &startTime_, 0 );\n result.SetInvalid();\n\n if (responseProcessed_)\n {\n PreserveReceiveBuffer();\n ResetTransaction();\n }\n\n if (socket_.IsConnected(0) &&\n ReadHeader(result) &&\n ReadResponse(result))\n {\n switch (ProcessResponse(result))\n {\n case ProcessResponseSuccess : return true;\n case ProcessResponseErrorKeepOpen : return false;\n }\n }\n\n Reset();\n return false;\n}\n\nbool Client::Notify(const char* method, Value& params, Value& result)\n{\n log_trace();\n gettimeofday( &startTime_, 0 );\n result.SetInvalid();\n\n PreserveReceiveBuffer();\n ResetTransaction();\n\n if (Connect(result) &&\n GenerateRequest(method, params, true) &&\n GenerateHeader())\n {\n if (!WriteRequest(result))\n {\n \/\/ retry the connection\n Close();\n if (!Connect(result) ||\n !WriteRequest(result))\n {\n Reset();\n return false;\n }\n }\n \/\/ Not all notification require a response\n if (!TransportHasNotifyResponse())\n {\n requestId_.pop_front();\n return true;\n }\n \/\/ continue with the processing response\n if (ReadHeader(result) &&\n ReadResponse(result))\n {\n \/\/ don't process the response for a notification\n requestId_.pop_front();\n result.SetNull();\n return true;\n }\n }\n Reset();\n return false;\n}\n\nvoid Client::Reset()\n{\n Close();\n ResetReceiveBuffer();\n ResetTransaction();\n requestId_.clear();\n}\n\nvoid Client::ResetTransaction()\n{\n contentLength_ = 0;\n if (responseAllocated_)\n free(response_);\n response_ = 0;\n responseAllocated_ = false;\n responseProcessed_ = false;\n contentAvail_ = 0;\n header_.Clear();\n request_.Clear();\n}\n\nvoid Client::PreserveReceiveBuffer()\n{\n \/\/ only need to consider preserving data if we didn't need to allocate a new buffer\n \/\/ if a new buffer was allocated, then only the required data would be read\n if (!responseAllocated_)\n {\n if (response_ != 0)\n {\n \/\/ a response was processed so there might be data left in the buffer\n if (contentAvail_ > contentLength_)\n {\n \/\/ there is data left in the buffer move it to the start of the buffer\n char* responseEnd = response_ + contentLength_;\n size_t dataRemaining = contentAvail_ - contentLength_;\n log_debug(\"PreserveReceiveBuffer: Preserve data: \" << dataRemaining << \" bytes\");\n memmove(buffer_, responseEnd, dataRemaining);\n bufferLength_ = dataRemaining;\n }\n else\n {\n log_debug(\"PreserveReceiveBuffer: No data to preserve\");\n bufferLength_ = 0;\n }\n }\n else\n log_debug(\"PreserveReceiveBuffer: Keep any previous data: \" << bufferLength_ << \" bytes\");\n }\n else\n {\n log_debug(\"PreserveReceiveBuffer: Reset buffer\");\n bufferLength_ = 0;\n }\n responseProcessed_ = true;\n}\n\nunsigned Client::GetTimeLeft()\n{\n struct timeval currentTime;\n gettimeofday( ¤tTime, 0 );\n\n int timeUsed = MilliTimeDiff(currentTime,startTime_);\n\n int timeLeft = std::max(0,(int)timeout_ - timeUsed);\n\n log_debug(\"GetTimeLeft: timeout=\" << timeout_ << \", timeLeft=\" << timeLeft << \", timeUsed=\" << timeUsed);\n return timeLeft;\n}\n\nbool Client::Connect(Value& result)\n{\n log_trace();\n if (socket_.IsConnected(0))\n {\n log_debug(\"Already connected\");\n return true;\n }\n \/\/ Close the connection but keep any data that has been setup for the next message\n Close();\n ResetReceiveBuffer();\n\n log_debug(\"Create a new connection\");\n socket_.Create();\n socket_.SetNonBlocking();\n\n socket_.Connect(host_.c_str(), port_);\n\n socket_.SetKeepAlive();\n socket_.SetTcpNoDelay();\n\n if (!socket_.IsConnected(GetTimeLeft()))\n {\n socket_.Close();\n return false;\n }\n return true;\n}\n\nbool Client::GenerateRequest(const char* method, Value& params, bool notification)\n{\n int requestId;\n\n bool result = handler_->GenerateRequest(method,params,request_,requestId,notification);\n requestId_.push_back(requestId);\n return result;\n}\n\nbool Client::WriteRequest(Value& result)\n{\n log_trace();\n\n size_t bytesWritten;\n size_t bytesToSend;\n\n \/\/ write the header - it make be in several segments\n size_t headerBytesWritten = 0;\n while (headerBytesWritten < header_.Length())\n {\n const char* buffer = header_.GetBuffer(headerBytesWritten, bytesToSend);\n if (!socket_.Send(buffer, bytesToSend, bytesWritten, GetTimeLeft()))\n return false;\n\n headerBytesWritten += bytesWritten;\n\n if (bytesToSend < bytesWritten)\n return false; \/\/ timeout\n }\n\n \/\/ write the request - it make be in several segments\n size_t requestBytesWritten = 0;\n while (requestBytesWritten < request_.Length())\n {\n const char* buffer = request_.GetBuffer(requestBytesWritten, bytesToSend);\n if (!socket_.Send(buffer, bytesToSend, bytesWritten, GetTimeLeft()))\n return false;\n\n requestBytesWritten += bytesWritten;\n\n if (bytesToSend < bytesWritten)\n return false; \/\/ timeout\n }\n\n return true;\n}\n\nbool Client::ReadHeader(Value& result)\n{\n log_trace();\n \/\/ Read available data\n socket_.SetTimeout(0);\n while (true)\n {\n int bytesRead;\n bool eof;\n socket_.Receive(buffer_+bufferLength_, MaxBufferLength-bufferLength_, bytesRead, eof, 0);\n if (socket_.FatalError())\n {\n log_warn(\"error while reading header: \" << socket_.GetLastError() << \", bytesRead=\" << bytesRead);\n return false;\n }\n bufferLength_ += bytesRead;\n log_info(\"read=\" << bytesRead << \", total=\" << bufferLength_);\n\n switch (ProcessHeader(eof))\n {\n case HEADER_COMPLETE : return true;\n case HEADER_FAULT : return false;\n }\n unsigned timeLeft = GetTimeLeft();\n if (timeLeft == 0)\n {\n handler_->GenerateFaultResult(AnyRpcErrorTransportError,\"Timeout reading response header\",result);\n break;\n }\n socket_.WaitReadable(timeLeft);\n }\n return false;\n}\n\nbool Client::ReadResponse(Value& result)\n{\n log_trace();\n if (contentAvail_ >= contentLength_)\n return true;\n\n int bytesRead;\n bool eof;\n bool receiveResult = socket_.Receive(response_+contentAvail_, contentLength_-contentAvail_, bytesRead, eof, GetTimeLeft());\n contentAvail_ += bytesRead;\n if(response_)\n \tresponse_[contentAvail_] = 0;\n if (!receiveResult)\n handler_->GenerateFaultResult(AnyRpcErrorTransportError,\"Failed reading response\",result);\n return receiveResult;\n}\n\nProcessResponseEnum Client::ProcessResponse(Value& result, bool notification)\n{\n int requestId = requestId_.front();\n if(!requestId_.empty())\n \trequestId_.pop_front();\n responseProcessed_ = true;\n return handler_->ProcessResponse(response_,contentLength_,result,requestId,notification);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool HttpClient::GenerateHeader()\n{\n log_trace();\n header_ << \"POST \/RPC2 HTTP\/1.1\\r\\n\";\n header_ << \"User-Agent: \" << ANYRPC_APP_NAME << \" v\" << ANYRPC_VERSION_STRING << \"\\r\\n\";\n header_ << \"Host: \" << host_ << \":\" << port_ << \"\\r\\n\";\n header_ << \"Content-Type: \" << contentType_ << \"\\r\\n\";\n header_ << \"Accept: \" << contentType_ << \"\\r\\n\";\n header_ << \"Content-length: \" << request_.Length() << \"\\r\\n\";\n header_ << \"\\r\\n\";\n\n return true;\n}\n\nint HttpClient::ProcessHeader(bool eof)\n{\n log_trace();\n switch (httpResponseState_.ProcessHeaderData(buffer_, bufferLength_, eof))\n {\n case internal::HttpHeader::HEADER_FAULT : return HEADER_FAULT;\n case internal::HttpHeader::HEADER_INCOMPLETE : return HEADER_INCOMPLETE;\n }\n\n size_t bodyStartPos = httpResponseState_.GetBodyStartPos();\n size_t bufferSpaceAvail = MaxBufferLength - bodyStartPos;\n\n contentLength_ = httpResponseState_.GetContentLength();\n contentAvail_ = bufferLength_ - bodyStartPos;\n \/\/keepAlive_ = httpResponseState_.GetKeepAlive();\n\n if (contentLength_ > MaxContentLength)\n {\n log_warn(\"Content-length too large=\" << contentLength_ << \", max allowed=\" << MaxContentLength);\n return HEADER_FAULT;\n }\n if (contentLength_ > (int)bufferSpaceAvail)\n {\n \/\/ try to malloc the buffer space needed\n response_ = static_cast(malloc(contentLength_+1));\n if (response_ == 0)\n {\n log_warn(\"Could not allocate space=\" << contentLength_);\n return HEADER_FAULT;\n }\n \/\/ copy the content that was already read to the new space\n memcpy(response_,buffer_+bodyStartPos,contentAvail_);\n responseAllocated_ = true;\n }\n else\n {\n responseAllocated_ = false;\n response_ = buffer_ + bodyStartPos;\n }\n response_[contentAvail_] = 0;\n\n log_info(\"specified content length is \" << contentLength_);\n\n return HEADER_COMPLETE;\n}\n\nProcessResponseEnum HttpClient::ProcessResponse(Value& result, bool notification)\n{\n log_trace();\n int requestId = requestId_.front();\n requestId_.pop_front();\n responseProcessed_ = true;\n ProcessResponseEnum processResult = handler_->ProcessResponse(response_,contentLength_,result,requestId,notification);\n if (!httpResponseState_.GetKeepAlive())\n {\n log_info(\"Http response header indicates to close connection\");\n Close();\n }\n return processResult;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool TcpClient::GenerateHeader()\n{\n log_trace();\n header_ << request_.Length() << \":\";\n log_debug(\"Request length=\" << request_.Length());\n\n \/\/ add the comma separator to the request buffer\n request_ << ',';\n\n return true;\n}\n\nint TcpClient::ProcessHeader(bool eof)\n{\n \/\/ search for the length\/body separator, ':'\n char* body = 0;\n char* header = buffer_;\n char* end = buffer_ + bufferLength_;\n for (char* current = buffer_; current < end; current++)\n {\n if (*current == ':')\n {\n body = current + 1;\n break;\n }\n }\n\n \/\/ If we haven't gotten the entire header yet, return (keep reading)\n if (body == 0)\n {\n \/\/ EOF in the middle of a request is an error, otherwise its ok\n if (eof)\n {\n log_warn(\"EOF while reading header\");\n return HEADER_FAULT;\n }\n return HEADER_INCOMPLETE; \/\/ Keep reading\n }\n\n \/\/ check for comma separator\n if (commaExpected_)\n {\n if (*header != ',')\n {\n log_warn(\"Expected comma to separate messages\");\n log_warn(\"bufferLength=\" << bufferLength_ << \", buffer=\" << buffer_);\n return HEADER_FAULT;\n }\n header++;\n }\n\n contentLength_ = atoi(header);\n if (contentLength_ <= 0)\n {\n log_warn(\"Invalid string length specified \" << contentLength_);\n log_warn(\"bufferLength=\" << bufferLength_ << \", buffer=\" << buffer_);\n return HEADER_FAULT;\n }\n\n int bufferSpaceAvail = buffer_ + MaxBufferLength - body;\n contentAvail_ = end - body;\n\n if (contentLength_ > MaxContentLength)\n {\n log_warn(\"String length too large=\" << contentLength_ << \", max allowed=\" << MaxContentLength);\n return HEADER_FAULT;\n }\n if (contentLength_ > bufferSpaceAvail)\n {\n \/\/ try to malloc the buffer space needed\n response_ = static_cast(malloc(contentLength_+1));\n if (response_ == 0)\n {\n log_warn(\"Could not allocate space=\" << contentLength_);\n return HEADER_FAULT;\n }\n \/\/ copy the content that was already read to the new space\n memcpy(response_,body,contentAvail_);\n responseAllocated_ = true;\n }\n else\n {\n responseAllocated_ = false;\n response_ = body;\n }\n response_[contentAvail_] = 0;\n log_info(\"specified content length is \" << contentLength_);\n\n \/\/ a comma is expected to separate the next message\n commaExpected_ = true;\n\n return HEADER_COMPLETE;\n}\n\n} \/\/ namespace anyrpc\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Claire Xenia Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/ffinit.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct ZinitPass : public Pass {\n\tZinitPass() : Pass(\"zinit\", \"add inverters so all FF are zero-initialized\") { }\n\tvoid help() override\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" zinit [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Add inverters as needed to make all FFs zero-initialized.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -all\\n\");\n\t\tlog(\" also add zero initialization to uninitialized FFs\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector args, RTLIL::Design *design) override\n\t{\n\t\tbool all_mode = false;\n\n\t\tlog_header(design, \"Executing ZINIT pass (make all FFs zero-initialized).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\tif (args[argidx] == \"-all\") {\n\t\t\t\tall_mode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t{\n\t\t\tSigMap sigmap(module);\n\t\t\tFfInitVals initvals(&sigmap, module);\n\n\t\t\tpool dff_types = {\n\t\t\t\t\t\t\t\t\/\/ FIXME: It would appear that supporting\n\t\t\t\t\t\t\t\t\/\/ $dffsr\/$_DFFSR_* would require a new\n\t\t\t\t\t\t\t\t\/\/ cell type where S has priority over R\n\t\t\t\tID($ff), ID($dff), ID($dffe), \/*ID($dffsr),*\/ ID($adff), ID($adffe),\n\t\t\t\tID($sdff), ID($sdffe), ID($sdffce),\n\t\t\t\tID($_FF_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_),\n\t\t\t\t\/*ID($_DFFSR_NNN_), ID($_DFFSR_NNP_), ID($_DFFSR_NPN_), ID($_DFFSR_NPP_),\n\t\t\t\tID($_DFFSR_PNN_), ID($_DFFSR_PNP_), ID($_DFFSR_PPN_), ID($_DFFSR_PPP_),*\/\n\t\t\t\tID($_DFF_N_), ID($_DFF_NN0_), ID($_DFF_NN1_), ID($_DFF_NP0_), ID($_DFF_NP1_),\n\t\t\t\tID($_DFF_P_), ID($_DFF_PN0_), ID($_DFF_PN1_), ID($_DFF_PP0_), ID($_DFF_PP1_),\n\t\t\t\t\/\/ Async set\/reset\n\t\t\t\tID($_DFFE_NN0P_), ID($_DFFE_NN1P_), ID($_DFFE_NP0P_), ID($_DFFE_NP1P_),\n\t\t\t\tID($_DFFE_PN0P_), ID($_DFFE_PN1P_), ID($_DFFE_PP0P_), ID($_DFFE_PP1P_),\n\t\t\t\tID($_DFFE_NN0N_), ID($_DFFE_NN1N_), ID($_DFFE_NP0N_), ID($_DFFE_NP1N_),\n\t\t\t\tID($_DFFE_PN0N_), ID($_DFFE_PN1N_), ID($_DFFE_PP0N_), ID($_DFFE_PP1N_),\n\t\t\t\t\/\/ Sync set\/reset\n\t\t\t\tID($_SDFF_NN0_), ID($_SDFF_NN1_), ID($_SDFF_NP0_), ID($_SDFF_NP1_),\n\t\t\t\tID($_SDFF_PN0_), ID($_SDFF_PN1_), ID($_SDFF_PP0_), ID($_SDFF_PP1_),\n\t\t\t\tID($_SDFFE_NN0P_), ID($_SDFFE_NN1P_), ID($_SDFFE_NP0P_), ID($_SDFFE_NP1P_),\n\t\t\t\tID($_SDFFE_PN0P_), ID($_SDFFE_PN1P_), ID($_SDFFE_PP0P_), ID($_SDFFE_PP1P_),\n\t\t\t\tID($_SDFFE_NN0N_), ID($_SDFFE_NN1N_), ID($_SDFFE_NP0N_), ID($_SDFFE_NP1N_),\n\t\t\t\tID($_SDFFE_PN0N_), ID($_SDFFE_PN1N_), ID($_SDFFE_PP0N_), ID($_SDFFE_PP1N_),\n\t\t\t\tID($_SDFFCE_NN0P_), ID($_SDFFCE_NN1P_), ID($_SDFFCE_NP0P_), ID($_SDFFCE_NP1P_),\n\t\t\t\tID($_SDFFCE_PN0P_), ID($_SDFFCE_PN1P_), ID($_SDFFCE_PP0P_), ID($_SDFFCE_PP1P_),\n\t\t\t\tID($_SDFFCE_NN0N_), ID($_SDFFCE_NN1N_), ID($_SDFFCE_NP0N_), ID($_SDFFCE_NP1N_),\n\t\t\t\tID($_SDFFCE_PN0N_), ID($_SDFFCE_PN1N_), ID($_SDFFCE_PP0N_), ID($_SDFFCE_PP1N_)\n\t\t\t};\n\n\t\t\tfor (auto cell : module->selected_cells())\n\t\t\t{\n\t\t\t\tif (!dff_types.count(cell->type))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tSigSpec sig_d = sigmap(cell->getPort(ID::D));\n\t\t\t\tSigSpec sig_q = sigmap(cell->getPort(ID::Q));\n\n\t\t\t\tif (GetSize(sig_d) < 1 || GetSize(sig_q) < 1)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tConst initval = initvals(sig_q);\n\t\t\t\tConst newval = initval;\n\t\t\t\tinitvals.remove_init(sig_q);\n\n\t\t\t\tWire *initwire = module->addWire(NEW_ID, GetSize(sig_q));\n\n\t\t\t\tfor (int i = 0; i < GetSize(initwire); i++)\n\t\t\t\t\tif (initval[i] == State::S1)\n\t\t\t\t\t{\n\t\t\t\t\t\tsig_d[i] = module->NotGate(NEW_ID, sig_d[i]);\n\t\t\t\t\t\tmodule->addNotGate(NEW_ID, SigSpec(initwire, i), sig_q[i]);\n\t\t\t\t\t\tnewval[i] = State::S0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmodule->connect(sig_q[i], SigSpec(initwire, i));\n\t\t\t\t\t\tif (all_mode)\n\t\t\t\t\t\t\tnewval[i] = State::S0;\n\t\t\t\t\t}\n\n\t\t\t\tinitvals.set_init(initwire, newval);\n\n\t\t\t\tlog(\"FF init value for cell %s (%s): %s = %s\\n\", log_id(cell), log_id(cell->type),\n\t\t\t\t\t\tlog_signal(sig_q), log_signal(initval));\n\n\t\t\t\tcell->setPort(ID::D, sig_d);\n\t\t\t\tcell->setPort(ID::Q, initwire);\n\n\t\t\t\tif (cell->type.in(ID($adff), ID($adffe))) {\n\t\t\t\t\tauto val = cell->getParam(ID::ARST_VALUE);\n\t\t\t\t\tfor (int i = 0; i < GetSize(initwire); i++)\n\t\t\t\t\t\tif (initval[i] == State::S1)\n\t\t\t\t\t\t\tval[i] = (val[i] == State::S1 ? State::S0 : State::S1);\n\t\t\t\t\tcell->setParam(ID::ARST_VALUE, std::move(val));\n\t\t\t\t}\n\t\t\t\telse if (cell->type.in(ID($sdff), ID($sdffe), ID($sdffce))) {\n\t\t\t\t\tauto val = cell->getParam(ID::SRST_VALUE);\n\t\t\t\t\tfor (int i = 0; i < GetSize(initwire); i++)\n\t\t\t\t\t\tif (initval[i] == State::S1)\n\t\t\t\t\t\t\tval[i] = (val[i] == State::S1 ? State::S0 : State::S1);\n\t\t\t\t\tcell->setParam(ID::SRST_VALUE, std::move(val));\n\t\t\t\t}\n\t\t\t\telse if (initval == State::S1) {\n\t\t\t\t\tstd::string t = cell->type.str();\n\t\t\t\t\tif (cell->type.in(ID($_DFF_NN0_), ID($_DFF_NN1_), ID($_DFF_NP0_), ID($_DFF_NP1_),\n\t\t\t\t\t\t\t\tID($_DFF_PN0_), ID($_DFF_PN1_), ID($_DFF_PP0_), ID($_DFF_PP1_)))\n\t\t\t\t\t{\n\t\t\t\t\t\tt[8] = (t[8] == '0' ? '1' : '0');\n\t\t\t\t\t}\n\t\t\t\t\telse if (cell->type.in(ID($_SDFF_NN0_), ID($_SDFF_NN1_), ID($_SDFF_NP0_), ID($_SDFF_NP1_),\n\t\t\t\t\t\t\t\tID($_SDFF_PN0_), ID($_SDFF_PN1_), ID($_SDFF_PP0_), ID($_SDFF_PP1_)))\n\t\t\t\t\t{\n\t\t\t\t\t\tt[9] = (t[9] == '0' ? '1' : '0');\n\t\t\t\t\t}\n\t\t\t\t\telse if (cell->type.in(ID($_DFFE_NN0P_), ID($_DFFE_NN1P_), ID($_DFFE_NP0P_), ID($_DFFE_NP1P_),\n\t\t\t\t\t\t\t\tID($_DFFE_PN0P_), ID($_DFFE_PN1P_), ID($_DFFE_PP0P_), ID($_DFFE_PP1P_),\n\t\t\t\t\t\t\t\tID($_DFFE_NN0N_), ID($_DFFE_NN1N_), ID($_DFFE_NP0N_), ID($_DFFE_NP1N_),\n\t\t\t\t\t\t\t\tID($_DFFE_PN0N_), ID($_DFFE_PN1N_), ID($_DFFE_PP0N_), ID($_DFFE_PP1N_)))\n\t\t\t\t\t{\n\t\t\t\t\t\tt[9] = (t[9] == '0' ? '1' : '0');\n\t\t\t\t\t}\n\t\t\t\t\telse if (cell->type.in(ID($_SDFFE_NN0P_), ID($_SDFFE_NN1P_), ID($_SDFFE_NP0P_), ID($_SDFFE_NP1P_),\n\t\t\t\t\t\t\t\tID($_SDFFE_PN0P_), ID($_SDFFE_PN1P_), ID($_SDFFE_PP0P_), ID($_SDFFE_PP1P_),\n\t\t\t\t\t\t\t\tID($_SDFFE_NN0N_), ID($_SDFFE_NN1N_), ID($_SDFFE_NP0N_), ID($_SDFFE_NP1N_),\n\t\t\t\t\t\t\t\tID($_SDFFE_PN0N_), ID($_SDFFE_PN1N_), ID($_SDFFE_PP0N_), ID($_SDFFE_PP1N_)))\n\t\t\t\t\t{\n\t\t\t\t\t\tt[10] = (t[10] == '0' ? '1' : '0');\n\t\t\t\t\t}\n\t\t\t\t\telse if (cell->type.in(ID($_SDFFCE_NN0P_), ID($_SDFFCE_NN1P_), ID($_SDFFCE_NP0P_), ID($_SDFFCE_NP1P_),\n\t\t\t\t\t\t\t\tID($_SDFFCE_PN0P_), ID($_SDFFCE_PN1P_), ID($_SDFFCE_PP0P_), ID($_SDFFCE_PP1P_),\n\t\t\t\t\t\t\t\tID($_SDFFCE_NN0N_), ID($_SDFFCE_NN1N_), ID($_SDFFCE_NP0N_), ID($_SDFFCE_NP1N_),\n\t\t\t\t\t\t\t\tID($_SDFFCE_PN0N_), ID($_SDFFCE_PN1N_), ID($_SDFFCE_PP0N_), ID($_SDFFCE_PP1N_)))\n\t\t\t\t\t{\n\t\t\t\t\t\tt[11] = (t[11] == '0' ? '1' : '0');\n\t\t\t\t\t}\n\t\t\t\t\tcell->type = t;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n} ZinitPass;\n\nPRIVATE_NAMESPACE_END\nzinit: Refactor to use FfData.\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Claire Xenia Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/ffinit.h\"\n#include \"kernel\/ff.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nState invert(State s) {\n\tswitch (s) {\n\t\tcase State::S0: return State::S1;\n\t\tcase State::S1: return State::S0;\n\t\tdefault: return s;\n\t}\n}\n\nstruct ZinitPass : public Pass {\n\tZinitPass() : Pass(\"zinit\", \"add inverters so all FF are zero-initialized\") { }\n\tvoid help() override\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" zinit [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Add inverters as needed to make all FFs zero-initialized.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -all\\n\");\n\t\tlog(\" also add zero initialization to uninitialized FFs\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector args, RTLIL::Design *design) override\n\t{\n\t\tbool all_mode = false;\n\n\t\tlog_header(design, \"Executing ZINIT pass (make all FFs zero-initialized).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\tif (args[argidx] == \"-all\") {\n\t\t\t\tall_mode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t{\n\t\t\tSigMap sigmap(module);\n\t\t\tFfInitVals initvals(&sigmap, module);\n\n\t\t\tfor (auto cell : module->selected_cells())\n\t\t\t{\n\t\t\t\tif (!RTLIL::builtin_ff_cell_types().count(cell->type))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tFfData ff(&initvals, cell);\n\t\t\t\tif (!ff.width)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t\/\/ Supporting those would require a new cell type where S has priority over R.\n\t\t\t\tif (ff.has_sr)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tWire *new_q = module->addWire(NEW_ID, ff.width);\n\n\t\t\t\tlog(\"FF init value for cell %s (%s): %s = %s\\n\", log_id(cell), log_id(cell->type),\n\t\t\t\t\t\tlog_signal(ff.sig_q), log_signal(ff.val_init));\n\n\t\t\t\tIdString name = cell->name;\n\t\t\t\tmodule->remove(cell);\n\t\t\t\tinitvals.remove_init(ff.sig_q);\n\n\t\t\t\tfor (int i = 0; i < ff.width; i++)\n\t\t\t\t\tif (ff.val_init[i] == State::S1)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ff.has_clk || ff.has_gclk)\n\t\t\t\t\t\t\tff.sig_d[i] = module->NotGate(NEW_ID, ff.sig_d[i]);\n\t\t\t\t\t\tif (ff.has_aload)\n\t\t\t\t\t\t\tff.sig_ad[i] = module->NotGate(NEW_ID, ff.sig_ad[i]);\n\t\t\t\t\t\tif (ff.has_arst)\n\t\t\t\t\t\t\tff.val_arst[i] = invert(ff.val_arst[i]);\n\t\t\t\t\t\tif (ff.has_srst)\n\t\t\t\t\t\t\tff.val_srst[i] = invert(ff.val_srst[i]);\n\t\t\t\t\t\tmodule->addNotGate(NEW_ID, SigSpec(new_q, i), ff.sig_q[i]);\n\t\t\t\t\t\tff.val_init[i] = State::S0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmodule->connect(ff.sig_q[i], SigSpec(new_q, i));\n\t\t\t\t\t\tif (all_mode)\n\t\t\t\t\t\t\tff.val_init[i] = State::S0;\n\t\t\t\t\t}\n\n\t\t\t\tff.sig_q = new_q;\n\t\t\t\tff.emit(module, name);\n\t\t\t}\n\t\t}\n\t}\n} ZinitPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016 Shanghai Jiao Tong University.\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an \"AS\n * IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n * http:\/\/ipads.se.sjtu.edu.cn\/projects\/wukong.html\n *\n *\/\n\n#include \"client.h\"\n\nclient::client(thread_cfg *_cfg, string_server *_str_server):\n cfg(_cfg), str_server(_str_server), parser(_str_server) { }\n\nvoid\nclient::send(request_or_reply &req)\n{\n assert(req.pid != -1);\n\n if (req.start_from_index()) {\n int nthread = max(1, min(global_mt_threshold, global_nbewkrs));\n for (int i = 0; i < global_nsrvs; i++) {\n for (int j = 0; j < nthread; j++) {\n req.mt_total_thread = nthread;\n req.mt_current_thread = j;\n SendR(cfg, i, global_nfewkrs + j, req);\n }\n }\n return ;\n }\n req.first_target = mymath::hash_mod(req.cmd_chains[0], global_nsrvs);\n\n \/\/ one-to-one mapping\n \/\/int server_per_client = global_nbewkrs \/ global_nfewkrs;\n \/\/int mid = global_nfewkrs + server_per_client * cfg->wid + cfg->get_random() % server_per_client;\n\n \/\/ random\n int tid = global_nfewkrs + cfg->get_random() % global_nbewkrs;\n SendR(cfg, req.first_target, tid, req);\n}\n\nrequest_or_reply\nclient::recv(void)\n{\n request_or_reply r = RecvR(cfg);\n if (r.start_from_index()) {\n int nthread = max(1, min(global_mt_threshold, global_nbewkrs));\n for (int count = 0; count < global_nsrvs * nthread - 1 ; count++) {\n request_or_reply r2 = RecvR(cfg);\n r.row_num += r2.row_num;\n int new_size = r.result_table.size() + r2.result_table.size();\n r.result_table.reserve(new_size);\n r.result_table.insert(r.result_table.end(), r2.result_table.begin(), r2.result_table.end());\n }\n }\n\n return r;\n}\n\nvoid\nclient::print_result(request_or_reply &r, int row2print)\n{\n cout << \"The first \" << row2print << \" rows of results: \" << endl;\n for (int i = 0; i < row2print; i++) {\n cout << i + 1 << \": \";\n for (int c = 0; c < r.get_col_num(); c++) {\n int id = r.get_row_col(i, c);\n if (str_server->id2str.find(id) == str_server->id2str.end()) {\n cout << \"NULL \";\n } else {\n cout << str_server->id2str[r.get_row_col(i, c)] << \" \";\n }\n }\n cout << endl;\n }\n}\nrefine print\/*\n * Copyright (c) 2016 Shanghai Jiao Tong University.\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an \"AS\n * IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n * http:\/\/ipads.se.sjtu.edu.cn\/projects\/wukong.html\n *\n *\/\n\n#include \"client.h\"\n\nclient::client(thread_cfg *_cfg, string_server *_str_server):\n cfg(_cfg), str_server(_str_server), parser(_str_server) { }\n\nvoid\nclient::send(request_or_reply &req)\n{\n assert(req.pid != -1);\n\n if (req.start_from_index()) {\n int nthread = max(1, min(global_mt_threshold, global_nbewkrs));\n for (int i = 0; i < global_nsrvs; i++) {\n for (int j = 0; j < nthread; j++) {\n req.mt_total_thread = nthread;\n req.mt_current_thread = j;\n SendR(cfg, i, global_nfewkrs + j, req);\n }\n }\n return ;\n }\n req.first_target = mymath::hash_mod(req.cmd_chains[0], global_nsrvs);\n\n \/\/ one-to-one mapping\n \/\/int server_per_client = global_nbewkrs \/ global_nfewkrs;\n \/\/int mid = global_nfewkrs + server_per_client * cfg->wid + cfg->get_random() % server_per_client;\n\n \/\/ random\n int tid = global_nfewkrs + cfg->get_random() % global_nbewkrs;\n SendR(cfg, req.first_target, tid, req);\n}\n\nrequest_or_reply\nclient::recv(void)\n{\n request_or_reply r = RecvR(cfg);\n if (r.start_from_index()) {\n int nthread = max(1, min(global_mt_threshold, global_nbewkrs));\n for (int count = 0; count < global_nsrvs * nthread - 1 ; count++) {\n request_or_reply r2 = RecvR(cfg);\n r.row_num += r2.row_num;\n int new_size = r.result_table.size() + r2.result_table.size();\n r.result_table.reserve(new_size);\n r.result_table.insert(r.result_table.end(), r2.result_table.begin(), r2.result_table.end());\n }\n }\n\n return r;\n}\n\nvoid\nclient::print_result(request_or_reply &r, int row2print)\n{\n cout << \"The first \" << row2print << \" rows of results: \" << endl;\n for (int i = 0; i < row2print; i++) {\n cout << i + 1 << \": \";\n for (int c = 0; c < r.get_col_num(); c++) {\n int id = r.get_row_col(i, c);\n if (str_server->id2str.find(id) == str_server->id2str.end())\n cout << id << \"\\t\";\n else\n cout << str_server->id2str[r.get_row_col(i, c)] << \" \";\n }\n cout << endl;\n }\n}\n<|endoftext|>"} {"text":"#include \"..\/glm\/glm.hpp\"\n\n#include \"box.h\"\n#include \"..\/physic\/pbox.h\"\n\nusing namespace glm;\n\nBox::Box(float w, float h, float d)\n{\n std::vector vertices;\n std::vector indices;\n\n vertices.push_back(vec3( w \/ 2, -h \/ 2, -d \/ 2));\n vertices.push_back(vec3( w \/ 2, -h \/ 2, d \/ 2));\n vertices.push_back(vec3(-w \/ 2, -h \/ 2, d \/ 2));\n vertices.push_back(vec3(-w \/ 2, -h \/ 2, -d \/ 2));\n vertices.push_back(vec3( w \/ 2, h \/ 2, -d \/ 2));\n vertices.push_back(vec3( w \/ 2, h \/ 2, d \/ 2));\n vertices.push_back(vec3(-w \/ 2, h \/ 2, d \/ 2));\n vertices.push_back(vec3(-w \/ 2, h \/ 2, -d \/ 2));\n\n indices.push_back(uvec3(0, 1, 2));\n indices.push_back(uvec3(0, 2, 3));\n indices.push_back(uvec3(4, 7, 6));\n indices.push_back(uvec3(4, 6, 5));\n indices.push_back(uvec3(0, 4, 5));\n indices.push_back(uvec3(0, 5, 1));\n indices.push_back(uvec3(1, 5, 6));\n indices.push_back(uvec3(1, 6, 2));\n indices.push_back(uvec3(2, 6, 7));\n indices.push_back(uvec3(2, 7, 3));\n indices.push_back(uvec3(4, 0, 3));\n indices.push_back(uvec3(4, 3, 7));\n\n \/\/m_gObj.load(vertices, indices);\n m_pObj = new PBox(w, h, d);\n}\n\nBox::~Box()\n{\n delete m_pObj;\n}\n\nObject::ObjectType Box::getType()\n{\n return Object::Box;\n}\nsolution temporaire load pour box#include \"..\/glm\/glm.hpp\"\n\n#include \"box.h\"\n#include \"..\/physic\/pbox.h\"\n\nusing namespace glm;\n\nBox::Box(float w, float h, float d)\n{\n std::vector vertices;\n std::vector indices;\n\n vertices.push_back(vec3( w \/ 2, -h \/ 2, -d \/ 2));\n vertices.push_back(vec3( w \/ 2, -h \/ 2, d \/ 2));\n vertices.push_back(vec3(-w \/ 2, -h \/ 2, d \/ 2));\n vertices.push_back(vec3(-w \/ 2, -h \/ 2, -d \/ 2));\n vertices.push_back(vec3( w \/ 2, h \/ 2, -d \/ 2));\n vertices.push_back(vec3( w \/ 2, h \/ 2, d \/ 2));\n vertices.push_back(vec3(-w \/ 2, h \/ 2, d \/ 2));\n vertices.push_back(vec3(-w \/ 2, h \/ 2, -d \/ 2));\n\n indices.push_back(uvec3(0, 1, 2));\n indices.push_back(uvec3(0, 2, 3));\n indices.push_back(uvec3(4, 7, 6));\n indices.push_back(uvec3(4, 6, 5));\n indices.push_back(uvec3(0, 4, 5));\n indices.push_back(uvec3(0, 5, 1));\n indices.push_back(uvec3(1, 5, 6));\n indices.push_back(uvec3(1, 6, 2));\n indices.push_back(uvec3(2, 6, 7));\n indices.push_back(uvec3(2, 7, 3));\n indices.push_back(uvec3(4, 0, 3));\n indices.push_back(uvec3(4, 3, 7));\n\n \/\/Pas propre, mais ça fonctionne en attendant.\n m_gObj.load(vertices, *((std::vector*) &indices));\n m_pObj = new PBox(w, h, d);\n}\n\nBox::~Box()\n{\n delete m_pObj;\n}\n\nObject::ObjectType Box::getType()\n{\n return Object::Box;\n}\n<|endoftext|>"} {"text":"\/*\r\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * * Redistributions of source code must retain the above copyright\r\n * notice, this list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright\r\n * notice, this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * * Neither the name of the nor the\r\n * names of its contributors may be used to endorse or promote products\r\n * derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include \"CppUTest\/TestHarness.h\"\r\n#include \"CppUTest\/SimpleString.h\"\r\n#include \"CppUTest\/PlatformSpecificFunctions.h\"\r\n\r\n#include \"CppUTest\/MemoryLeakDetector.h\" \/\/ REMOVE THIS AFTER THE VC++ EXPRESS IS FIXED!\r\n\r\nTEST_GROUP(SimpleString)\r\n{\r\n\tvoid setup()\r\n\t{\r\n\t\tMemoryLeakWarningPlugin::getGlobalDetector()->disableAllocationTypeChecking (); \/\/ REMOVE THIS AFTER THE VC++ EXPRESS IS FIXED!\r\n\t}\r\n\r\n\tvoid teardown()\r\n\t{\r\n\t\tMemoryLeakWarningPlugin::getGlobalDetector()->enableAllocationTypeChecking (); \/\/ REMOVE THIS AFTER THE VC++ EXPRESS IS FIXED!\r\n\t}\r\n};\r\n\r\nTEST(SimpleString, CreateSequence)\r\n{\r\n SimpleString expected(\"hellohello\");\r\n SimpleString actual(\"hello\", 2);\r\n\r\n CHECK_EQUAL(expected, actual);\r\n}\r\n\r\nTEST(SimpleString, CreateSequenceOfZero)\r\n{\r\n SimpleString expected(\"\");\r\n SimpleString actual(\"hello\", 0);\r\n\r\n CHECK_EQUAL(expected, actual);\r\n}\r\n\r\nTEST(SimpleString, Copy)\r\n{\r\n SimpleString s1(\"hello\");\r\n SimpleString s2(s1);\r\n\r\n CHECK_EQUAL(s1, s2);\r\n}\r\n\r\nTEST(SimpleString, Assignment)\r\n{\r\n SimpleString s1(\"hello\");\r\n SimpleString s2(\"goodbye\");\r\n\r\n s2 = s1;\r\n\r\n CHECK_EQUAL(s1, s2);\r\n}\r\n\r\nTEST(SimpleString, Equality)\r\n{\r\n SimpleString s1(\"hello\");\r\n SimpleString s2(\"hello\");\r\n\r\n CHECK(s1 == s2);\r\n}\r\n\r\nTEST(SimpleString, InEquality)\r\n{\r\n SimpleString s1(\"hello\");\r\n SimpleString s2(\"goodbye\");\r\n\r\n CHECK(s1 != s2);\r\n}\r\n\r\nTEST(SimpleString, asCharString)\r\n{\r\n SimpleString s1(\"hello\");\r\n\r\n STRCMP_EQUAL(\"hello\", s1.asCharString());\r\n}\r\n\r\nTEST(SimpleString, Size)\r\n{\r\n SimpleString s1(\"hello!\");\r\n\r\n LONGS_EQUAL(6, s1.size());\r\n}\r\n\r\nTEST(SimpleString, Addition)\r\n{\r\n SimpleString s1(\"hello!\");\r\n SimpleString s2(\"goodbye!\");\r\n SimpleString s3(\"hello!goodbye!\");\r\n SimpleString s4;\r\n s4 = s1 + s2;\r\n\r\n CHECK_EQUAL(s3, s4);\r\n}\r\n\r\nTEST(SimpleString, Concatenation)\r\n{\r\n SimpleString s1(\"hello!\");\r\n SimpleString s2(\"goodbye!\");\r\n SimpleString s3(\"hello!goodbye!\");\r\n SimpleString s4;\r\n s4 += s1;\r\n s4 += s2;\r\n\r\n CHECK_EQUAL(s3, s4);\r\n\r\n SimpleString s5(\"hello!goodbye!hello!goodbye!\");\r\n s4 += s4;\r\n\r\n CHECK_EQUAL(s5, s4);\r\n}\r\n\r\n\r\nTEST(SimpleString, Contains)\r\n{\r\n SimpleString s(\"hello!\");\r\n SimpleString empty(\"\");\r\n SimpleString beginning(\"hello\");\r\n SimpleString end(\"lo!\");\r\n SimpleString mid(\"l\");\r\n SimpleString notPartOfString(\"xxxx\");\r\n\r\n CHECK(s.contains(empty));\r\n CHECK(s.contains(beginning));\r\n CHECK(s.contains(end));\r\n CHECK(s.contains(mid));\r\n CHECK(!s.contains(notPartOfString));\r\n\r\n CHECK(empty.contains(empty));\r\n CHECK(!empty.contains(s));\r\n}\r\n\r\nTEST(SimpleString, startsWith)\r\n{\r\n\tSimpleString hi(\"Hi you!\");\r\n\tSimpleString part(\"Hi\");\r\n\tSimpleString diff(\"Hrrm Hi you! ffdsfd\");\r\n\tCHECK(hi.startsWith(part));\r\n\tCHECK(!part.startsWith(hi));\r\n\tCHECK(!diff.startsWith(hi));\r\n}\r\n\r\nTEST(SimpleString, split)\r\n{\r\n\tSimpleString hi(\"hello\\nworld\\nhow\\ndo\\nyou\\ndo\\n\\n\");\r\n\r\n\tSimpleStringCollection collection;\r\n\thi.split(\"\\n\", collection);\r\n\r\n\tLONGS_EQUAL(7, collection.size());\r\n\tSTRCMP_EQUAL(\"hello\\n\", collection[0].asCharString());\r\n\tSTRCMP_EQUAL(\"world\\n\", collection[1].asCharString());\r\n\tSTRCMP_EQUAL(\"how\\n\", collection[2].asCharString());\r\n\tSTRCMP_EQUAL(\"do\\n\", collection[3].asCharString());\r\n\tSTRCMP_EQUAL(\"you\\n\", collection[4].asCharString());\r\n\tSTRCMP_EQUAL(\"do\\n\", collection[5].asCharString());\r\n\tSTRCMP_EQUAL(\"\\n\", collection[6].asCharString());\r\n}\r\n\r\nTEST(SimpleString, splitNoTokenOnTheEnd)\r\n{\r\n\tSimpleString string(\"Bah Yah oops\");\r\n SimpleStringCollection collection;\r\n\r\n\tstring.split(\" \", collection);\r\n\tLONGS_EQUAL(3, collection.size());\r\n\tSTRCMP_EQUAL(\"Bah \", collection[0].asCharString());\r\n\tSTRCMP_EQUAL(\"Yah \", collection[1].asCharString());\r\n\tSTRCMP_EQUAL(\"oops\", collection[2].asCharString());\r\n}\r\n\r\nTEST(SimpleString, count)\r\n{\r\n\tSimpleString str(\"ha ha ha ha\");\r\n\tLONGS_EQUAL(4, str.count(\"ha\"));\r\n}\r\n\r\nTEST(SimpleString, countTogether)\r\n{\r\n\tSimpleString str(\"hahahaha\");\r\n\tLONGS_EQUAL(4, str.count(\"ha\"));\r\n}\r\n\r\nTEST(SimpleString, endsWith)\r\n{\r\n\tSimpleString str(\"Hello World\");\r\n\tCHECK(str.endsWith(\"World\"));\r\n\tCHECK(!str.endsWith(\"Worl\"));\r\n\tCHECK(!str.endsWith(\"Hello\"));\r\n\tSimpleString str2(\"ah\");\r\n\tCHECK(str2.endsWith(\"ah\"));\r\n\tCHECK(!str2.endsWith(\"baah\"));\r\n\tSimpleString str3(\"\");\r\n\tCHECK(!str3.endsWith(\"baah\"));\r\n\r\n\tSimpleString str4(\"ha ha ha ha\");\r\n\tCHECK(str4.endsWith(\"ha\"));\r\n}\r\n\r\nTEST(SimpleString, replaceCharWithChar)\r\n{\r\n\tSimpleString str(\"abcabcabca\");\r\n\tstr.replace('a','b');\r\n\tSTRCMP_EQUAL(\"bbcbbcbbcb\", str.asCharString());\r\n}\r\n\r\nTEST(SimpleString, replaceStringWithString)\r\n{\r\n\tSimpleString str(\"boo baa boo baa boo\");\r\n\tstr.replace(\"boo\",\"boohoo\");\r\n\tSTRCMP_EQUAL(\"boohoo baa boohoo baa boohoo\", str.asCharString());\r\n}\r\n\r\nTEST(SimpleString, ContainsNull)\r\n{\r\n\tSimpleString s(0);\r\n\tCHECK(!s.contains(\"something\"));\r\n}\r\n\r\nTEST(SimpleString, Characters)\r\n{\r\n SimpleString s(StringFrom('a'));\r\n SimpleString s2(StringFrom('a'));\r\n CHECK(s == s2);\r\n}\r\n\r\nTEST(SimpleString, Doubles)\r\n{\r\n\tSimpleString s(StringFrom(1.2));\r\n\tSTRCMP_EQUAL(\"1.200000\", s.asCharString());\r\n\ts = StringFrom(1.2,2);\r\n\tSTRCMP_EQUAL(\"1.20\", s.asCharString());\r\n}\r\n\r\nTEST(SimpleString, HexStrings)\r\n{\r\n SimpleString h1 = HexStringFrom(0xffff);\r\n STRCMP_EQUAL(\"fffe\", h1.asCharString());\r\n}\r\n\r\nTEST(SimpleString, StringFromFormat)\r\n{\r\n SimpleString h1 = StringFromFormat(\"%s %s! %d\", \"Hello\", \"World\", 2009);\r\n STRCMP_EQUAL(\"Hello World! 2009\", h1.asCharString());\r\n}\r\n\r\nTEST(SimpleString, StringFromFormatLarge)\r\n{\r\n const char* s = \"ThisIsAPrettyLargeStringAndIfWeAddThisManyTimesToABufferItWillbeFull\";\r\n SimpleString h1 = StringFromFormat(\"%s%s%s%s%s%s%s%s%s%s\", s, s, s, s, s, s, s, s, s, s);\r\n LONGS_EQUAL(10, h1.count(s));\r\n}\r\n\r\nstatic int WrappedUpVSNPrintf(char* buf, int n, const char* format, ...)\r\n{\r\n va_list arguments;\r\n va_start(arguments, format);\r\n\r\n int result = PlatformSpecificVSNprintf(buf, n, format, arguments);\r\n va_end(arguments);\r\n return result;\r\n}\r\n\r\nTEST(SimpleString, PlatformSpecificSprintf_fits)\r\n{\r\n char buf[10];\r\n\r\n int count = WrappedUpVSNPrintf(buf, sizeof(buf), \"%s\", \"12345\");\r\n STRCMP_EQUAL(\"12345\", buf);\r\n LONGS_EQUAL(5, count);\r\n}\r\n\r\nTEST(SimpleString, PlatformSpecificSprintf_doesNotFit)\r\n{\r\n char buf[10];\r\n\r\n int count = WrappedUpVSNPrintf(buf, sizeof(buf), \"%s\", \"12345678901\");\r\n STRCMP_EQUAL(\"123456789\", buf);\r\n LONGS_EQUAL(11, count);\r\n}\r\n\r\nTEST(SimpleString, NullParameters2)\r\n{\r\n\tSimpleString* arr = new SimpleString[100];\r\n\tdelete [] arr;\r\n}\r\n\r\n\r\nTEST(SimpleString, CollectionMultipleAllocateNoLeaksMemory)\r\n{\r\n SimpleStringCollection col;\r\n col.allocate(5);\r\n col.allocate(5);\r\n \/\/ CHECK no memory leak\r\n}\r\n\r\nTEST(SimpleString, CollectionReadOutOfBoundsReturnsEmptyString)\r\n{\r\n SimpleStringCollection col;\r\n col.allocate(3);\r\n STRCMP_EQUAL(\"\", col[3].asCharString());\r\n}\r\n\r\nTEST(SimpleString, CollectionWritingToEmptyString)\r\n{\r\n SimpleStringCollection col;\r\n col.allocate(3);\r\n col[3] = SimpleString(\"HAH\");\r\n STRCMP_EQUAL(\"\", col[3].asCharString());\r\n}\r\nfixed intentional error to test hudson CI\/*\r\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * * Redistributions of source code must retain the above copyright\r\n * notice, this list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright\r\n * notice, this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * * Neither the name of the nor the\r\n * names of its contributors may be used to endorse or promote products\r\n * derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include \"CppUTest\/TestHarness.h\"\r\n#include \"CppUTest\/SimpleString.h\"\r\n#include \"CppUTest\/PlatformSpecificFunctions.h\"\r\n\r\n#include \"CppUTest\/MemoryLeakDetector.h\" \/\/ REMOVE THIS AFTER THE VC++ EXPRESS IS FIXED!\r\n\r\nTEST_GROUP(SimpleString)\r\n{\r\n\tvoid setup()\r\n\t{\r\n\t\tMemoryLeakWarningPlugin::getGlobalDetector()->disableAllocationTypeChecking (); \/\/ REMOVE THIS AFTER THE VC++ EXPRESS IS FIXED!\r\n\t}\r\n\r\n\tvoid teardown()\r\n\t{\r\n\t\tMemoryLeakWarningPlugin::getGlobalDetector()->enableAllocationTypeChecking (); \/\/ REMOVE THIS AFTER THE VC++ EXPRESS IS FIXED!\r\n\t}\r\n};\r\n\r\nTEST(SimpleString, CreateSequence)\r\n{\r\n SimpleString expected(\"hellohello\");\r\n SimpleString actual(\"hello\", 2);\r\n\r\n CHECK_EQUAL(expected, actual);\r\n}\r\n\r\nTEST(SimpleString, CreateSequenceOfZero)\r\n{\r\n SimpleString expected(\"\");\r\n SimpleString actual(\"hello\", 0);\r\n\r\n CHECK_EQUAL(expected, actual);\r\n}\r\n\r\nTEST(SimpleString, Copy)\r\n{\r\n SimpleString s1(\"hello\");\r\n SimpleString s2(s1);\r\n\r\n CHECK_EQUAL(s1, s2);\r\n}\r\n\r\nTEST(SimpleString, Assignment)\r\n{\r\n SimpleString s1(\"hello\");\r\n SimpleString s2(\"goodbye\");\r\n\r\n s2 = s1;\r\n\r\n CHECK_EQUAL(s1, s2);\r\n}\r\n\r\nTEST(SimpleString, Equality)\r\n{\r\n SimpleString s1(\"hello\");\r\n SimpleString s2(\"hello\");\r\n\r\n CHECK(s1 == s2);\r\n}\r\n\r\nTEST(SimpleString, InEquality)\r\n{\r\n SimpleString s1(\"hello\");\r\n SimpleString s2(\"goodbye\");\r\n\r\n CHECK(s1 != s2);\r\n}\r\n\r\nTEST(SimpleString, asCharString)\r\n{\r\n SimpleString s1(\"hello\");\r\n\r\n STRCMP_EQUAL(\"hello\", s1.asCharString());\r\n}\r\n\r\nTEST(SimpleString, Size)\r\n{\r\n SimpleString s1(\"hello!\");\r\n\r\n LONGS_EQUAL(6, s1.size());\r\n}\r\n\r\nTEST(SimpleString, Addition)\r\n{\r\n SimpleString s1(\"hello!\");\r\n SimpleString s2(\"goodbye!\");\r\n SimpleString s3(\"hello!goodbye!\");\r\n SimpleString s4;\r\n s4 = s1 + s2;\r\n\r\n CHECK_EQUAL(s3, s4);\r\n}\r\n\r\nTEST(SimpleString, Concatenation)\r\n{\r\n SimpleString s1(\"hello!\");\r\n SimpleString s2(\"goodbye!\");\r\n SimpleString s3(\"hello!goodbye!\");\r\n SimpleString s4;\r\n s4 += s1;\r\n s4 += s2;\r\n\r\n CHECK_EQUAL(s3, s4);\r\n\r\n SimpleString s5(\"hello!goodbye!hello!goodbye!\");\r\n s4 += s4;\r\n\r\n CHECK_EQUAL(s5, s4);\r\n}\r\n\r\n\r\nTEST(SimpleString, Contains)\r\n{\r\n SimpleString s(\"hello!\");\r\n SimpleString empty(\"\");\r\n SimpleString beginning(\"hello\");\r\n SimpleString end(\"lo!\");\r\n SimpleString mid(\"l\");\r\n SimpleString notPartOfString(\"xxxx\");\r\n\r\n CHECK(s.contains(empty));\r\n CHECK(s.contains(beginning));\r\n CHECK(s.contains(end));\r\n CHECK(s.contains(mid));\r\n CHECK(!s.contains(notPartOfString));\r\n\r\n CHECK(empty.contains(empty));\r\n CHECK(!empty.contains(s));\r\n}\r\n\r\nTEST(SimpleString, startsWith)\r\n{\r\n\tSimpleString hi(\"Hi you!\");\r\n\tSimpleString part(\"Hi\");\r\n\tSimpleString diff(\"Hrrm Hi you! ffdsfd\");\r\n\tCHECK(hi.startsWith(part));\r\n\tCHECK(!part.startsWith(hi));\r\n\tCHECK(!diff.startsWith(hi));\r\n}\r\n\r\nTEST(SimpleString, split)\r\n{\r\n\tSimpleString hi(\"hello\\nworld\\nhow\\ndo\\nyou\\ndo\\n\\n\");\r\n\r\n\tSimpleStringCollection collection;\r\n\thi.split(\"\\n\", collection);\r\n\r\n\tLONGS_EQUAL(7, collection.size());\r\n\tSTRCMP_EQUAL(\"hello\\n\", collection[0].asCharString());\r\n\tSTRCMP_EQUAL(\"world\\n\", collection[1].asCharString());\r\n\tSTRCMP_EQUAL(\"how\\n\", collection[2].asCharString());\r\n\tSTRCMP_EQUAL(\"do\\n\", collection[3].asCharString());\r\n\tSTRCMP_EQUAL(\"you\\n\", collection[4].asCharString());\r\n\tSTRCMP_EQUAL(\"do\\n\", collection[5].asCharString());\r\n\tSTRCMP_EQUAL(\"\\n\", collection[6].asCharString());\r\n}\r\n\r\nTEST(SimpleString, splitNoTokenOnTheEnd)\r\n{\r\n\tSimpleString string(\"Bah Yah oops\");\r\n SimpleStringCollection collection;\r\n\r\n\tstring.split(\" \", collection);\r\n\tLONGS_EQUAL(3, collection.size());\r\n\tSTRCMP_EQUAL(\"Bah \", collection[0].asCharString());\r\n\tSTRCMP_EQUAL(\"Yah \", collection[1].asCharString());\r\n\tSTRCMP_EQUAL(\"oops\", collection[2].asCharString());\r\n}\r\n\r\nTEST(SimpleString, count)\r\n{\r\n\tSimpleString str(\"ha ha ha ha\");\r\n\tLONGS_EQUAL(4, str.count(\"ha\"));\r\n}\r\n\r\nTEST(SimpleString, countTogether)\r\n{\r\n\tSimpleString str(\"hahahaha\");\r\n\tLONGS_EQUAL(4, str.count(\"ha\"));\r\n}\r\n\r\nTEST(SimpleString, endsWith)\r\n{\r\n\tSimpleString str(\"Hello World\");\r\n\tCHECK(str.endsWith(\"World\"));\r\n\tCHECK(!str.endsWith(\"Worl\"));\r\n\tCHECK(!str.endsWith(\"Hello\"));\r\n\tSimpleString str2(\"ah\");\r\n\tCHECK(str2.endsWith(\"ah\"));\r\n\tCHECK(!str2.endsWith(\"baah\"));\r\n\tSimpleString str3(\"\");\r\n\tCHECK(!str3.endsWith(\"baah\"));\r\n\r\n\tSimpleString str4(\"ha ha ha ha\");\r\n\tCHECK(str4.endsWith(\"ha\"));\r\n}\r\n\r\nTEST(SimpleString, replaceCharWithChar)\r\n{\r\n\tSimpleString str(\"abcabcabca\");\r\n\tstr.replace('a','b');\r\n\tSTRCMP_EQUAL(\"bbcbbcbbcb\", str.asCharString());\r\n}\r\n\r\nTEST(SimpleString, replaceStringWithString)\r\n{\r\n\tSimpleString str(\"boo baa boo baa boo\");\r\n\tstr.replace(\"boo\",\"boohoo\");\r\n\tSTRCMP_EQUAL(\"boohoo baa boohoo baa boohoo\", str.asCharString());\r\n}\r\n\r\nTEST(SimpleString, ContainsNull)\r\n{\r\n\tSimpleString s(0);\r\n\tCHECK(!s.contains(\"something\"));\r\n}\r\n\r\nTEST(SimpleString, Characters)\r\n{\r\n SimpleString s(StringFrom('a'));\r\n SimpleString s2(StringFrom('a'));\r\n CHECK(s == s2);\r\n}\r\n\r\nTEST(SimpleString, Doubles)\r\n{\r\n\tSimpleString s(StringFrom(1.2));\r\n\tSTRCMP_EQUAL(\"1.200000\", s.asCharString());\r\n\ts = StringFrom(1.2,2);\r\n\tSTRCMP_EQUAL(\"1.20\", s.asCharString());\r\n}\r\n\r\nTEST(SimpleString, HexStrings)\r\n{\r\n SimpleString h1 = HexStringFrom(0xffff);\r\n STRCMP_EQUAL(\"ffff\", h1.asCharString());\r\n}\r\n\r\nTEST(SimpleString, StringFromFormat)\r\n{\r\n SimpleString h1 = StringFromFormat(\"%s %s! %d\", \"Hello\", \"World\", 2009);\r\n STRCMP_EQUAL(\"Hello World! 2009\", h1.asCharString());\r\n}\r\n\r\nTEST(SimpleString, StringFromFormatLarge)\r\n{\r\n const char* s = \"ThisIsAPrettyLargeStringAndIfWeAddThisManyTimesToABufferItWillbeFull\";\r\n SimpleString h1 = StringFromFormat(\"%s%s%s%s%s%s%s%s%s%s\", s, s, s, s, s, s, s, s, s, s);\r\n LONGS_EQUAL(10, h1.count(s));\r\n}\r\n\r\nstatic int WrappedUpVSNPrintf(char* buf, int n, const char* format, ...)\r\n{\r\n va_list arguments;\r\n va_start(arguments, format);\r\n\r\n int result = PlatformSpecificVSNprintf(buf, n, format, arguments);\r\n va_end(arguments);\r\n return result;\r\n}\r\n\r\nTEST(SimpleString, PlatformSpecificSprintf_fits)\r\n{\r\n char buf[10];\r\n\r\n int count = WrappedUpVSNPrintf(buf, sizeof(buf), \"%s\", \"12345\");\r\n STRCMP_EQUAL(\"12345\", buf);\r\n LONGS_EQUAL(5, count);\r\n}\r\n\r\nTEST(SimpleString, PlatformSpecificSprintf_doesNotFit)\r\n{\r\n char buf[10];\r\n\r\n int count = WrappedUpVSNPrintf(buf, sizeof(buf), \"%s\", \"12345678901\");\r\n STRCMP_EQUAL(\"123456789\", buf);\r\n LONGS_EQUAL(11, count);\r\n}\r\n\r\nTEST(SimpleString, NullParameters2)\r\n{\r\n\tSimpleString* arr = new SimpleString[100];\r\n\tdelete [] arr;\r\n}\r\n\r\n\r\nTEST(SimpleString, CollectionMultipleAllocateNoLeaksMemory)\r\n{\r\n SimpleStringCollection col;\r\n col.allocate(5);\r\n col.allocate(5);\r\n \/\/ CHECK no memory leak\r\n}\r\n\r\nTEST(SimpleString, CollectionReadOutOfBoundsReturnsEmptyString)\r\n{\r\n SimpleStringCollection col;\r\n col.allocate(3);\r\n STRCMP_EQUAL(\"\", col[3].asCharString());\r\n}\r\n\r\nTEST(SimpleString, CollectionWritingToEmptyString)\r\n{\r\n SimpleStringCollection col;\r\n col.allocate(3);\r\n col[3] = SimpleString(\"HAH\");\r\n STRCMP_EQUAL(\"\", col[3].asCharString());\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nTEST(macro_ASSERT_TRUE, simple_expressions_pass)\n{\n ASSERT_TRUE(true);\n ASSERT_TRUE(!false);\n ASSERT_TRUE(1 == 2);\n ASSERT_TRUE(2 != 5);\n ASSERT_TRUE(1 < 10);\n ASSERT_TRUE(100 > 2.34);\n ASSERT_TRUE(10 > 2);\n ASSERT_TRUE(1.123 < 3.14);\n ASSERT_TRUE(\"foo\" == \"foo\");\n ASSERT_TRUE(\"ciphertext\" != \"plaintext\");\n}\n\nTEST(macro_ASSERT_FALSE, simple_expressions_pass)\n{\n ASSERT_FALSE(false);\n ASSERT_FALSE(!true);\n ASSERT_FALSE(1 != 2);\n ASSERT_FALSE(2 == 5);\n ASSERT_FALSE(1 > 10);\n ASSERT_FALSE(100 < 2.34);\n ASSERT_FALSE(10 < 2);\n ASSERT_FALSE(1.123 > 3.14);\n ASSERT_FALSE(\"foo\" != \"foo\");\n ASSERT_FALSE(\"ciphertext\" == \"plaintext\");\n}\n\nTEST(macro_ASSERT_EQ, strings_test_out_equal)\n{\n ASSERT_EQ(\"\", \"\");\n ASSERT_EQ(\"a\", \"a\");\n ASSERT_EQ(\"murrekatt\", \"murrekatt\");\n ASSERT_EQ(\"this is a longer string with some special chars!@#\", \"this is a longer string with some special chars!@#\");\n}\n\nTEST(macro_ASSERT_EQ, string_objects_test_out_equal)\n{\n std::string s1;\n std::string s2;\n ASSERT_EQ(s1, s1);\n}\n\nTEST(macro_ASSERT_NEQ, string_objects_test_out_not_equal)\n{\n std::string s1(\"foo\");\n std::string s2(\"bar\");\n ASSERT_NEQ(s1, s2);\n}\n\nTEST(macro_ASSERT_STREQ, conversion_to_string_objects_tests_out_equal)\n{\n ASSERT_STREQ(\"murrekatt\", \"murrekatt\");\n}\n\nTEST(macro_ASSERT_NEAR, floats_test_out_to_equal_within_given_epsilon)\n{\n ASSERT_NEAR(3.1415, M_PI, 0.0001);\n}\n\nnamespace\n{\n\nstruct Example\n{\n int value() { return 42; }\n};\n\nstruct ExampleFixture\n{\n Example e_;\n};\n\n} \/\/ namespace\n\nTEST_F(ExampleFixture, when_doing_this_that_will_happen_as_a_result)\n{\n \/\/ Arrange\n \/\/ Act\n \/\/ Assert\n ASSERT_EQ(42, e_.value());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTEST(Example, simple_test_of_something_that_should_result_in_something)\n{\n \/\/ Arrange\n Example e;\n \/\/ Act\n int value = e.value();\n \/\/ Assert\n ASSERT_EQ(42, value);\n}\nMinor adjustment in test descriptions.#include \n#include \n#include \n\nTEST(macro_ASSERT_TRUE, simple_expressions_equal_true)\n{\n ASSERT_TRUE(true);\n ASSERT_TRUE(!false);\n ASSERT_TRUE(1 == 2);\n ASSERT_TRUE(2 != 5);\n ASSERT_TRUE(1 < 10);\n ASSERT_TRUE(100 > 2.34);\n ASSERT_TRUE(10 > 2);\n ASSERT_TRUE(1.123 < 3.14);\n ASSERT_TRUE(\"foo\" == \"foo\");\n ASSERT_TRUE(\"ciphertext\" != \"plaintext\");\n}\n\nTEST(macro_ASSERT_FALSE, simple_expressions_equal_false)\n{\n ASSERT_FALSE(false);\n ASSERT_FALSE(!true);\n ASSERT_FALSE(1 != 2);\n ASSERT_FALSE(2 == 5);\n ASSERT_FALSE(1 > 10);\n ASSERT_FALSE(100 < 2.34);\n ASSERT_FALSE(10 < 2);\n ASSERT_FALSE(1.123 > 3.14);\n ASSERT_FALSE(\"foo\" != \"foo\");\n ASSERT_FALSE(\"ciphertext\" == \"plaintext\");\n}\n\nTEST(macro_ASSERT_EQ, strings_test_out_equal)\n{\n ASSERT_EQ(\"\", \"\");\n ASSERT_EQ(\"a\", \"a\");\n ASSERT_EQ(\"murrekatt\", \"murrekatt\");\n ASSERT_EQ(\"this is a longer string with some special chars!@#\", \"this is a longer string with some special chars!@#\");\n}\n\nTEST(macro_ASSERT_EQ, string_objects_test_out_equal)\n{\n std::string s1;\n std::string s2;\n ASSERT_EQ(s1, s1);\n}\n\nTEST(macro_ASSERT_NEQ, string_objects_test_out_not_equal)\n{\n std::string s1(\"foo\");\n std::string s2(\"bar\");\n ASSERT_NEQ(s1, s2);\n}\n\nTEST(macro_ASSERT_STREQ, conversion_to_string_objects_tests_out_equal)\n{\n ASSERT_STREQ(\"murrekatt\", \"murrekatt\");\n}\n\nTEST(macro_ASSERT_NEAR, floats_test_out_to_equal_within_given_epsilon)\n{\n ASSERT_NEAR(3.1415, M_PI, 0.0001);\n}\n\nnamespace\n{\n\nstruct Example\n{\n int value() { return 42; }\n};\n\nstruct ExampleFixture\n{\n Example e_;\n};\n\n} \/\/ namespace\n\nTEST_F(ExampleFixture, when_doing_this_that_will_happen_as_a_result)\n{\n \/\/ Arrange\n \/\/ Act\n \/\/ Assert\n ASSERT_EQ(42, e_.value());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTEST(Example, simple_test_of_something_that_should_result_in_something)\n{\n \/\/ Arrange\n Example e;\n \/\/ Act\n int value = e.value();\n \/\/ Assert\n ASSERT_EQ(42, value);\n}\n<|endoftext|>"} {"text":"\/* RMSDCalculator.C\n*\n* Copyright (C) 2011 Marcel Schumann\n*\n* This program free software; you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation; either version 3 of the License, or (at\n* your option) any later version.\n*\n* This program is distributed in the hope that it will be useful, but\n* WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program; if not, see .\n*\/\n\n\/\/ ----------------------------------------------------\n\/\/ $Maintainer: Marcel Schumann $\n\/\/ $Authors: Marcel Schumann $\n\/\/ ----------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"version.h\"\n\nusing namespace BALL;\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n\tCommandlineParser parpars(\"RMSDCalculator\", \"calculate RMSD between poses\", VERSION, String(__DATE__), \"Analysis\");\n\tparpars.registerParameter(\"i\", \"input molecule file\", INFILE, true);\n\tparpars.registerParameter(\"org\", \"molecule file containing the original ('true') poses\", INFILE, true);\n\tparpars.registerParameter(\"o\", \"output molecule file\", OUTFILE);\n\tparpars.registerFlag(\"quiet\", \"by quiet, i.e. do not print progress information\");\n\tString man = \"This tool calculates the RMSD between different conformations of the same molecule.\\n\\nTherefore this tool can for example be used to evaluate the different between ligands taken from co-crystal structures and their poses generated by a docking.\\nMolecules may be sorted differently in the two input files; a topology hashkey will be used to match molecules to each other.\\n\\nOutput of this tool is a molecule file which will for each molecule contain a property-tag 'RMSD' holding the calculated RMSD value.\";\n\tparpars.setToolManual(man);\n\tparpars.setSupportedFormats(\"i\",MolFileFactory::getSupportedFormats());\n\tparpars.setSupportedFormats(\"org\",MolFileFactory::getSupportedFormats());\n\tparpars.setSupportedFormats(\"o\",\"mol2,sdf,drf\");\n\tparpars.setOutputFormatSource(\"o\",\"i\");\n\tparpars.parse(argc, argv);\n\n\t\/\/ Retrieve coordinates of original poses\n\tGenericMolFile* original = MolFileFactory::open(parpars.get(\"org\"));\n\tHashMap > original_poses;\n\tfor (Molecule* mol = original->read(); mol; delete mol, mol = original->read())\n\t{\n\t\tString topology_hash;\n\t\tFlexibleMolecule::generateTopologyHash(mol, topology_hash, true);\n\t\tif (original_poses.find(topology_hash) != original_poses.end())\n\t\t{\n\t\t\tLog<<\"[Warning:] more than one 'original' conformation for a molecule detected. Will use only the first conformation and ignore all other.\"< l;\n\t\t\tHashMap >::iterator map_it = original_poses.insert(make_pair(topology_hash, l)).first;\n\n\t\t\tfor (AtomConstIterator it = mol->beginAtom(); +it; it++)\n\t\t\t{\n\t\t\t\tif (it->getElement().getSymbol() != \"H\")\n\t\t\t\t{\n\t\t\t\t\tmap_it->second.push_back(it->getPosition());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdelete original;\n\n\t\/\/ Retrieve coordinates of input poses and calculate RMSDs\n\tGenericMolFile* input = MolFileFactory::open(parpars.get(\"i\"));\n\tGenericMolFile* output = 0;\n\tString filename = parpars.get(\"o\");\n\tif (filename != CommandlineParser::NOT_FOUND)\n\t{\n\t\toutput = MolFileFactory::open(filename, ios::out, input);\n\t}\n\n\tdouble average_RMSD = 0;\n\tint no_mols = 0;\n\tint no_valid_rmsds = 0;\n\tbool quiet = (parpars.get(\"quiet\")!=CommandlineParser::NOT_FOUND);\n\n\tfor (Molecule* mol = input->read(); mol; delete mol, mol = input->read())\n\t{\n\t\tno_mols++;\n\t\tString topology_hash;\n\t\tFlexibleMolecule::generateTopologyHash(mol, topology_hash, true);\n\n\t\tHashMap >::iterator map_it = original_poses.find(topology_hash);\n\t\tif (map_it == original_poses.end())\n\t\t{\n\t\t\tLog<<\"[Warning:] no original pose for molecule '\"<getName()<<\"' found, its RMSD can thus not be computed.\"<setProperty(\"RMSD\", \"N\/A\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble RMSD = 0;\n\t\t\tlist::iterator list_it = map_it->second.begin();\n\t\t\tint no_heavy_atoms = 0;\n\t\t\tAtomConstIterator it = mol->beginAtom();\n\t\t\tfor (; +it ; it++)\n\t\t\t{\n\t\t\t\tif (it->getElement().getSymbol() != \"H\" && list_it != map_it->second.end())\n\t\t\t\t{\n\t\t\t\t\tRMSD += pow(it->getPosition().getDistance(*list_it), 2);\n\t\t\t\t\tno_heavy_atoms++;\n\t\t\t\t\tlist_it++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (it != mol->endAtom() || list_it != map_it->second.end())\n\t\t\t{\n\t\t\t\tLog.error()<<\"[Error:] Number of heavy atoms of input pose do not match number of heavy atoms of original pose!!\"<setProperty(\"RMSD\", RMSD);\n\t\t\taverage_RMSD += RMSD;\n\t\t\tno_valid_rmsds++;\n\n\t\t\tif (!quiet) Log << \"RMSD for molecule \"<getName()<<\"' = \"<Removed the inaccurate license\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"version.h\"\n\nusing namespace BALL;\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n\tCommandlineParser parpars(\"RMSDCalculator\", \"calculate RMSD between poses\", VERSION, String(__DATE__), \"Analysis\");\n\tparpars.registerParameter(\"i\", \"input molecule file\", INFILE, true);\n\tparpars.registerParameter(\"org\", \"molecule file containing the original ('true') poses\", INFILE, true);\n\tparpars.registerParameter(\"o\", \"output molecule file\", OUTFILE);\n\tparpars.registerFlag(\"quiet\", \"by quiet, i.e. do not print progress information\");\n\tString man = \"This tool calculates the RMSD between different conformations of the same molecule.\\n\\nTherefore this tool can for example be used to evaluate the different between ligands taken from co-crystal structures and their poses generated by a docking.\\nMolecules may be sorted differently in the two input files; a topology hashkey will be used to match molecules to each other.\\n\\nOutput of this tool is a molecule file which will for each molecule contain a property-tag 'RMSD' holding the calculated RMSD value.\";\n\tparpars.setToolManual(man);\n\tparpars.setSupportedFormats(\"i\",MolFileFactory::getSupportedFormats());\n\tparpars.setSupportedFormats(\"org\",MolFileFactory::getSupportedFormats());\n\tparpars.setSupportedFormats(\"o\",\"mol2,sdf,drf\");\n\tparpars.setOutputFormatSource(\"o\",\"i\");\n\tparpars.parse(argc, argv);\n\n\t\/\/ Retrieve coordinates of original poses\n\tGenericMolFile* original = MolFileFactory::open(parpars.get(\"org\"));\n\tHashMap > original_poses;\n\tfor (Molecule* mol = original->read(); mol; delete mol, mol = original->read())\n\t{\n\t\tString topology_hash;\n\t\tFlexibleMolecule::generateTopologyHash(mol, topology_hash, true);\n\t\tif (original_poses.find(topology_hash) != original_poses.end())\n\t\t{\n\t\t\tLog<<\"[Warning:] more than one 'original' conformation for a molecule detected. Will use only the first conformation and ignore all other.\"< l;\n\t\t\tHashMap >::iterator map_it = original_poses.insert(make_pair(topology_hash, l)).first;\n\n\t\t\tfor (AtomConstIterator it = mol->beginAtom(); +it; it++)\n\t\t\t{\n\t\t\t\tif (it->getElement().getSymbol() != \"H\")\n\t\t\t\t{\n\t\t\t\t\tmap_it->second.push_back(it->getPosition());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdelete original;\n\n\t\/\/ Retrieve coordinates of input poses and calculate RMSDs\n\tGenericMolFile* input = MolFileFactory::open(parpars.get(\"i\"));\n\tGenericMolFile* output = 0;\n\tString filename = parpars.get(\"o\");\n\tif (filename != CommandlineParser::NOT_FOUND)\n\t{\n\t\toutput = MolFileFactory::open(filename, ios::out, input);\n\t}\n\n\tdouble average_RMSD = 0;\n\tint no_mols = 0;\n\tint no_valid_rmsds = 0;\n\tbool quiet = (parpars.get(\"quiet\")!=CommandlineParser::NOT_FOUND);\n\n\tfor (Molecule* mol = input->read(); mol; delete mol, mol = input->read())\n\t{\n\t\tno_mols++;\n\t\tString topology_hash;\n\t\tFlexibleMolecule::generateTopologyHash(mol, topology_hash, true);\n\n\t\tHashMap >::iterator map_it = original_poses.find(topology_hash);\n\t\tif (map_it == original_poses.end())\n\t\t{\n\t\t\tLog<<\"[Warning:] no original pose for molecule '\"<getName()<<\"' found, its RMSD can thus not be computed.\"<setProperty(\"RMSD\", \"N\/A\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble RMSD = 0;\n\t\t\tlist::iterator list_it = map_it->second.begin();\n\t\t\tint no_heavy_atoms = 0;\n\t\t\tAtomConstIterator it = mol->beginAtom();\n\t\t\tfor (; +it ; it++)\n\t\t\t{\n\t\t\t\tif (it->getElement().getSymbol() != \"H\" && list_it != map_it->second.end())\n\t\t\t\t{\n\t\t\t\t\tRMSD += pow(it->getPosition().getDistance(*list_it), 2);\n\t\t\t\t\tno_heavy_atoms++;\n\t\t\t\t\tlist_it++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (it != mol->endAtom() || list_it != map_it->second.end())\n\t\t\t{\n\t\t\t\tLog.error()<<\"[Error:] Number of heavy atoms of input pose do not match number of heavy atoms of original pose!!\"<setProperty(\"RMSD\", RMSD);\n\t\t\taverage_RMSD += RMSD;\n\t\t\tno_valid_rmsds++;\n\n\t\t\tif (!quiet) Log << \"RMSD for molecule \"<getName()<<\"' = \"<"} {"text":"\/\/===-- ProcessLauncherLinux.cpp --------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Host\/linux\/ProcessLauncherLinux.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Host\/FileSpec.h\"\n#include \"lldb\/Host\/Host.h\"\n#include \"lldb\/Host\/HostProcess.h\"\n#include \"lldb\/Host\/Pipe.h\"\n#include \"lldb\/Target\/ProcessLaunchInfo.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace lldb;\nusing namespace lldb_private;\n\nstatic void FixupEnvironment(Args &env) {\n#ifdef __ANDROID_NDK__\n \/\/ If there is no PATH variable specified inside the environment then set the\n \/\/ path to \/system\/bin. It is required because the default path used by\n \/\/ execve() is wrong on android.\n static const char *path = \"PATH=\";\n for (auto &entry : entries) {\n if (entry.ref.startswith(path))\n return;\n }\n env.AppendArgument(llvm::StringRef(\"PATH=\/system\/bin\"));\n#endif\n}\n\nstatic void LLVM_ATTRIBUTE_NORETURN ExitWithError(int error_fd,\n const char *operation) {\n std::ostringstream os;\n os << operation << \" failed: \" << strerror(errno);\n write(error_fd, os.str().data(), os.str().size());\n close(error_fd);\n _exit(1);\n}\n\nstatic void DupDescriptor(int error_fd, const FileSpec &file_spec, int fd,\n int flags) {\n int target_fd = ::open(file_spec.GetCString(), flags, 0666);\n\n if (target_fd == -1)\n ExitWithError(error_fd, \"DupDescriptor-open\");\n\n if (target_fd == fd)\n return;\n\n if (::dup2(target_fd, fd) == -1)\n ExitWithError(error_fd, \"DupDescriptor-dup2\");\n\n ::close(target_fd);\n return;\n}\n\nstatic void LLVM_ATTRIBUTE_NORETURN ChildFunc(int error_fd,\n const ProcessLaunchInfo &info) {\n \/\/ First, make sure we disable all logging. If we are logging to stdout, our\n \/\/ logs can be\n \/\/ mistaken for inferior output.\n Log::DisableAllLogChannels(nullptr);\n\n \/\/ Do not inherit setgid powers.\n if (setgid(getgid()) != 0)\n ExitWithError(error_fd, \"setgid\");\n\n if (info.GetFlags().Test(eLaunchFlagLaunchInSeparateProcessGroup)) {\n if (setpgid(0, 0) != 0)\n ExitWithError(error_fd, \"setpgid\");\n }\n\n for (size_t i = 0; i < info.GetNumFileActions(); ++i) {\n const FileAction &action = *info.GetFileActionAtIndex(i);\n switch (action.GetAction()) {\n case FileAction::eFileActionClose:\n if (close(action.GetFD()) != 0)\n ExitWithError(error_fd, \"close\");\n break;\n case FileAction::eFileActionDuplicate:\n if (dup2(action.GetFD(), action.GetActionArgument()) == -1)\n ExitWithError(error_fd, \"dup2\");\n break;\n case FileAction::eFileActionOpen:\n DupDescriptor(error_fd, action.GetFileSpec(), action.GetFD(),\n action.GetActionArgument());\n break;\n case FileAction::eFileActionNone:\n break;\n }\n }\n\n const char **argv = info.GetArguments().GetConstArgumentVector();\n\n \/\/ Change working directory\n if (info.GetWorkingDirectory() &&\n 0 != ::chdir(info.GetWorkingDirectory().GetCString()))\n ExitWithError(error_fd, \"chdir\");\n\n \/\/ Disable ASLR if requested.\n if (info.GetFlags().Test(lldb::eLaunchFlagDisableASLR)) {\n const unsigned long personality_get_current = 0xffffffff;\n int value = personality(personality_get_current);\n if (value == -1)\n ExitWithError(error_fd, \"personality get\");\n\n value = personality(ADDR_NO_RANDOMIZE | value);\n if (value == -1)\n ExitWithError(error_fd, \"personality set\");\n }\n\n Args env = info.GetEnvironmentEntries();\n FixupEnvironment(env);\n const char **envp = env.GetConstArgumentVector();\n\n \/\/ Clear the signal mask to prevent the child from being affected by\n \/\/ any masking done by the parent.\n sigset_t set;\n if (sigemptyset(&set) != 0 ||\n pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)\n ExitWithError(error_fd, \"pthread_sigmask\");\n\n if (info.GetFlags().Test(eLaunchFlagDebug)) {\n \/\/ HACK:\n \/\/ Close everything besides stdin, stdout, and stderr that has no file\n \/\/ action to avoid leaking. Only do this when debugging, as elsewhere we\n \/\/ actually rely on\n \/\/ passing open descriptors to child processes.\n for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)\n if (!info.GetFileActionForFD(fd) && fd != error_fd)\n close(fd);\n\n \/\/ Start tracing this child that is about to exec.\n if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1)\n ExitWithError(error_fd, \"ptrace\");\n }\n\n \/\/ Execute. We should never return...\n execve(argv[0], const_cast(argv),\n const_cast(envp));\n\n if (errno == ETXTBSY) {\n \/\/ On android M and earlier we can get this error because the adb deamon can\n \/\/ hold a write\n \/\/ handle on the executable even after it has finished uploading it. This\n \/\/ state lasts\n \/\/ only a short time and happens only when there are many concurrent adb\n \/\/ commands being\n \/\/ issued, such as when running the test suite. (The file remains open when\n \/\/ someone does\n \/\/ an \"adb shell\" command in the fork() child before it has had a chance to\n \/\/ exec.) Since\n \/\/ this state should clear up quickly, wait a while and then give it one\n \/\/ more go.\n usleep(50000);\n execve(argv[0], const_cast(argv),\n const_cast(envp));\n }\n\n \/\/ ...unless exec fails. In which case we definitely need to end the child\n \/\/ here.\n ExitWithError(error_fd, \"execve\");\n}\n\nHostProcess\nProcessLauncherLinux::LaunchProcess(const ProcessLaunchInfo &launch_info,\n Error &error) {\n char exe_path[PATH_MAX];\n launch_info.GetExecutableFile().GetPath(exe_path, sizeof(exe_path));\n\n \/\/ A pipe used by the child process to report errors.\n PipePosix pipe;\n const bool child_processes_inherit = false;\n error = pipe.CreateNew(child_processes_inherit);\n if (error.Fail())\n return HostProcess();\n\n ::pid_t pid = ::fork();\n if (pid == -1) {\n \/\/ Fork failed\n error.SetErrorStringWithFormat(\"Fork failed with error message: %s\",\n strerror(errno));\n return HostProcess(LLDB_INVALID_PROCESS_ID);\n }\n if (pid == 0) {\n \/\/ child process\n pipe.CloseReadFileDescriptor();\n ChildFunc(pipe.ReleaseWriteFileDescriptor(), launch_info);\n }\n\n \/\/ parent process\n\n pipe.CloseWriteFileDescriptor();\n char buf[1000];\n int r = read(pipe.GetReadFileDescriptor(), buf, sizeof buf);\n\n if (r == 0)\n return HostProcess(pid); \/\/ No error. We're done.\n\n error.SetErrorString(buf);\n\n waitpid(pid, nullptr, 0);\n\n return HostProcess();\n}\nFix build error on Android again.\/\/===-- ProcessLauncherLinux.cpp --------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Host\/linux\/ProcessLauncherLinux.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Host\/FileSpec.h\"\n#include \"lldb\/Host\/Host.h\"\n#include \"lldb\/Host\/HostProcess.h\"\n#include \"lldb\/Host\/Pipe.h\"\n#include \"lldb\/Target\/ProcessLaunchInfo.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace lldb;\nusing namespace lldb_private;\n\nstatic void FixupEnvironment(Args &env) {\n#ifdef __ANDROID_NDK__\n \/\/ If there is no PATH variable specified inside the environment then set the\n \/\/ path to \/system\/bin. It is required because the default path used by\n \/\/ execve() is wrong on android.\n static const char *path = \"PATH=\";\n for (auto &entry : env.entries()) {\n if (entry.ref.startswith(path))\n return;\n }\n env.AppendArgument(llvm::StringRef(\"PATH=\/system\/bin\"));\n#endif\n}\n\nstatic void LLVM_ATTRIBUTE_NORETURN ExitWithError(int error_fd,\n const char *operation) {\n std::ostringstream os;\n os << operation << \" failed: \" << strerror(errno);\n write(error_fd, os.str().data(), os.str().size());\n close(error_fd);\n _exit(1);\n}\n\nstatic void DupDescriptor(int error_fd, const FileSpec &file_spec, int fd,\n int flags) {\n int target_fd = ::open(file_spec.GetCString(), flags, 0666);\n\n if (target_fd == -1)\n ExitWithError(error_fd, \"DupDescriptor-open\");\n\n if (target_fd == fd)\n return;\n\n if (::dup2(target_fd, fd) == -1)\n ExitWithError(error_fd, \"DupDescriptor-dup2\");\n\n ::close(target_fd);\n return;\n}\n\nstatic void LLVM_ATTRIBUTE_NORETURN ChildFunc(int error_fd,\n const ProcessLaunchInfo &info) {\n \/\/ First, make sure we disable all logging. If we are logging to stdout, our\n \/\/ logs can be\n \/\/ mistaken for inferior output.\n Log::DisableAllLogChannels(nullptr);\n\n \/\/ Do not inherit setgid powers.\n if (setgid(getgid()) != 0)\n ExitWithError(error_fd, \"setgid\");\n\n if (info.GetFlags().Test(eLaunchFlagLaunchInSeparateProcessGroup)) {\n if (setpgid(0, 0) != 0)\n ExitWithError(error_fd, \"setpgid\");\n }\n\n for (size_t i = 0; i < info.GetNumFileActions(); ++i) {\n const FileAction &action = *info.GetFileActionAtIndex(i);\n switch (action.GetAction()) {\n case FileAction::eFileActionClose:\n if (close(action.GetFD()) != 0)\n ExitWithError(error_fd, \"close\");\n break;\n case FileAction::eFileActionDuplicate:\n if (dup2(action.GetFD(), action.GetActionArgument()) == -1)\n ExitWithError(error_fd, \"dup2\");\n break;\n case FileAction::eFileActionOpen:\n DupDescriptor(error_fd, action.GetFileSpec(), action.GetFD(),\n action.GetActionArgument());\n break;\n case FileAction::eFileActionNone:\n break;\n }\n }\n\n const char **argv = info.GetArguments().GetConstArgumentVector();\n\n \/\/ Change working directory\n if (info.GetWorkingDirectory() &&\n 0 != ::chdir(info.GetWorkingDirectory().GetCString()))\n ExitWithError(error_fd, \"chdir\");\n\n \/\/ Disable ASLR if requested.\n if (info.GetFlags().Test(lldb::eLaunchFlagDisableASLR)) {\n const unsigned long personality_get_current = 0xffffffff;\n int value = personality(personality_get_current);\n if (value == -1)\n ExitWithError(error_fd, \"personality get\");\n\n value = personality(ADDR_NO_RANDOMIZE | value);\n if (value == -1)\n ExitWithError(error_fd, \"personality set\");\n }\n\n Args env = info.GetEnvironmentEntries();\n FixupEnvironment(env);\n const char **envp = env.GetConstArgumentVector();\n\n \/\/ Clear the signal mask to prevent the child from being affected by\n \/\/ any masking done by the parent.\n sigset_t set;\n if (sigemptyset(&set) != 0 ||\n pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)\n ExitWithError(error_fd, \"pthread_sigmask\");\n\n if (info.GetFlags().Test(eLaunchFlagDebug)) {\n \/\/ HACK:\n \/\/ Close everything besides stdin, stdout, and stderr that has no file\n \/\/ action to avoid leaking. Only do this when debugging, as elsewhere we\n \/\/ actually rely on\n \/\/ passing open descriptors to child processes.\n for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)\n if (!info.GetFileActionForFD(fd) && fd != error_fd)\n close(fd);\n\n \/\/ Start tracing this child that is about to exec.\n if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1)\n ExitWithError(error_fd, \"ptrace\");\n }\n\n \/\/ Execute. We should never return...\n execve(argv[0], const_cast(argv),\n const_cast(envp));\n\n if (errno == ETXTBSY) {\n \/\/ On android M and earlier we can get this error because the adb deamon can\n \/\/ hold a write\n \/\/ handle on the executable even after it has finished uploading it. This\n \/\/ state lasts\n \/\/ only a short time and happens only when there are many concurrent adb\n \/\/ commands being\n \/\/ issued, such as when running the test suite. (The file remains open when\n \/\/ someone does\n \/\/ an \"adb shell\" command in the fork() child before it has had a chance to\n \/\/ exec.) Since\n \/\/ this state should clear up quickly, wait a while and then give it one\n \/\/ more go.\n usleep(50000);\n execve(argv[0], const_cast(argv),\n const_cast(envp));\n }\n\n \/\/ ...unless exec fails. In which case we definitely need to end the child\n \/\/ here.\n ExitWithError(error_fd, \"execve\");\n}\n\nHostProcess\nProcessLauncherLinux::LaunchProcess(const ProcessLaunchInfo &launch_info,\n Error &error) {\n char exe_path[PATH_MAX];\n launch_info.GetExecutableFile().GetPath(exe_path, sizeof(exe_path));\n\n \/\/ A pipe used by the child process to report errors.\n PipePosix pipe;\n const bool child_processes_inherit = false;\n error = pipe.CreateNew(child_processes_inherit);\n if (error.Fail())\n return HostProcess();\n\n ::pid_t pid = ::fork();\n if (pid == -1) {\n \/\/ Fork failed\n error.SetErrorStringWithFormat(\"Fork failed with error message: %s\",\n strerror(errno));\n return HostProcess(LLDB_INVALID_PROCESS_ID);\n }\n if (pid == 0) {\n \/\/ child process\n pipe.CloseReadFileDescriptor();\n ChildFunc(pipe.ReleaseWriteFileDescriptor(), launch_info);\n }\n\n \/\/ parent process\n\n pipe.CloseWriteFileDescriptor();\n char buf[1000];\n int r = read(pipe.GetReadFileDescriptor(), buf, sizeof buf);\n\n if (r == 0)\n return HostProcess(pid); \/\/ No error. We're done.\n\n error.SetErrorString(buf);\n\n waitpid(pid, nullptr, 0);\n\n return HostProcess();\n}\n<|endoftext|>"} {"text":"#ifndef IO_HELPERS_HPP_\n#define IO_HELPERS_HPP_\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkTransformFileReader.h\"\n#include \"itkTransformFileWriter.h\"\n\n#include \"PathHelpers.hpp\"\n\nusing namespace std;\n\n\/\/ Reader helpers\nitk::TransformBase::Pointer readTransform(const string& fileName)\n{\n typedef itk::TransformFileReader ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( fileName.c_str() );\n \n try\n {\n reader->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n std::cerr << \"ExceptionObject caught while reading transform.\" << std::endl;\n cerr << err << endl;\n\t\texit(EXIT_FAILURE);\n }\n \n return *(reader->GetTransformList()->begin());\n}\n\ntemplate\ntypename ImageType::Pointer readImage(const string& fileName)\n{\n typedef itk::ImageFileReader< ImageType > ReaderType;\n typename ReaderType::Pointer reader = ReaderType::New();\n\t\n reader->SetFileName( fileName.c_str() );\n\t\n try {\n \treader->Update();\n }\n\tcatch( itk::ExceptionObject & err ) {\n cerr << \"ExceptionObject caught while reading image.\" << endl;\n cerr << err << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\t\n return reader->GetOutput();\n}\n\ntemplate \nvector< typename ImageType::Pointer > readImages(vector< string > fileNames)\n{\n vector< typename ImageType::Pointer > originalImages;\n\t\n\tfor(unsigned int i=0; i(fileNames[i]) );\n\t }\n\t else\n\t {\n\t \/\/ create a new image of zero size\n originalImages.push_back( ImageType::New() );\n\t }\n\t}\n\t\n return originalImages;\n}\n\n\/\/ Writer helpers\n\/\/ const Data\ntemplate\nvoid writeData(const typename DataType::ConstPointer data, const string& fileName)\n{\n typename WriterType::Pointer writer = WriterType::New();\n\t\n\twriter->SetInput( data );\n \/\/ writer->AddTransform( anotherTransform ); \/\/ only applies to writing transforms\n \n writer->SetFileName( fileName.c_str() );\n\t\n try {\n \twriter->Update();\n }\n\tcatch( itk::ExceptionObject & err ) {\n cerr << \"ExceptionObject caught while writing.\" << endl;\n cerr << err << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\n\/\/ Data\ntemplate\nvoid writeData(const typename DataType::Pointer data, const string& fileName)\n{\n writeData< WriterType, DataType >( (typename DataType::ConstPointer) data, fileName);\n}\n\n\/\/ Const Image\ntemplate\nvoid writeImage(const typename ImageType::ConstPointer image, const string& fileName)\n{\n writeData< itk::ImageFileWriter< ImageType >, ImageType >( image, fileName );\n}\n\n\/\/ Image\ntemplate\nvoid writeImage(const typename ImageType::Pointer image, const string& fileName)\n{\n writeData< itk::ImageFileWriter< ImageType >, ImageType >( image, fileName );\n}\n\n\/\/ Transform\nvoid writeTransform(const itk::TransformBase *transform, const string& fileName)\n{\n itk::TransformBase::ConstPointer transformConstPointer(transform);\n writeData< itk::TransformFileWriter, itk::TransformBase >( transformConstPointer, fileName );\n}\n\nbool fileExists(const string& strFilename)\n{\n struct stat stFileInfo;\n bool blnReturn;\n int intStat;\n \n \/\/ Attempt to get the file attributes\n intStat = stat(strFilename.c_str(),&stFileInfo);\n if(intStat == 0) {\n \/\/ We were able to get the file attributes \n \/\/ so the file obviously exists.\n blnReturn = true; \n } else { \n blnReturn = false; \n } \n \n return(blnReturn); \n}\n\n\n#endif\nMoved fileExists.#ifndef IO_HELPERS_HPP_\n#define IO_HELPERS_HPP_\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkTransformFileReader.h\"\n#include \"itkTransformFileWriter.h\"\n\n#include \"PathHelpers.hpp\"\n\nusing namespace std;\n\nbool fileExists(const string& strFilename)\n{\n struct stat stFileInfo;\n bool blnReturn;\n int intStat;\n \n \/\/ Attempt to get the file attributes\n intStat = stat(strFilename.c_str(),&stFileInfo);\n if(intStat == 0) {\n \/\/ We were able to get the file attributes \n \/\/ so the file obviously exists.\n blnReturn = true; \n } else { \n blnReturn = false; \n } \n \n return(blnReturn); \n}\n\n\/\/ Reader helpers\nitk::TransformBase::Pointer readTransform(const string& fileName)\n{\n typedef itk::TransformFileReader ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( fileName.c_str() );\n \n try\n {\n reader->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n std::cerr << \"ExceptionObject caught while reading transform.\" << std::endl;\n cerr << err << endl;\n\t\texit(EXIT_FAILURE);\n }\n \n return *(reader->GetTransformList()->begin());\n}\n\ntemplate\ntypename ImageType::Pointer readImage(const string& fileName)\n{\n typedef itk::ImageFileReader< ImageType > ReaderType;\n typename ReaderType::Pointer reader = ReaderType::New();\n\t\n reader->SetFileName( fileName.c_str() );\n\t\n try {\n \treader->Update();\n }\n\tcatch( itk::ExceptionObject & err ) {\n cerr << \"ExceptionObject caught while reading image.\" << endl;\n cerr << err << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\t\n return reader->GetOutput();\n}\n\ntemplate \nvector< typename ImageType::Pointer > readImages(vector< string > fileNames)\n{\n vector< typename ImageType::Pointer > originalImages;\n\t\n\tfor(unsigned int i=0; i(fileNames[i]) );\n\t }\n\t else\n\t {\n\t \/\/ create a new image of zero size\n originalImages.push_back( ImageType::New() );\n\t }\n\t}\n\t\n return originalImages;\n}\n\n\/\/ Writer helpers\n\/\/ const Data\ntemplate\nvoid writeData(const typename DataType::ConstPointer data, const string& fileName)\n{\n typename WriterType::Pointer writer = WriterType::New();\n\t\n\twriter->SetInput( data );\n \/\/ writer->AddTransform( anotherTransform ); \/\/ only applies to writing transforms\n \n writer->SetFileName( fileName.c_str() );\n\t\n try {\n \twriter->Update();\n }\n\tcatch( itk::ExceptionObject & err ) {\n cerr << \"ExceptionObject caught while writing.\" << endl;\n cerr << err << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\n\/\/ Data\ntemplate\nvoid writeData(const typename DataType::Pointer data, const string& fileName)\n{\n writeData< WriterType, DataType >( (typename DataType::ConstPointer) data, fileName);\n}\n\n\/\/ Const Image\ntemplate\nvoid writeImage(const typename ImageType::ConstPointer image, const string& fileName)\n{\n writeData< itk::ImageFileWriter< ImageType >, ImageType >( image, fileName );\n}\n\n\/\/ Image\ntemplate\nvoid writeImage(const typename ImageType::Pointer image, const string& fileName)\n{\n writeData< itk::ImageFileWriter< ImageType >, ImageType >( image, fileName );\n}\n\n\/\/ Transform\nvoid writeTransform(const itk::TransformBase *transform, const string& fileName)\n{\n itk::TransformBase::ConstPointer transformConstPointer(transform);\n writeData< itk::TransformFileWriter, itk::TransformBase >( transformConstPointer, fileName );\n}\n\n\n#endif\n<|endoftext|>"} {"text":"\/*\n Copyright 2008 Google Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"js_native_wrapper.h\"\n#include \"converter.h\"\n#include \"js_function_slot.h\"\n#include \"js_script_context.h\"\n\nnamespace ggadget {\nnamespace smjs {\n\n\/\/ This JSClass is used to create the reference tracker JSObjects.\nJSClass JSNativeWrapper::js_reference_tracker_class_ = {\n \"JSReferenceTracker\",\n \/\/ Use the private slot to store the wrapper.\n JSCLASS_HAS_PRIVATE,\n JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,\n JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, FinalizeTracker,\n JSCLASS_NO_OPTIONAL_MEMBERS\n};\n\nstatic const char *kTrackerReferenceName = \"[[[TrackerReference]]]\";\n\nJSNativeWrapper::JSNativeWrapper(JSContext *js_context, JSObject *js_object)\n : js_context_(js_context),\n js_object_(js_object),\n name_(PrintJSValue(js_context, OBJECT_TO_JSVAL(js_object))),\n call_self_slot_(NULL) {\n \/\/ Wrap this object again into a JS object, and add this object as a property\n \/\/ of the original object, to make it possible to auto detach this object\n \/\/ when the original object is finalized.\n JSObject *js_reference_tracker = JS_NewObject(js_context,\n &js_reference_tracker_class_,\n NULL, NULL);\n JS_DefineProperty(js_context, js_object, kTrackerReferenceName,\n OBJECT_TO_JSVAL(js_reference_tracker),\n NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT);\n JS_SetPrivate(js_context, js_reference_tracker, this);\n \/\/ Count the current JavaScript reference.\n Ref();\n ASSERT(GetRefCount() == 1);\n\n if (JS_TypeOfValue(js_context, OBJECT_TO_JSVAL(js_object)) ==\n JSTYPE_FUNCTION) {\n \/\/ This object can be called as a function.\n call_self_slot_ = new JSFunctionSlot(NULL, js_context, NULL, js_object);\n }\n}\n\nJSNativeWrapper::~JSNativeWrapper() {\n delete call_self_slot_;\n if (CheckContext())\n JSScriptContext::FinalizeJSNativeWrapper(js_context_, this);\n}\n\nbool JSNativeWrapper::CheckContext() const {\n if (!js_context_) {\n LOG(\"The context of a native wrapped JS object has already been \"\n \"destroyed.\");\n return false;\n }\n return true;\n}\n\nvoid JSNativeWrapper::Ref() const {\n ScriptableHelperDefault::Ref();\n if (CheckContext() && GetRefCount() == 2) {\n \/\/ There must be a new native reference, let JavaScript know it by adding\n \/\/ the object to root.\n JS_AddNamedRootRT(JS_GetRuntime(js_context_),\n const_cast(&js_object_), name_.c_str());\n }\n}\n\nvoid JSNativeWrapper::Unref(bool transient) const {\n if (CheckContext() && GetRefCount() == 2) {\n \/\/ The last native reference is about to be released, let JavaScript know\n \/\/ it by removing the root reference.\n JS_RemoveRootRT(JS_GetRuntime(js_context_),\n const_cast(&js_object_));\n }\n ScriptableHelperDefault::Unref(transient);\n}\n\nScriptableInterface::PropertyType JSNativeWrapper::GetPropertyInfo(\n const char *name, Variant *prototype) {\n if (!*name && call_self_slot_) {\n *prototype = Variant(&call_self_slot_);\n return ScriptableInterface::PROPERTY_METHOD;\n }\n return ScriptableInterface::PROPERTY_DYNAMIC;\n}\n\nbool JSNativeWrapper::EnumerateProperties(\n EnumeratePropertiesCallback *callback) {\n ASSERT(callback);\n if (!CheckContext()) {\n delete callback;\n return false;\n }\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n bool result = true;\n JSIdArray *id_array = JS_Enumerate(js_context_, js_object_);\n if (id_array) {\n for (int i = 0; i < id_array->length; i++) {\n jsid id = id_array->vector[i];\n jsval key = JSVAL_VOID;\n JS_IdToValue(js_context_, id, &key);\n if (JSVAL_IS_STRING(key)) {\n char *name = JS_GetStringBytes(JSVAL_TO_STRING(key));\n if (name &&\n !(*callback)(name, ScriptableInterface::PROPERTY_DYNAMIC,\n GetProperty(name).v())) {\n result = false;\n break;\n }\n }\n \/\/ Otherwise, ignore the property.\n }\n }\n JS_DestroyIdArray(js_context_, id_array);\n delete callback;\n return result;\n}\n\nbool JSNativeWrapper::EnumerateElements(EnumerateElementsCallback *callback) {\n ASSERT(callback);\n if (!CheckContext()) {\n delete callback;\n return false;\n }\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n bool result = true;\n JSIdArray *id_array = JS_Enumerate(js_context_, js_object_);\n if (id_array) {\n for (int i = 0; i < id_array->length; i++) {\n jsid id = id_array->vector[i];\n jsval key = JSVAL_VOID;\n JS_IdToValue(js_context_, id, &key);\n if (JSVAL_IS_INT(key)) {\n int index = JSVAL_TO_INT(key);\n if (!(*callback)(index, GetPropertyByIndex(index).v())) {\n result = false;\n break;\n }\n }\n \/\/ Otherwise, ignore the property.\n }\n }\n JS_DestroyIdArray(js_context_, id_array);\n delete callback;\n return result;\n}\n\nResultVariant JSNativeWrapper::GetProperty(const char *name) {\n Variant result;\n if (!CheckContext())\n return ResultVariant(result);\n\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n if (!*name && call_self_slot_) {\n \/\/ Get the default method used to call this object as a function.\n return ResultVariant(Variant(call_self_slot_));\n }\n\n UTF16String utf16;\n ConvertStringUTF8ToUTF16(name, strlen(name), &utf16);\n jsval rval;\n if (JS_GetUCProperty(js_context_, js_object_, utf16.c_str(), utf16.size(),\n &rval) &&\n !ConvertJSToNativeVariant(js_context_, rval, &result)) {\n RaiseException(js_context_,\n \"Failed to convert JS property %s value(%s) to native.\",\n name, PrintJSValue(js_context_, rval).c_str());\n }\n return ResultVariant(result);\n}\n\nbool JSNativeWrapper::SetProperty(const char *name, const Variant &value) {\n if (!CheckContext())\n return false;\n\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n jsval js_val;\n if (!ConvertNativeToJS(js_context_, value, &js_val)) {\n RaiseException(js_context_,\n \"Failed to convert native property %s value(%s) to jsval.\",\n name, value.Print().c_str());\n return false;\n }\n UTF16String utf16;\n ConvertStringUTF8ToUTF16(name, strlen(name), &utf16);\n return JS_SetUCProperty(js_context_, js_object_, utf16.c_str(), utf16.size(),\n &js_val);\n}\n\nResultVariant JSNativeWrapper::GetPropertyByIndex(int index) {\n Variant result;\n if (!CheckContext())\n return ResultVariant(result);\n\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n jsval rval;\n if (JS_GetElement(js_context_, js_object_, index, &rval) &&\n !ConvertJSToNativeVariant(js_context_, rval, &result)) {\n RaiseException(js_context_,\n \"Failed to convert JS property %d value(%s) to native.\",\n index, PrintJSValue(js_context_, rval).c_str());\n }\n return ResultVariant(result);\n}\n\nbool JSNativeWrapper::SetPropertyByIndex(int index, const Variant &value) {\n if (!CheckContext())\n return false;\n\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n jsval js_val;\n if (!ConvertNativeToJS(js_context_, value, &js_val)) {\n JS_ReportError(js_context_,\n \"Failed to convert native property %d value(%s) to jsval.\",\n index, value.Print().c_str());\n return false;\n }\n return JS_SetElement(js_context_, js_object_, index, &js_val);\n}\n\nvoid JSNativeWrapper::FinalizeTracker(JSContext *cx, JSObject *obj) {\n if (obj) {\n JSClass *cls = JS_GET_CLASS(cx, obj);\n if (cls && cls->finalize == js_reference_tracker_class_.finalize) {\n JSNativeWrapper *wrapper =\n reinterpret_cast(JS_GetPrivate(cx, obj));\n if (wrapper)\n wrapper->Unref();\n }\n }\n}\n\nvoid JSNativeWrapper::OnContextDestroy() {\n JS_RemoveRootRT(JS_GetRuntime(js_context_),\n const_cast(&js_object_));\n delete call_self_slot_;\n call_self_slot_ = NULL;\n js_context_ = NULL;\n}\n\n} \/\/ namespace smjs\n} \/\/ namespace ggadget\n r1237@wangxianzhu: wangxianzhu | 2009-03-13 12:40:52 +0800 Fixed a bug in JSNativeWrapper which causes loss of slot prototype.\/*\n Copyright 2008 Google Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"js_native_wrapper.h\"\n#include \"converter.h\"\n#include \"js_function_slot.h\"\n#include \"js_script_context.h\"\n\nnamespace ggadget {\nnamespace smjs {\n\n\/\/ This JSClass is used to create the reference tracker JSObjects.\nJSClass JSNativeWrapper::js_reference_tracker_class_ = {\n \"JSReferenceTracker\",\n \/\/ Use the private slot to store the wrapper.\n JSCLASS_HAS_PRIVATE,\n JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,\n JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, FinalizeTracker,\n JSCLASS_NO_OPTIONAL_MEMBERS\n};\n\nstatic const char *kTrackerReferenceName = \"[[[TrackerReference]]]\";\n\nJSNativeWrapper::JSNativeWrapper(JSContext *js_context, JSObject *js_object)\n : js_context_(js_context),\n js_object_(js_object),\n name_(PrintJSValue(js_context, OBJECT_TO_JSVAL(js_object))),\n call_self_slot_(NULL) {\n \/\/ Wrap this object again into a JS object, and add this object as a property\n \/\/ of the original object, to make it possible to auto detach this object\n \/\/ when the original object is finalized.\n JSObject *js_reference_tracker = JS_NewObject(js_context,\n &js_reference_tracker_class_,\n NULL, NULL);\n JS_DefineProperty(js_context, js_object, kTrackerReferenceName,\n OBJECT_TO_JSVAL(js_reference_tracker),\n NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT);\n JS_SetPrivate(js_context, js_reference_tracker, this);\n \/\/ Count the current JavaScript reference.\n Ref();\n ASSERT(GetRefCount() == 1);\n\n if (JS_TypeOfValue(js_context, OBJECT_TO_JSVAL(js_object)) ==\n JSTYPE_FUNCTION) {\n \/\/ This object can be called as a function.\n call_self_slot_ = new JSFunctionSlot(NULL, js_context, NULL, js_object);\n }\n}\n\nJSNativeWrapper::~JSNativeWrapper() {\n delete call_self_slot_;\n if (CheckContext())\n JSScriptContext::FinalizeJSNativeWrapper(js_context_, this);\n}\n\nbool JSNativeWrapper::CheckContext() const {\n if (!js_context_) {\n LOG(\"The context of a native wrapped JS object has already been \"\n \"destroyed.\");\n return false;\n }\n return true;\n}\n\nvoid JSNativeWrapper::Ref() const {\n ScriptableHelperDefault::Ref();\n if (CheckContext() && GetRefCount() == 2) {\n \/\/ There must be a new native reference, let JavaScript know it by adding\n \/\/ the object to root.\n JS_AddNamedRootRT(JS_GetRuntime(js_context_),\n const_cast(&js_object_), name_.c_str());\n }\n}\n\nvoid JSNativeWrapper::Unref(bool transient) const {\n if (CheckContext() && GetRefCount() == 2) {\n \/\/ The last native reference is about to be released, let JavaScript know\n \/\/ it by removing the root reference.\n JS_RemoveRootRT(JS_GetRuntime(js_context_),\n const_cast(&js_object_));\n }\n ScriptableHelperDefault::Unref(transient);\n}\n\nScriptableInterface::PropertyType JSNativeWrapper::GetPropertyInfo(\n const char *name, Variant *prototype) {\n if (!*name && call_self_slot_) {\n *prototype = Variant(call_self_slot_);\n return ScriptableInterface::PROPERTY_METHOD;\n }\n return ScriptableInterface::PROPERTY_DYNAMIC;\n}\n\nbool JSNativeWrapper::EnumerateProperties(\n EnumeratePropertiesCallback *callback) {\n ASSERT(callback);\n if (!CheckContext()) {\n delete callback;\n return false;\n }\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n bool result = true;\n JSIdArray *id_array = JS_Enumerate(js_context_, js_object_);\n if (id_array) {\n for (int i = 0; i < id_array->length; i++) {\n jsid id = id_array->vector[i];\n jsval key = JSVAL_VOID;\n JS_IdToValue(js_context_, id, &key);\n if (JSVAL_IS_STRING(key)) {\n char *name = JS_GetStringBytes(JSVAL_TO_STRING(key));\n if (name &&\n !(*callback)(name, ScriptableInterface::PROPERTY_DYNAMIC,\n GetProperty(name).v())) {\n result = false;\n break;\n }\n }\n \/\/ Otherwise, ignore the property.\n }\n }\n JS_DestroyIdArray(js_context_, id_array);\n delete callback;\n return result;\n}\n\nbool JSNativeWrapper::EnumerateElements(EnumerateElementsCallback *callback) {\n ASSERT(callback);\n if (!CheckContext()) {\n delete callback;\n return false;\n }\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n bool result = true;\n JSIdArray *id_array = JS_Enumerate(js_context_, js_object_);\n if (id_array) {\n for (int i = 0; i < id_array->length; i++) {\n jsid id = id_array->vector[i];\n jsval key = JSVAL_VOID;\n JS_IdToValue(js_context_, id, &key);\n if (JSVAL_IS_INT(key)) {\n int index = JSVAL_TO_INT(key);\n if (!(*callback)(index, GetPropertyByIndex(index).v())) {\n result = false;\n break;\n }\n }\n \/\/ Otherwise, ignore the property.\n }\n }\n JS_DestroyIdArray(js_context_, id_array);\n delete callback;\n return result;\n}\n\nResultVariant JSNativeWrapper::GetProperty(const char *name) {\n Variant result;\n if (!CheckContext())\n return ResultVariant(result);\n\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n if (!*name && call_self_slot_) {\n \/\/ Get the default method used to call this object as a function.\n return ResultVariant(Variant(call_self_slot_));\n }\n\n UTF16String utf16;\n ConvertStringUTF8ToUTF16(name, strlen(name), &utf16);\n jsval rval;\n if (JS_GetUCProperty(js_context_, js_object_, utf16.c_str(), utf16.size(),\n &rval) &&\n !ConvertJSToNativeVariant(js_context_, rval, &result)) {\n RaiseException(js_context_,\n \"Failed to convert JS property %s value(%s) to native.\",\n name, PrintJSValue(js_context_, rval).c_str());\n }\n return ResultVariant(result);\n}\n\nbool JSNativeWrapper::SetProperty(const char *name, const Variant &value) {\n if (!CheckContext())\n return false;\n\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n jsval js_val;\n if (!ConvertNativeToJS(js_context_, value, &js_val)) {\n RaiseException(js_context_,\n \"Failed to convert native property %s value(%s) to jsval.\",\n name, value.Print().c_str());\n return false;\n }\n UTF16String utf16;\n ConvertStringUTF8ToUTF16(name, strlen(name), &utf16);\n return JS_SetUCProperty(js_context_, js_object_, utf16.c_str(), utf16.size(),\n &js_val);\n}\n\nResultVariant JSNativeWrapper::GetPropertyByIndex(int index) {\n Variant result;\n if (!CheckContext())\n return ResultVariant(result);\n\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n jsval rval;\n if (JS_GetElement(js_context_, js_object_, index, &rval) &&\n !ConvertJSToNativeVariant(js_context_, rval, &result)) {\n RaiseException(js_context_,\n \"Failed to convert JS property %d value(%s) to native.\",\n index, PrintJSValue(js_context_, rval).c_str());\n }\n return ResultVariant(result);\n}\n\nbool JSNativeWrapper::SetPropertyByIndex(int index, const Variant &value) {\n if (!CheckContext())\n return false;\n\n ScopedLogContext log_context(GetJSScriptContext(js_context_));\n jsval js_val;\n if (!ConvertNativeToJS(js_context_, value, &js_val)) {\n JS_ReportError(js_context_,\n \"Failed to convert native property %d value(%s) to jsval.\",\n index, value.Print().c_str());\n return false;\n }\n return JS_SetElement(js_context_, js_object_, index, &js_val);\n}\n\nvoid JSNativeWrapper::FinalizeTracker(JSContext *cx, JSObject *obj) {\n if (obj) {\n JSClass *cls = JS_GET_CLASS(cx, obj);\n if (cls && cls->finalize == js_reference_tracker_class_.finalize) {\n JSNativeWrapper *wrapper =\n reinterpret_cast(JS_GetPrivate(cx, obj));\n if (wrapper)\n wrapper->Unref();\n }\n }\n}\n\nvoid JSNativeWrapper::OnContextDestroy() {\n JS_RemoveRootRT(JS_GetRuntime(js_context_),\n const_cast(&js_object_));\n delete call_self_slot_;\n call_self_slot_ = NULL;\n js_context_ = NULL;\n}\n\n} \/\/ namespace smjs\n} \/\/ namespace ggadget\n<|endoftext|>"} {"text":"#include \"SPlaying.h\"\n\n#include \n#include \n\n#include \"..\/World\/Block\/Block_Database.h\"\n#include \"..\/Renderer\/RMaster.h\"\n#include \"..\/Camera.h\"\n#include \"..\/Application.h\"\n#include \"..\/Display.h\"\n\nvoid Frame_Time_Checker::update()\n{\n m_frameCount++;\n\n if (m_updateTimer.getElapsedTime().asSeconds() >= 0.3)\n {\n m_fps = m_frameCount \/ m_timer.getElapsedTime().asMilliseconds();\n if (m_fps > 0)\n {\n m_frameTime = 1.0f \/ m_fps;\n }\n m_fps *= 1000;\n m_frameCount = 0;\n m_updateTimer.restart();\n m_timer.restart();\n }\n}\n\nconst float& Frame_Time_Checker::getFrameTime()\n{\n return m_frameTime;\n}\n\nconst float& Frame_Time_Checker::getFPS()\n{\n return m_fps;\n}\n\n\n\nnamespace State\n{\n namespace\n {\n uint32_t worldSize = 64;\n }\n\n Playing::Playing(Application& application)\n : Game_State (application)\n , m_world (application.getCamera(), worldSize)\n , m_player (application.getCamera())\n , m_quady (Block::Database::get().textures)\n , m_pauseMenu (GUI::Layout::Center)\n {\n application.getCamera().hookEntity(m_player);\n initHUD();\n initPause();\n\n m_quady.position =\n {\n (worldSize * CHUNK_SIZE) \/ 2,\n CHUNK_SIZE * 3,\n (worldSize * CHUNK_SIZE) \/ 2\n };\n\n m_player.position =\n {\n (worldSize * CHUNK_SIZE) \/ 2,\n CHUNK_SIZE * 3,\n (worldSize * CHUNK_SIZE) \/ 2\n };\n }\n\n void Playing::input(sf::Event& e)\n {\n\n if (m_isPaused)\n {\n m_pauseMenu.input(e);\n Display::get().setMouseCursorVisible(true);\n }\n else\n {\n Display::get().setMouseCursorVisible(false);\n }\n\n switch(e.type)\n {\n case sf::Event::KeyPressed:\n if (e.key.code == sf::Keyboard::Escape)\n {\n m_isPaused = !m_isPaused;\n }\n default:\n break;\n }\n }\n\n void Playing::input(Camera& camera)\n {\n if (!m_isPaused)\n {\n m_player.input();\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::R))\n {\n m_player.position =\n {\n (worldSize * CHUNK_SIZE) \/ 2,\n CHUNK_SIZE * 3,\n (worldSize * CHUNK_SIZE) \/ 2\n };\n }\n }\n }\n\n\n void Playing::update(Camera& camera, float dt)\n {\n static sf::Clock c;\n m_quady.position.x += sin(c.getElapsedTime().asSeconds()) * dt * 0.8;\n m_quady.position.z += cos(c.getElapsedTime().asSeconds()) * dt * 0.8;\n\n if (m_isPaused)\n {\n m_pauseMenu.update();\n }\n m_player.update(dt);\n m_world.checkPlayerBounds(m_player);\n m_frameTimeChecker.update();\n }\n\n void Playing::draw(Renderer::Master& renderer)\n {\n if (m_isPaused)\n {\n m_pauseMenu.draw(renderer);\n }\n m_world.drawWorld(renderer, m_application->getCamera());\n renderer.draw(m_quady);\n\n m_hud.draw(renderer);\n }\n\n void Playing::initHUD()\n {\n float yPos = 0;\n\n auto getYPosition = [&yPos]()\n {\n float val = yPos;\n yPos += 27;\n return val;\n };\n\n m_hud.debug.addDebugSector(\"Frame Time: %fms\", {0, getYPosition()}, &m_frameTimeChecker.getFrameTime());\n m_hud.debug.addDebugSector(\"FPS: %.0f\", {0, getYPosition()}, &m_frameTimeChecker.getFPS());\n m_hud.debug.addDebugSector(\"Faces drawn: %.0f\", {0, getYPosition()}, &m_world.m_facesDrawn);\n m_hud.debug.addDebugSector(\"Player Position: X: %.1f\", {0, getYPosition()}, &m_player.position.x);\n m_hud.debug.addDebugSector(\"Player Position: Y: %.1f\", {0, getYPosition()}, &m_player.position.y);\n m_hud.debug.addDebugSector(\"Player Position: Z: %.1f\", {0, getYPosition()}, &m_player.position.z);\n }\n\n void Playing::initPause()\n {\n m_pauseMenu.addComponent(std::make_unique(\"Logo\", sf::Vector2f{800, 100}));\n m_pauseMenu.addPadding(200);\n m_pauseMenu.addComponent(std::make_unique(\"Resume\", [&]()\n {\n m_isPaused = false;\n }));\n\n m_pauseMenu.addComponent(std::make_unique(\"Exit\", [&]()\n {\n m_application->popState();\n }));\n }\n\n}\n\n\n\n\nDecrease world size.#include \"SPlaying.h\"\n\n#include \n#include \n\n#include \"..\/World\/Block\/Block_Database.h\"\n#include \"..\/Renderer\/RMaster.h\"\n#include \"..\/Camera.h\"\n#include \"..\/Application.h\"\n#include \"..\/Display.h\"\n\nvoid Frame_Time_Checker::update()\n{\n m_frameCount++;\n\n if (m_updateTimer.getElapsedTime().asSeconds() >= 0.3)\n {\n m_fps = m_frameCount \/ m_timer.getElapsedTime().asMilliseconds();\n if (m_fps > 0)\n {\n m_frameTime = 1.0f \/ m_fps;\n }\n m_fps *= 1000;\n m_frameCount = 0;\n m_updateTimer.restart();\n m_timer.restart();\n }\n}\n\nconst float& Frame_Time_Checker::getFrameTime()\n{\n return m_frameTime;\n}\n\nconst float& Frame_Time_Checker::getFPS()\n{\n return m_fps;\n}\n\n\n\nnamespace State\n{\n namespace\n {\n uint32_t worldSize = 20;\n }\n\n Playing::Playing(Application& application)\n : Game_State (application)\n , m_world (application.getCamera(), worldSize)\n , m_player (application.getCamera())\n , m_quady (Block::Database::get().textures)\n , m_pauseMenu (GUI::Layout::Center)\n {\n application.getCamera().hookEntity(m_player);\n initHUD();\n initPause();\n\n m_quady.position =\n {\n (worldSize * CHUNK_SIZE) \/ 2,\n CHUNK_SIZE * 3,\n (worldSize * CHUNK_SIZE) \/ 2\n };\n\n m_player.position =\n {\n (worldSize * CHUNK_SIZE) \/ 2,\n CHUNK_SIZE * 3,\n (worldSize * CHUNK_SIZE) \/ 2\n };\n }\n\n void Playing::input(sf::Event& e)\n {\n\n if (m_isPaused)\n {\n m_pauseMenu.input(e);\n Display::get().setMouseCursorVisible(true);\n }\n else\n {\n Display::get().setMouseCursorVisible(false);\n }\n\n switch(e.type)\n {\n case sf::Event::KeyPressed:\n if (e.key.code == sf::Keyboard::Escape)\n {\n m_isPaused = !m_isPaused;\n }\n default:\n break;\n }\n }\n\n void Playing::input(Camera& camera)\n {\n if (!m_isPaused)\n {\n m_player.input();\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::R))\n {\n m_player.position =\n {\n (worldSize * CHUNK_SIZE) \/ 2,\n CHUNK_SIZE * 3,\n (worldSize * CHUNK_SIZE) \/ 2\n };\n }\n }\n }\n\n\n void Playing::update(Camera& camera, float dt)\n {\n static sf::Clock c;\n m_quady.position.x += sin(c.getElapsedTime().asSeconds()) * dt * 0.8;\n m_quady.position.z += cos(c.getElapsedTime().asSeconds()) * dt * 0.8;\n\n if (m_isPaused)\n {\n m_pauseMenu.update();\n }\n m_player.update(dt);\n m_world.checkPlayerBounds(m_player);\n m_frameTimeChecker.update();\n }\n\n void Playing::draw(Renderer::Master& renderer)\n {\n if (m_isPaused)\n {\n m_pauseMenu.draw(renderer);\n }\n m_world.drawWorld(renderer, m_application->getCamera());\n renderer.draw(m_quady);\n\n m_hud.draw(renderer);\n }\n\n void Playing::initHUD()\n {\n float yPos = 0;\n\n auto getYPosition = [&yPos]()\n {\n float val = yPos;\n yPos += 27;\n return val;\n };\n\n m_hud.debug.addDebugSector(\"Frame Time: %fms\", {0, getYPosition()}, &m_frameTimeChecker.getFrameTime());\n m_hud.debug.addDebugSector(\"FPS: %.0f\", {0, getYPosition()}, &m_frameTimeChecker.getFPS());\n m_hud.debug.addDebugSector(\"Faces drawn: %.0f\", {0, getYPosition()}, &m_world.m_facesDrawn);\n m_hud.debug.addDebugSector(\"Player Position: X: %.1f\", {0, getYPosition()}, &m_player.position.x);\n m_hud.debug.addDebugSector(\"Player Position: Y: %.1f\", {0, getYPosition()}, &m_player.position.y);\n m_hud.debug.addDebugSector(\"Player Position: Z: %.1f\", {0, getYPosition()}, &m_player.position.z);\n }\n\n void Playing::initPause()\n {\n m_pauseMenu.addComponent(std::make_unique(\"Logo\", sf::Vector2f{800, 100}));\n m_pauseMenu.addPadding(200);\n m_pauseMenu.addComponent(std::make_unique(\"Resume\", [&]()\n {\n m_isPaused = false;\n }));\n\n m_pauseMenu.addComponent(std::make_unique(\"Exit\", [&]()\n {\n m_application->popState();\n }));\n }\n\n}\n\n\n\n\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef DEBUG_STOP_WATCH_H\n#define DEBUG_STOP_WATCH_H\n\n#include \n#include \n\n#include \"StopWatch.hpp\"\n\nnamespace eddic {\n\n\/*!\n * \\class DebugStopWatch\n * \\brief Simple stopwatch to keep track of elapsed time between instantiation and destruction.\n * \n * If debug template argument is set to false, this class transforms to a no-op. \n * \n * \\see StopWatch\n *\/\ntemplate\nclass DebugStopWatch {\n private:\n StopWatch timer;\n std::string name;\n\n public:\n DebugStopWatch(const std::string& n) : name(n) {}\n \n ~DebugStopWatch(){\n std::cout << name << \" took \" << timer.elapsed() << \"ms\" << std::endl;\n }\n};\n\ntemplate<>\nstruct DebugStopWatch {\n DebugStopWatch(const std::string&) {}\n};\n\n} \/\/end of eddic\n\n#endif\nRemove unused class<|endoftext|>"} {"text":"#include \n\n#include \"demo\/demo.h\"\n\nint main()\n{\n \/\/ run demo\n demo::Demo demo;\n demo.startup();\n demo.run();\n demo.shutdown();\n\n return 0;\n}Clean up main.#include \"demo\/demo.h\"\n\nint main()\n{\n \/\/ run demo\n demo::Demo demo;\n demo.startup();\n demo.run();\n demo.shutdown();\n\n return 0;\n}<|endoftext|>"} {"text":"\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\n * adiosMpiHandshake.cpp\n *\n * Created on: Mar 1, 2020\n * Author: Jason Wang\n *\/\n\n#include \"adiosMpiHandshake.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace adios2\n{\nnamespace helper\n{\n\nconst std::vector> Handshake(const std::string &filename,\n const char mode,\n const int timeoutSeconds,\n MPI_Comm localComm)\n{\n std::vector> ret(3);\n\n int localRank;\n int localSize;\n int worldRank;\n int worldSize;\n\n MPI_Comm_rank(localComm, &localRank);\n MPI_Comm_size(localComm, &localSize);\n\n MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);\n MPI_Comm_size(MPI_COMM_WORLD, &worldSize);\n\n std::vector allLocalRanks(localSize);\n\n MPI_Gather(&worldRank, 1, MPI_INT, allLocalRanks.data(), 1, MPI_INT, 0,\n localComm);\n\n if (localRank == 0)\n {\n std::ofstream fs;\n fs.open(filename + \".\" + mode);\n for (auto rank : allLocalRanks)\n {\n fs << rank << std::endl;\n }\n fs.close();\n\n if (mode == 'r')\n {\n\n for (auto i : allLocalRanks)\n {\n ret[0].push_back(i);\n ret[2].push_back(i);\n }\n\n std::ofstream fsc;\n fsc.open(filename + \".r.c\");\n fsc << \"completed\";\n fsc.close();\n\n while (true)\n {\n std::ifstream fs;\n try\n {\n fs.open(filename + \".w.c\");\n std::string line;\n std::getline(fs, line);\n if (line != \"completed\")\n {\n continue;\n }\n fs.close();\n remove((filename + \".w.c\\0\").c_str());\n break;\n }\n catch (...)\n {\n continue;\n }\n }\n\n std::ifstream fs;\n fs.open(filename + \".w\");\n for (std::string line; std::getline(fs, line);)\n {\n ret[0].push_back(std::stoi(line));\n ret[1].push_back(std::stoi(line));\n }\n fs.close();\n remove((filename + \".w\\0\").c_str());\n }\n else if (mode == 'w')\n {\n for (auto i : allLocalRanks)\n {\n ret[0].push_back(i);\n ret[1].push_back(i);\n }\n\n std::ofstream fsc;\n fsc.open(filename + \".w.c\");\n fsc << \"completed\";\n fsc.close();\n\n while (true)\n {\n std::ifstream fs;\n try\n {\n fs.open(filename + \".r.c\");\n std::string line;\n std::getline(fs, line);\n if (line != \"completed\")\n {\n continue;\n }\n fs.close();\n remove((filename + \".r.c\\0\").c_str());\n break;\n }\n catch (...)\n {\n continue;\n }\n }\n\n std::ifstream fs;\n fs.open(filename + \".r\");\n for (std::string line; std::getline(fs, line);)\n {\n ret[0].push_back(std::stoi(line));\n ret[2].push_back(std::stoi(line));\n }\n fs.close();\n remove((filename + \".r\\0\").c_str());\n }\n }\n\n int dims[3];\n\n if (localRank == 0)\n {\n for (int i = 0; i < 3; ++i)\n {\n dims[i] = ret[i].size();\n std::sort(ret[i].begin(), ret[i].end());\n }\n }\n\n MPI_Bcast(dims, 3, MPI_INT, 0, localComm);\n\n if (localRank != 0)\n {\n for (int i = 0; i < 3; ++i)\n {\n ret[i].resize(dims[i]);\n }\n }\n\n for (int i = 0; i < 3; ++i)\n {\n MPI_Bcast(ret[i].data(), ret[i].size(), MPI_INT, 0, localComm);\n }\n\n return ret;\n}\n\n} \/\/ end namespace helper\n} \/\/ end namespace adios2\nadded algorithm.h\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\n * adiosMpiHandshake.cpp\n *\n * Created on: Mar 1, 2020\n * Author: Jason Wang\n *\/\n\n#include \"adiosMpiHandshake.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace adios2\n{\nnamespace helper\n{\n\nconst std::vector> Handshake(const std::string &filename,\n const char mode,\n const int timeoutSeconds,\n MPI_Comm localComm)\n{\n std::vector> ret(3);\n\n int localRank;\n int localSize;\n int worldRank;\n int worldSize;\n\n MPI_Comm_rank(localComm, &localRank);\n MPI_Comm_size(localComm, &localSize);\n\n MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);\n MPI_Comm_size(MPI_COMM_WORLD, &worldSize);\n\n std::vector allLocalRanks(localSize);\n\n MPI_Gather(&worldRank, 1, MPI_INT, allLocalRanks.data(), 1, MPI_INT, 0,\n localComm);\n\n if (localRank == 0)\n {\n std::ofstream fs;\n fs.open(filename + \".\" + mode);\n for (auto rank : allLocalRanks)\n {\n fs << rank << std::endl;\n }\n fs.close();\n\n if (mode == 'r')\n {\n\n for (auto i : allLocalRanks)\n {\n ret[0].push_back(i);\n ret[2].push_back(i);\n }\n\n std::ofstream fsc;\n fsc.open(filename + \".r.c\");\n fsc << \"completed\";\n fsc.close();\n\n while (true)\n {\n std::ifstream fs;\n try\n {\n fs.open(filename + \".w.c\");\n std::string line;\n std::getline(fs, line);\n if (line != \"completed\")\n {\n continue;\n }\n fs.close();\n remove((filename + \".w.c\\0\").c_str());\n break;\n }\n catch (...)\n {\n continue;\n }\n }\n\n std::ifstream fs;\n fs.open(filename + \".w\");\n for (std::string line; std::getline(fs, line);)\n {\n ret[0].push_back(std::stoi(line));\n ret[1].push_back(std::stoi(line));\n }\n fs.close();\n remove((filename + \".w\\0\").c_str());\n }\n else if (mode == 'w')\n {\n for (auto i : allLocalRanks)\n {\n ret[0].push_back(i);\n ret[1].push_back(i);\n }\n\n std::ofstream fsc;\n fsc.open(filename + \".w.c\");\n fsc << \"completed\";\n fsc.close();\n\n while (true)\n {\n std::ifstream fs;\n try\n {\n fs.open(filename + \".r.c\");\n std::string line;\n std::getline(fs, line);\n if (line != \"completed\")\n {\n continue;\n }\n fs.close();\n remove((filename + \".r.c\\0\").c_str());\n break;\n }\n catch (...)\n {\n continue;\n }\n }\n\n std::ifstream fs;\n fs.open(filename + \".r\");\n for (std::string line; std::getline(fs, line);)\n {\n ret[0].push_back(std::stoi(line));\n ret[2].push_back(std::stoi(line));\n }\n fs.close();\n remove((filename + \".r\\0\").c_str());\n }\n }\n\n int dims[3];\n\n if (localRank == 0)\n {\n for (int i = 0; i < 3; ++i)\n {\n dims[i] = ret[i].size();\n std::sort(ret[i].begin(), ret[i].end());\n }\n }\n\n MPI_Bcast(dims, 3, MPI_INT, 0, localComm);\n\n if (localRank != 0)\n {\n for (int i = 0; i < 3; ++i)\n {\n ret[i].resize(dims[i]);\n }\n }\n\n for (int i = 0; i < 3; ++i)\n {\n MPI_Bcast(ret[i].data(), ret[i].size(), MPI_INT, 0, localComm);\n }\n\n return ret;\n}\n\n} \/\/ end namespace helper\n} \/\/ end namespace adios2\n<|endoftext|>"} {"text":"\/\/ Each task is composed of a computing unit, which performs the desired\n\/\/ computation, and the arguments provided by the user. This file defines how\n\/\/ the computing units are created.\n\/\/\n\/\/ Each computing unit is identified by an id that should be unique, so that\n\/\/ the class used to compute can be identified. Currently the id is given by the\n\/\/ name provided by to the constructor. The class BaseComputingUnit is used only\n\/\/ to provide abstract pointers to units and thus should NEVER be used directly.\n\/\/\n\/\/ To create a new computing unit, inherit from ComputingUnit like this:\n\/\/ class MyUnit: public ComputingUnit\n\/\/ and provide the following inside the class:\n\/\/ 1) the constructor should call ComputingUnit with the desired unit's\n\/\/ name as argument;\n\/\/ 1) a method operator() that performs the computation desired.\n\/\/\n\/\/ Caveats:\n\/\/ 1) Only the return of operator() is considered as the result, so any changes\n\/\/ to the argument are ignored;\n\/\/ 2) All arguments and the return of operator() must be serializable through\n\/\/ boost;\n\/\/ 3) operator() must be declared as const, to ensure no modifications are\n\/\/ performed.\n\/\/\n\/\/ Besides these requirements, the user has control over the following options:\n\/\/ 1) whether the object must run on the master node, chosen through the method\n\/\/ \"run_locally()\". This should be used in case there is some restriction, like\n\/\/ file requirements or the operator() method is so fast that the communication\n\/\/ overhead isn't worth. The node is allowed to run anywhere by default;\n\/\/ 2) whether the result should be saved to disk, through the method\n\/\/ \"should_save()\". For very simple units, it may not be necessary or even\n\/\/ desidered to save the result of the computation. The default is to save.\n\/\/\n\/\/ For an example of how to implement an unit, check the IdentityComputingUnit\n\/\/ below.\n\n#ifndef __TASK_DISTRIBUTION__COMPUTING_UNIT_HPP__\n#define __TASK_DISTRIBUTION__COMPUTING_UNIT_HPP__\n\n#include \"object_archive.hpp\"\n\n#include \n#include \n#include \n\n#include \"compile_utils.hpp\"\n#include \"computing_unit_manager.hpp\"\n#include \"key.hpp\"\n#include \"task_entry.hpp\"\n\nnamespace TaskDistribution {\n \/\/ Abstract class to allow us to have pointers to units. Shouldn't be used\n \/\/ directly!\n class BaseComputingUnit {\n public:\n \/\/ Must the object be called on the master node? Defaults to false.\n virtual bool run_locally() const {\n return false;\n }\n\n \/\/ Should the computing results be saved? Defaults to true.\n virtual bool should_save() const {\n return true;\n }\n\n \/\/ Static method to fetch the correct kind of unit for an id. Returns NULL\n \/\/ if not found.\n static BaseComputingUnit const* get_by_id(std::string const& id);\n\n \/\/ Static method to fetch the correct kind of unit for a key. Returns NULL\n \/\/ if not found.\n static BaseComputingUnit const* get_by_key(Key const& key);\n\n \/\/ Binds a given id with a key. Multiple keys may be bound to the same id.\n \/\/ Returns true if the id was found.\n static bool bind_key(std::string const& id, Key const& key);\n\n \/\/ Gets the id associated with this kind of unit.\n std::string const& get_id() const {\n return *id_;\n }\n\n \/\/ Provides an invalid unit id.\n static std::string get_invalid_id() {\n return \"\";\n }\n\n \/\/ Callables need to be serializable. The default behavior is to transmit\n \/\/ nothing and may be overloaded.\n template\n void serialize(Archive& ar, const unsigned int version) { }\n\n \/\/ Loads the computing unit and arguments and stores the result in the\n \/\/ archive. Assumes every Key provided is valid.\n virtual void execute(ObjectArchive& archive,\n TaskEntry const& task, ComputingUnitManager& manager) const = 0;\n\n protected:\n \/\/ Expands the tuple and calls the functor\n template \n static typename function_traits::return_type\n apply(F&& f, Tuple&& args, seq) {\n return std::forward(f)(std::get(std::forward(args))...);\n }\n\n \/\/ Allows access to id_\n template friend class ComputingUnit;\n\n std::string const* id_;\n\n \/\/ Map between ids and units.\n static std::unordered_map id_map_;\n \/\/ Map between keys and units.\n static std::unordered_map key_map_;\n };\n\n \/\/ Class that should be inherited by the user's units. For an example on how\n \/\/ to do this, check the top of the file or the IdentityComputingUnit example.\n \/\/ Each kind of ComputingUnit used must be instantiated at least once and may\n \/\/ be destroyed before running the tasks.\n template \n class ComputingUnit: public BaseComputingUnit {\n public:\n \/\/ Registers the unit by placing a new copy into the units' map.\n explicit ComputingUnit(std::string const& name);\n\n virtual void execute(ObjectArchive& archive,\n TaskEntry const& task, ComputingUnitManager& manager) const;\n\n private:\n \/\/ Internal constructor to avoid deadlock during unit register.\n ComputingUnit() { }\n };\n\n \/\/ Example ComputingUnit that just returns its argument. Check that it\n \/\/ satisfies all the requirements for a valid unit.\n template \n class IdentityComputingUnit: public ComputingUnit> {\n public:\n IdentityComputingUnit():\n ComputingUnit>(\"identity\") { }\n\n virtual bool run_locally() const {\n return true;\n }\n\n virtual bool should_save() const {\n return false;\n }\n\n T operator()(T const& arg) const {\n return arg;\n }\n };\n\n template \n class ConvertComputingUnit:\n public ComputingUnit> {\n public:\n ConvertComputingUnit():\n ComputingUnit>(\"convert\") {\n static_assert(std::is_convertible::value,\n \"Invalid ConvertComputingUnit as types aren't convertible!\");\n static_assert(!std::is_same::value,\n \"Invalid ConvertComputingUnit as types are the same!\");\n }\n\n virtual bool run_locally() const {\n return true;\n }\n\n virtual bool should_save() const {\n return false;\n }\n\n To operator()(From const& arg) const {\n return arg;\n }\n };\n};\n\n#include \"computing_unit_impl.hpp\"\n\n#endif\nUpdated documentation for computing unit.\/\/ Each task is composed of a computing unit, which performs the desired\n\/\/ computation, and the arguments provided by the user. This file defines how\n\/\/ the computing units are created.\n\/\/\n\/\/ Each computing unit is identified by an id that should be unique, so that\n\/\/ the class used to compute can be identified. Currently the id is given by the\n\/\/ name provided by to the constructor. The class BaseComputingUnit is used only\n\/\/ to provide abstract pointers to units and thus should NEVER be used directly.\n\/\/\n\/\/ To create a new computing unit, inherit from ComputingUnit like this:\n\/\/ class MyUnit: public ComputingUnit\n\/\/ and provide the following inside the class:\n\/\/ 1) a constructor without arguments must be provided;\n\/\/ 2) the constructor must call ComputingUnit with the desired unit's\n\/\/ name as argument;\n\/\/ 3) a const method operator() that performs the computation desired;\n\/\/ 4) if the object has any internal parameters, they user must create the\n\/\/ method serialize.\n\/\/\n\/\/ Caveats:\n\/\/ 1) Only the return of operator() is considered as the result, so any changes\n\/\/ to the argument are ignored;\n\/\/ 2) All arguments and the return of operator() must be serializable through\n\/\/ boost;\n\/\/ 3) operator() must be declared as const, to ensure no modifications are\n\/\/ performed.\n\/\/\n\/\/ Besides these requirements, the user has control over the following options:\n\/\/ 1) whether the object must run on the master node, chosen through the method\n\/\/ \"run_locally()\". This should be used in case there is some restriction, like\n\/\/ file requirements or the operator() method is so fast that the communication\n\/\/ overhead isn't worth. The node is allowed to run anywhere by default;\n\/\/ 2) whether the result should be saved to disk, through the method\n\/\/ \"should_save()\". For very simple units, it may not be necessary or even\n\/\/ desidered to save the result of the computation. The default is to save.\n\/\/\n\/\/ For an example of how to implement an unit, check the IdentityComputingUnit\n\/\/ below.\n\n#ifndef __TASK_DISTRIBUTION__COMPUTING_UNIT_HPP__\n#define __TASK_DISTRIBUTION__COMPUTING_UNIT_HPP__\n\n#include \"object_archive.hpp\"\n\n#include \n#include \n#include \n\n#include \"compile_utils.hpp\"\n#include \"computing_unit_manager.hpp\"\n#include \"key.hpp\"\n#include \"task_entry.hpp\"\n\nnamespace TaskDistribution {\n \/\/ Abstract class to allow us to have pointers to units. Shouldn't be used\n \/\/ directly!\n class BaseComputingUnit {\n public:\n \/\/ Must the object be called on the master node? Defaults to false.\n virtual bool run_locally() const {\n return false;\n }\n\n \/\/ Should the computing results be saved? Defaults to true.\n virtual bool should_save() const {\n return true;\n }\n\n \/\/ Static method to fetch the correct kind of unit for an id. Returns NULL\n \/\/ if not found.\n static BaseComputingUnit const* get_by_id(std::string const& id);\n\n \/\/ Static method to fetch the correct kind of unit for a key. Returns NULL\n \/\/ if not found.\n static BaseComputingUnit const* get_by_key(Key const& key);\n\n \/\/ Binds a given id with a key. Multiple keys may be bound to the same id.\n \/\/ Returns true if the id was found.\n static bool bind_key(std::string const& id, Key const& key);\n\n \/\/ Gets the id associated with this kind of unit.\n std::string const& get_id() const {\n return *id_;\n }\n\n \/\/ Provides an invalid unit id.\n static std::string get_invalid_id() {\n return \"\";\n }\n\n \/\/ Callables need to be serializable. The default behavior is to transmit\n \/\/ nothing and may be overloaded.\n template\n void serialize(Archive& ar, const unsigned int version) { }\n\n \/\/ Loads the computing unit and arguments and stores the result in the\n \/\/ archive. Assumes every Key provided is valid.\n virtual void execute(ObjectArchive& archive,\n TaskEntry const& task, ComputingUnitManager& manager) const = 0;\n\n protected:\n \/\/ Expands the tuple and calls the functor\n template \n static typename function_traits::return_type\n apply(F&& f, Tuple&& args, seq) {\n return std::forward(f)(std::get(std::forward(args))...);\n }\n\n \/\/ Name of the computing unit given at construction\n std::string const* id_;\n\n \/\/ Map between ids and units.\n static std::unordered_map id_map_;\n \/\/ Map between keys and units.\n static std::unordered_map key_map_;\n };\n\n \/\/ Class that should be inherited by the user's units. For an example on how\n \/\/ to do this, check the top of the file or the IdentityComputingUnit example.\n \/\/ Each kind of ComputingUnit used must be instantiated at least once and may\n \/\/ be destroyed before running the tasks.\n template \n class ComputingUnit: public BaseComputingUnit {\n public:\n \/\/ Registers the unit by placing a new copy into the units' map.\n explicit ComputingUnit(std::string const& name);\n\n virtual void execute(ObjectArchive& archive,\n TaskEntry const& task, ComputingUnitManager& manager) const;\n\n private:\n \/\/ Internal constructor to avoid deadlock during unit register.\n ComputingUnit() { }\n };\n\n \/\/ Example ComputingUnit that just returns its argument. Check that it\n \/\/ satisfies all the requirements for a valid unit.\n template \n class IdentityComputingUnit: public ComputingUnit> {\n public:\n IdentityComputingUnit():\n ComputingUnit>(\"identity\") { }\n\n virtual bool run_locally() const {\n return true;\n }\n\n virtual bool should_save() const {\n return false;\n }\n\n T operator()(T const& arg) const {\n return arg;\n }\n };\n\n template \n class ConvertComputingUnit:\n public ComputingUnit> {\n public:\n ConvertComputingUnit():\n ComputingUnit>(\"convert\") {\n static_assert(std::is_convertible::value,\n \"Invalid ConvertComputingUnit as types aren't convertible!\");\n static_assert(!std::is_same::value,\n \"Invalid ConvertComputingUnit as types are the same!\");\n }\n\n virtual bool run_locally() const {\n return true;\n }\n\n virtual bool should_save() const {\n return false;\n }\n\n To operator()(From const& arg) const {\n return arg;\n }\n };\n};\n\n#include \"computing_unit_impl.hpp\"\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_file_util.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/string_util.h\"\n#include \"base\/path_service.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/extensions\/extension_constants.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace keys = extension_manifest_keys;\n\nTEST(ExtensionFileUtil, MoveDirSafely) {\n \/\/ Create a test directory structure with some data in it.\n ScopedTempDir temp;\n ASSERT_TRUE(temp.CreateUniqueTempDir());\n\n FilePath src_path = temp.path().AppendASCII(\"src\");\n ASSERT_TRUE(file_util::CreateDirectory(src_path));\n\n std::string data = \"foobar\";\n ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII(\"data\"),\n data.c_str(), data.length()));\n\n \/\/ Move it to a path that doesn't exist yet.\n FilePath dest_path = temp.path().AppendASCII(\"dest\").AppendASCII(\"dest\");\n ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path));\n\n \/\/ The path should get created.\n ASSERT_TRUE(file_util::DirectoryExists(dest_path));\n\n \/\/ The data should match.\n std::string data_out;\n ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII(\"data\"),\n &data_out));\n ASSERT_EQ(data, data_out);\n\n \/\/ The src path should be gone.\n ASSERT_FALSE(file_util::PathExists(src_path));\n\n \/\/ Create some new test data.\n ASSERT_TRUE(file_util::CopyDirectory(dest_path, src_path,\n true)); \/\/ recursive\n data = \"hotdog\";\n ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII(\"data\"),\n data.c_str(), data.length()));\n\n \/\/ Test again, overwriting the old path.\n ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path));\n ASSERT_TRUE(file_util::DirectoryExists(dest_path));\n\n data_out.clear();\n ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII(\"data\"),\n &data_out));\n ASSERT_EQ(data, data_out);\n ASSERT_FALSE(file_util::PathExists(src_path));\n}\n\nTEST(ExtensionFileUtil, CompareToInstalledVersion) {\n \/\/ Compare to an existing extension.\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"good\")\n .AppendASCII(\"Extensions\");\n\n const std::string kId = \"behllobkkfkfnphdnhnkndlbkcpglgmj\";\n const std::string kCurrentVersion = \"1.0.0.0\";\n\n FilePath version_dir;\n\n ASSERT_EQ(Extension::UPGRADE,\n extension_file_util::CompareToInstalledVersion(\n install_dir, kId, kCurrentVersion, \"1.0.0.1\", &version_dir));\n\n ASSERT_EQ(Extension::REINSTALL,\n extension_file_util::CompareToInstalledVersion(\n install_dir, kId, kCurrentVersion, \"1.0.0.0\", &version_dir));\n\n ASSERT_EQ(Extension::REINSTALL,\n extension_file_util::CompareToInstalledVersion(\n install_dir, kId, kCurrentVersion, \"1.0.0\", &version_dir));\n\n ASSERT_EQ(Extension::DOWNGRADE,\n extension_file_util::CompareToInstalledVersion(\n install_dir, kId, kCurrentVersion, \"0.0.1.0\", &version_dir));\n\n \/\/ Compare to an extension that is missing its manifest file.\n ScopedTempDir temp;\n ASSERT_TRUE(temp.CreateUniqueTempDir());\n FilePath src = install_dir.AppendASCII(kId).AppendASCII(kCurrentVersion);\n FilePath dest = temp.path().AppendASCII(kId).AppendASCII(kCurrentVersion);\n ASSERT_TRUE(file_util::CreateDirectory(dest.DirName()));\n ASSERT_TRUE(file_util::CopyDirectory(src, dest, true));\n ASSERT_TRUE(file_util::Delete(dest.AppendASCII(\"manifest.json\"), false));\n\n ASSERT_EQ(Extension::NEW_INSTALL,\n extension_file_util::CompareToInstalledVersion(\n temp.path(), kId, kCurrentVersion, \"1.0.0\", &version_dir));\n\n \/\/ Compare to a non-existent extension.\n const std::string kMissingVersion = \"\";\n const std::string kBadId = \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\";\n ASSERT_EQ(Extension::NEW_INSTALL,\n extension_file_util::CompareToInstalledVersion(\n temp.path(), kBadId, kMissingVersion, \"1.0.0\", &version_dir));\n}\n\nTEST(ExtensionFileUtil, LoadExtensionWithValidLocales) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"good\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"behllobkkfkfnphdnhnkndlbkcpglgmj\")\n .AppendASCII(\"1.0.0.0\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_TRUE(extension != NULL);\n EXPECT_EQ(\"The first extension that I made.\", extension->description());\n}\n\nTEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"good\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"bjafgdebaacbbbecmhlhpofkepfkgcpa\")\n .AppendASCII(\"1.0\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_FALSE(extension == NULL);\n EXPECT_TRUE(error.empty());\n}\n\nTEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) {\n ScopedTempDir temp;\n ASSERT_TRUE(temp.CreateUniqueTempDir());\n\n FilePath src_path = temp.path().AppendASCII(\"some_dir\");\n ASSERT_TRUE(file_util::CreateDirectory(src_path));\n\n std::string data = \"{ \\\"name\\\": { \\\"message\\\": \\\"foobar\\\" } }\";\n ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII(\"some_file.txt\"),\n data.c_str(), data.length()));\n std::string error;\n EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),\n &error));\n}\n\nTEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) {\n ScopedTempDir temp;\n ASSERT_TRUE(temp.CreateUniqueTempDir());\n\n FilePath src_path = temp.path().Append(Extension::kLocaleFolder);\n ASSERT_TRUE(file_util::CreateDirectory(src_path));\n\n std::string error;\n EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),\n &error));\n}\n\nTEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) {\n ScopedTempDir temp;\n ASSERT_TRUE(temp.CreateUniqueTempDir());\n\n FilePath src_path = temp.path().Append(Extension::kLocaleFolder);\n ASSERT_TRUE(file_util::CreateDirectory(src_path));\n\n src_path = temp.path().AppendASCII(\"_some_dir\");\n ASSERT_TRUE(file_util::CreateDirectory(src_path));\n\n std::string error;\n EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(),\n &error));\n}\n\nTEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"bad\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"dddddddddddddddddddddddddddddddd\")\n .AppendASCII(\"1.0\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_TRUE(extension == NULL);\n ASSERT_FALSE(error.empty());\n ASSERT_STREQ(\"Manifest file is missing or unreadable.\", error.c_str());\n}\n\nTEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"bad\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\")\n .AppendASCII(\"1.0\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_TRUE(extension == NULL);\n ASSERT_FALSE(error.empty());\n ASSERT_STREQ(\"Manifest is not valid JSON. \"\n \"Line: 2, column: 16, Syntax error.\", error.c_str());\n}\n\nTEST(ExtensionFileUtil, MissingPrivacyBlacklist) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"privacy_blacklists\")\n .AppendASCII(\"missing_blacklist\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_TRUE(extension == NULL);\n ASSERT_FALSE(error.empty());\n EXPECT_TRUE(MatchPatternASCII(error,\n \"Could not load '*privacy_blacklist.pbl' for privacy blacklist: \"\n \"file does not exist.\")) << error;\n}\n\nTEST(ExtensionFileUtil, InvalidPrivacyBlacklist) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"privacy_blacklists\")\n .AppendASCII(\"invalid_blacklist\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_TRUE(extension == NULL);\n ASSERT_FALSE(error.empty());\n EXPECT_TRUE(MatchPatternASCII(error,\n \"Could not load '*privacy_blacklist.pbl' for privacy blacklist: \"\n \"Incorrect header.\")) << error;\n}\n\n\/\/ TODO(aa): More tests as motivation allows. Maybe steal some from\n\/\/ ExtensionsService? Many of them could probably be tested here without the\n\/\/ MessageLoop shenanigans.\nadd unit test for ExtensionURLToRelativeFilePath\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_file_util.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/string_util.h\"\n#include \"base\/path_service.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/extensions\/extension_constants.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace keys = extension_manifest_keys;\n\nTEST(ExtensionFileUtil, MoveDirSafely) {\n \/\/ Create a test directory structure with some data in it.\n ScopedTempDir temp;\n ASSERT_TRUE(temp.CreateUniqueTempDir());\n\n FilePath src_path = temp.path().AppendASCII(\"src\");\n ASSERT_TRUE(file_util::CreateDirectory(src_path));\n\n std::string data = \"foobar\";\n ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII(\"data\"),\n data.c_str(), data.length()));\n\n \/\/ Move it to a path that doesn't exist yet.\n FilePath dest_path = temp.path().AppendASCII(\"dest\").AppendASCII(\"dest\");\n ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path));\n\n \/\/ The path should get created.\n ASSERT_TRUE(file_util::DirectoryExists(dest_path));\n\n \/\/ The data should match.\n std::string data_out;\n ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII(\"data\"),\n &data_out));\n ASSERT_EQ(data, data_out);\n\n \/\/ The src path should be gone.\n ASSERT_FALSE(file_util::PathExists(src_path));\n\n \/\/ Create some new test data.\n ASSERT_TRUE(file_util::CopyDirectory(dest_path, src_path,\n true)); \/\/ recursive\n data = \"hotdog\";\n ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII(\"data\"),\n data.c_str(), data.length()));\n\n \/\/ Test again, overwriting the old path.\n ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path));\n ASSERT_TRUE(file_util::DirectoryExists(dest_path));\n\n data_out.clear();\n ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII(\"data\"),\n &data_out));\n ASSERT_EQ(data, data_out);\n ASSERT_FALSE(file_util::PathExists(src_path));\n}\n\nTEST(ExtensionFileUtil, CompareToInstalledVersion) {\n \/\/ Compare to an existing extension.\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"good\")\n .AppendASCII(\"Extensions\");\n\n const std::string kId = \"behllobkkfkfnphdnhnkndlbkcpglgmj\";\n const std::string kCurrentVersion = \"1.0.0.0\";\n\n FilePath version_dir;\n\n ASSERT_EQ(Extension::UPGRADE,\n extension_file_util::CompareToInstalledVersion(\n install_dir, kId, kCurrentVersion, \"1.0.0.1\", &version_dir));\n\n ASSERT_EQ(Extension::REINSTALL,\n extension_file_util::CompareToInstalledVersion(\n install_dir, kId, kCurrentVersion, \"1.0.0.0\", &version_dir));\n\n ASSERT_EQ(Extension::REINSTALL,\n extension_file_util::CompareToInstalledVersion(\n install_dir, kId, kCurrentVersion, \"1.0.0\", &version_dir));\n\n ASSERT_EQ(Extension::DOWNGRADE,\n extension_file_util::CompareToInstalledVersion(\n install_dir, kId, kCurrentVersion, \"0.0.1.0\", &version_dir));\n\n \/\/ Compare to an extension that is missing its manifest file.\n ScopedTempDir temp;\n ASSERT_TRUE(temp.CreateUniqueTempDir());\n FilePath src = install_dir.AppendASCII(kId).AppendASCII(kCurrentVersion);\n FilePath dest = temp.path().AppendASCII(kId).AppendASCII(kCurrentVersion);\n ASSERT_TRUE(file_util::CreateDirectory(dest.DirName()));\n ASSERT_TRUE(file_util::CopyDirectory(src, dest, true));\n ASSERT_TRUE(file_util::Delete(dest.AppendASCII(\"manifest.json\"), false));\n\n ASSERT_EQ(Extension::NEW_INSTALL,\n extension_file_util::CompareToInstalledVersion(\n temp.path(), kId, kCurrentVersion, \"1.0.0\", &version_dir));\n\n \/\/ Compare to a non-existent extension.\n const std::string kMissingVersion = \"\";\n const std::string kBadId = \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\";\n ASSERT_EQ(Extension::NEW_INSTALL,\n extension_file_util::CompareToInstalledVersion(\n temp.path(), kBadId, kMissingVersion, \"1.0.0\", &version_dir));\n}\n\nTEST(ExtensionFileUtil, LoadExtensionWithValidLocales) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"good\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"behllobkkfkfnphdnhnkndlbkcpglgmj\")\n .AppendASCII(\"1.0.0.0\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_TRUE(extension != NULL);\n EXPECT_EQ(\"The first extension that I made.\", extension->description());\n}\n\nTEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"good\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"bjafgdebaacbbbecmhlhpofkepfkgcpa\")\n .AppendASCII(\"1.0\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_FALSE(extension == NULL);\n EXPECT_TRUE(error.empty());\n}\n\nTEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) {\n ScopedTempDir temp;\n ASSERT_TRUE(temp.CreateUniqueTempDir());\n\n FilePath src_path = temp.path().AppendASCII(\"some_dir\");\n ASSERT_TRUE(file_util::CreateDirectory(src_path));\n\n std::string data = \"{ \\\"name\\\": { \\\"message\\\": \\\"foobar\\\" } }\";\n ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII(\"some_file.txt\"),\n data.c_str(), data.length()));\n std::string error;\n EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),\n &error));\n}\n\nTEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) {\n ScopedTempDir temp;\n ASSERT_TRUE(temp.CreateUniqueTempDir());\n\n FilePath src_path = temp.path().Append(Extension::kLocaleFolder);\n ASSERT_TRUE(file_util::CreateDirectory(src_path));\n\n std::string error;\n EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),\n &error));\n}\n\nTEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) {\n ScopedTempDir temp;\n ASSERT_TRUE(temp.CreateUniqueTempDir());\n\n FilePath src_path = temp.path().Append(Extension::kLocaleFolder);\n ASSERT_TRUE(file_util::CreateDirectory(src_path));\n\n src_path = temp.path().AppendASCII(\"_some_dir\");\n ASSERT_TRUE(file_util::CreateDirectory(src_path));\n\n std::string error;\n EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(),\n &error));\n}\n\nTEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"bad\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"dddddddddddddddddddddddddddddddd\")\n .AppendASCII(\"1.0\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_TRUE(extension == NULL);\n ASSERT_FALSE(error.empty());\n ASSERT_STREQ(\"Manifest file is missing or unreadable.\", error.c_str());\n}\n\nTEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"bad\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\")\n .AppendASCII(\"1.0\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_TRUE(extension == NULL);\n ASSERT_FALSE(error.empty());\n ASSERT_STREQ(\"Manifest is not valid JSON. \"\n \"Line: 2, column: 16, Syntax error.\", error.c_str());\n}\n\nTEST(ExtensionFileUtil, MissingPrivacyBlacklist) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"privacy_blacklists\")\n .AppendASCII(\"missing_blacklist\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_TRUE(extension == NULL);\n ASSERT_FALSE(error.empty());\n EXPECT_TRUE(MatchPatternASCII(error,\n \"Could not load '*privacy_blacklist.pbl' for privacy blacklist: \"\n \"file does not exist.\")) << error;\n}\n\nTEST(ExtensionFileUtil, InvalidPrivacyBlacklist) {\n FilePath install_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));\n install_dir = install_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"privacy_blacklists\")\n .AppendASCII(\"invalid_blacklist\");\n\n std::string error;\n scoped_ptr extension(\n extension_file_util::LoadExtension(install_dir, false, &error));\n ASSERT_TRUE(extension == NULL);\n ASSERT_FALSE(error.empty());\n EXPECT_TRUE(MatchPatternASCII(error,\n \"Could not load '*privacy_blacklist.pbl' for privacy blacklist: \"\n \"Incorrect header.\")) << error;\n}\n\n#define URL_PREFIX \"chrome-extension:\/\/extension-id\/\"\n\nTEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) {\n struct TestCase {\n const char* url;\n const char* expected_relative_path;\n } test_cases[] = {\n { URL_PREFIX \"simple.html\",\n \"simple.html\" },\n { URL_PREFIX \"directory\/to\/file.html\",\n \"directory\/to\/file.html\" },\n { URL_PREFIX \"escape%20spaces.html\",\n \"escape spaces.html\" },\n { URL_PREFIX \"%C3%9Cber.html\",\n \"\\xC3\\x9C\" \"ber.html\" },\n };\n\n for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {\n GURL url(test_cases[i].url);\n#if defined(OS_POSIX)\n FilePath expected_path(test_cases[i].expected_relative_path);\n#elif defined(OS_WIN)\n FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path));\n#endif\n\n FilePath actual_path =\n extension_file_util::ExtensionURLToRelativeFilePath(url);\n EXPECT_FALSE(actual_path.IsAbsolute()) <<\n \" For the path \" << actual_path.value();\n EXPECT_EQ(expected_path.value(), actual_path.value());\n }\n}\n\n\/\/ TODO(aa): More tests as motivation allows. Maybe steal some from\n\/\/ ExtensionsService? Many of them could probably be tested here without the\n\/\/ MessageLoop shenanigans.\n<|endoftext|>"} {"text":"\/* This file is part of the KDE project\n Copyright (C) 2006-2008 Matthias Kretz \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), Trolltech ASA \n (or its successors, if any) and the KDE Free Qt Foundation, which shall\n act as a proxy defined in Section 6 of version 3 of the license.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public \n License along with this library. If not, see .\n\n*\/\n\n#include \"globalconfig_p.h\"\n\n#include \"factory_p.h\"\n#include \"objectdescription.h\"\n#include \"phonondefs_p.h\"\n#include \"platformplugin.h\"\n#include \"backendinterface.h\"\n#include \"qsettingsgroup_p.h\"\n#include \"phononnamespace_p.h\"\n\n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\nnamespace Phonon\n{\n\nGlobalConfig::GlobalConfig(QObject *parent)\n : QObject(parent)\n , m_config(QLatin1String(\"kde.org\"), QLatin1String(\"libphonon\"))\n{\n}\n\nGlobalConfig::~GlobalConfig()\n{\n}\n\nenum WhatToFilter {\n FilterAdvancedDevices = 1,\n FilterHardwareDevices = 2\n};\n\nstatic void filter(ObjectDescriptionType type, BackendInterface *backendIface, QList *list, int whatToFilter)\n{\n QMutableListIterator it(*list);\n while (it.hasNext()) {\n const QHash properties = backendIface->objectDescriptionProperties(type, it.next());\n QVariant var;\n if (whatToFilter & FilterAdvancedDevices) {\n var = properties.value(\"isAdvanced\");\n if (var.isValid() && var.toBool()) {\n it.remove();\n continue;\n }\n }\n if (whatToFilter & FilterHardwareDevices) {\n var = properties.value(\"isHardwareDevice\");\n if (var.isValid() && var.toBool()) {\n it.remove();\n continue;\n }\n }\n }\n}\n\nstatic QList listSortedByConfig(const QSettingsGroup &backendConfig, Phonon::Category category, QList &defaultList)\n{\n if (defaultList.size() <= 1) {\n \/\/ nothing to sort\n return defaultList;\n } else {\n \/\/ make entries unique\n QSet seen;\n QMutableListIterator it(defaultList);\n while (it.hasNext()) {\n if (seen.contains(it.next())) {\n it.remove();\n } else {\n seen.insert(it.value());\n }\n }\n }\n\n QString categoryKey = QLatin1String(\"Category_\") + QString::number(static_cast(category));\n if (!backendConfig.hasKey(categoryKey)) {\n \/\/ no list in config for the given category\n categoryKey = QLatin1String(\"Category_\") + QString::number(static_cast(Phonon::NoCategory));\n if (!backendConfig.hasKey(categoryKey)) {\n \/\/ no list in config for NoCategory\n return defaultList;\n }\n }\n\n \/\/Now the list from m_config\n QList deviceList = backendConfig.value(categoryKey, QList());\n\n \/\/if there are devices in m_config that the backend doesn't report, remove them from the list\n QMutableListIterator i(deviceList);\n while (i.hasNext()) {\n if (0 == defaultList.removeAll(i.next())) {\n i.remove();\n }\n }\n\n \/\/if the backend reports more devices that are not in m_config append them to the list\n deviceList += defaultList;\n\n return deviceList;\n}\n\nQList GlobalConfig::audioOutputDeviceListFor(Phonon::Category category, HideAdvancedDevicesOverride override) const\n{\n \/\/The devices need to be stored independently for every backend\n const QSettingsGroup backendConfig(&m_config, QLatin1String(\"AudioOutputDevice\")); \/\/ + Factory::identifier());\n const QSettingsGroup generalGroup(&m_config, QLatin1String(\"General\"));\n const bool hideAdvancedDevices = (override == FromSettings\n ? generalGroup.value(QLatin1String(\"HideAdvancedDevices\"), true)\n : static_cast(override));\n\n PlatformPlugin *platformPlugin = Factory::platformPlugin();\n BackendInterface *backendIface = qobject_cast(Factory::backend());\n\n QList defaultList;\n if (platformPlugin) {\n \/\/ the platform plugin lists the audio devices for the platform\n \/\/ this list already is in default order (as defined by the platform plugin)\n defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);\n QMutableListIterator it(defaultList);\n while (it.hasNext()) {\n AudioOutputDevice objDesc = AudioOutputDevice::fromIndex(it.next());\n const QVariant var = objDesc.property(\"isAdvanced\");\n if (var.isValid() && var.toBool()) {\n it.remove();\n }\n }\n }\n\n \/\/ lookup the available devices directly from the backend (mostly for virtual devices)\n if (backendIface) {\n \/\/ this list already is in default order (as defined by the backend)\n QList list = backendIface->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);\n if (hideAdvancedDevices || !defaultList.isEmpty()) {\n filter(AudioOutputDeviceType, backendIface, &list,\n (hideAdvancedDevices ? FilterAdvancedDevices : 0)\n \/\/ the platform plugin already provided the hardware devices\n | (defaultList.isEmpty() ? 0 : FilterHardwareDevices)\n );\n }\n defaultList += list;\n }\n\n return listSortedByConfig(backendConfig, category, defaultList);\n}\n\nint GlobalConfig::audioOutputDeviceFor(Phonon::Category category) const\n{\n QList ret = audioOutputDeviceListFor(category);\n if (ret.isEmpty())\n return -1;\n return ret.first();\n}\n\nQList GlobalConfig::audioCaptureDeviceListFor(Phonon::Category category, HideAdvancedDevicesOverride override) const\n{\n \/\/The devices need to be stored independently for every backend\n const QSettingsGroup backendConfig(&m_config, QLatin1String(\"AudioCaptureDevice\")); \/\/ + Factory::identifier());\n const QSettingsGroup generalGroup(&m_config, QLatin1String(\"General\"));\n const bool hideAdvancedDevices = (override == FromSettings\n ? generalGroup.value(QLatin1String(\"HideAdvancedDevices\"), true)\n : static_cast(override));\n\n PlatformPlugin *platformPlugin = Factory::platformPlugin();\n BackendInterface *backendIface = qobject_cast(Factory::backend());\n\n QList defaultList;\n if (platformPlugin) {\n \/\/ the platform plugin lists the audio devices for the platform\n \/\/ this list already is in default order (as defined by the platform plugin)\n defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);\n QMutableListIterator it(defaultList);\n while (it.hasNext()) {\n AudioCaptureDevice objDesc = AudioCaptureDevice::fromIndex(it.next());\n const QVariant var = objDesc.property(\"isAdvanced\");\n if (var.isValid() && var.toBool()) {\n it.remove();\n }\n }\n }\n\n \/\/ lookup the available devices directly from the backend (mostly for virtual devices)\n if (backendIface) {\n \/\/ this list already is in default order (as defined by the backend)\n QList list = backendIface->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);\n if (hideAdvancedDevices || !defaultList.isEmpty()) {\n filter(AudioCaptureDeviceType, backendIface, &list,\n (hideAdvancedDevices ? FilterAdvancedDevices : 0)\n \/\/ the platform plugin already provided the hardware devices\n | (defaultList.isEmpty() ? 0 : FilterHardwareDevices)\n );\n }\n defaultList += list;\n }\n\n return listSortedByConfig(backendConfig, category, defaultList);\n}\n\nint GlobalConfig::audioCaptureDeviceFor(Phonon::Category category) const\n{\n QList ret = audioCaptureDeviceListFor(category);\n if (ret.isEmpty())\n return -1;\n return ret.first();\n}\n\n} \/\/ namespace Phonon\n\nQT_END_NAMESPACE\n\n#include \"moc_globalconfig_p.cpp\"\n\n\/\/ vim: sw=4 ts=4\nunhide advanced devices from the platform plugin BUG: 166713\/* This file is part of the KDE project\n Copyright (C) 2006-2008 Matthias Kretz \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), Trolltech ASA \n (or its successors, if any) and the KDE Free Qt Foundation, which shall\n act as a proxy defined in Section 6 of version 3 of the license.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public \n License along with this library. If not, see .\n\n*\/\n\n#include \"globalconfig_p.h\"\n\n#include \"factory_p.h\"\n#include \"objectdescription.h\"\n#include \"phonondefs_p.h\"\n#include \"platformplugin.h\"\n#include \"backendinterface.h\"\n#include \"qsettingsgroup_p.h\"\n#include \"phononnamespace_p.h\"\n\n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\nnamespace Phonon\n{\n\nGlobalConfig::GlobalConfig(QObject *parent)\n : QObject(parent)\n , m_config(QLatin1String(\"kde.org\"), QLatin1String(\"libphonon\"))\n{\n}\n\nGlobalConfig::~GlobalConfig()\n{\n}\n\nenum WhatToFilter {\n FilterAdvancedDevices = 1,\n FilterHardwareDevices = 2\n};\n\nstatic void filter(ObjectDescriptionType type, BackendInterface *backendIface, QList *list, int whatToFilter)\n{\n QMutableListIterator it(*list);\n while (it.hasNext()) {\n const QHash properties = backendIface->objectDescriptionProperties(type, it.next());\n QVariant var;\n if (whatToFilter & FilterAdvancedDevices) {\n var = properties.value(\"isAdvanced\");\n if (var.isValid() && var.toBool()) {\n it.remove();\n continue;\n }\n }\n if (whatToFilter & FilterHardwareDevices) {\n var = properties.value(\"isHardwareDevice\");\n if (var.isValid() && var.toBool()) {\n it.remove();\n continue;\n }\n }\n }\n}\n\nstatic QList listSortedByConfig(const QSettingsGroup &backendConfig, Phonon::Category category, QList &defaultList)\n{\n if (defaultList.size() <= 1) {\n \/\/ nothing to sort\n return defaultList;\n } else {\n \/\/ make entries unique\n QSet seen;\n QMutableListIterator it(defaultList);\n while (it.hasNext()) {\n if (seen.contains(it.next())) {\n it.remove();\n } else {\n seen.insert(it.value());\n }\n }\n }\n\n QString categoryKey = QLatin1String(\"Category_\") + QString::number(static_cast(category));\n if (!backendConfig.hasKey(categoryKey)) {\n \/\/ no list in config for the given category\n categoryKey = QLatin1String(\"Category_\") + QString::number(static_cast(Phonon::NoCategory));\n if (!backendConfig.hasKey(categoryKey)) {\n \/\/ no list in config for NoCategory\n return defaultList;\n }\n }\n\n \/\/Now the list from m_config\n QList deviceList = backendConfig.value(categoryKey, QList());\n\n \/\/if there are devices in m_config that the backend doesn't report, remove them from the list\n QMutableListIterator i(deviceList);\n while (i.hasNext()) {\n if (0 == defaultList.removeAll(i.next())) {\n i.remove();\n }\n }\n\n \/\/if the backend reports more devices that are not in m_config append them to the list\n deviceList += defaultList;\n\n return deviceList;\n}\n\nQList GlobalConfig::audioOutputDeviceListFor(Phonon::Category category, HideAdvancedDevicesOverride override) const\n{\n \/\/The devices need to be stored independently for every backend\n const QSettingsGroup backendConfig(&m_config, QLatin1String(\"AudioOutputDevice\")); \/\/ + Factory::identifier());\n const QSettingsGroup generalGroup(&m_config, QLatin1String(\"General\"));\n const bool hideAdvancedDevices = (override == FromSettings\n ? generalGroup.value(QLatin1String(\"HideAdvancedDevices\"), true)\n : static_cast(override));\n\n PlatformPlugin *platformPlugin = Factory::platformPlugin();\n BackendInterface *backendIface = qobject_cast(Factory::backend());\n\n QList defaultList;\n if (platformPlugin) {\n \/\/ the platform plugin lists the audio devices for the platform\n \/\/ this list already is in default order (as defined by the platform plugin)\n defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);\n if (hideAdvancedDevices) {\n QMutableListIterator it(defaultList);\n while (it.hasNext()) {\n AudioOutputDevice objDesc = AudioOutputDevice::fromIndex(it.next());\n const QVariant var = objDesc.property(\"isAdvanced\");\n if (var.isValid() && var.toBool()) {\n it.remove();\n }\n }\n }\n }\n\n \/\/ lookup the available devices directly from the backend (mostly for virtual devices)\n if (backendIface) {\n \/\/ this list already is in default order (as defined by the backend)\n QList list = backendIface->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);\n if (hideAdvancedDevices || !defaultList.isEmpty()) {\n filter(AudioOutputDeviceType, backendIface, &list,\n (hideAdvancedDevices ? FilterAdvancedDevices : 0)\n \/\/ the platform plugin already provided the hardware devices\n | (defaultList.isEmpty() ? 0 : FilterHardwareDevices)\n );\n }\n defaultList += list;\n }\n\n return listSortedByConfig(backendConfig, category, defaultList);\n}\n\nint GlobalConfig::audioOutputDeviceFor(Phonon::Category category) const\n{\n QList ret = audioOutputDeviceListFor(category);\n if (ret.isEmpty())\n return -1;\n return ret.first();\n}\n\nQList GlobalConfig::audioCaptureDeviceListFor(Phonon::Category category, HideAdvancedDevicesOverride override) const\n{\n \/\/The devices need to be stored independently for every backend\n const QSettingsGroup backendConfig(&m_config, QLatin1String(\"AudioCaptureDevice\")); \/\/ + Factory::identifier());\n const QSettingsGroup generalGroup(&m_config, QLatin1String(\"General\"));\n const bool hideAdvancedDevices = (override == FromSettings\n ? generalGroup.value(QLatin1String(\"HideAdvancedDevices\"), true)\n : static_cast(override));\n\n PlatformPlugin *platformPlugin = Factory::platformPlugin();\n BackendInterface *backendIface = qobject_cast(Factory::backend());\n\n QList defaultList;\n if (platformPlugin) {\n \/\/ the platform plugin lists the audio devices for the platform\n \/\/ this list already is in default order (as defined by the platform plugin)\n defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);\n if (hideAdvancedDevices) {\n QMutableListIterator it(defaultList);\n while (it.hasNext()) {\n AudioCaptureDevice objDesc = AudioCaptureDevice::fromIndex(it.next());\n const QVariant var = objDesc.property(\"isAdvanced\");\n if (var.isValid() && var.toBool()) {\n it.remove();\n }\n }\n }\n }\n\n \/\/ lookup the available devices directly from the backend (mostly for virtual devices)\n if (backendIface) {\n \/\/ this list already is in default order (as defined by the backend)\n QList list = backendIface->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);\n if (hideAdvancedDevices || !defaultList.isEmpty()) {\n filter(AudioCaptureDeviceType, backendIface, &list,\n (hideAdvancedDevices ? FilterAdvancedDevices : 0)\n \/\/ the platform plugin already provided the hardware devices\n | (defaultList.isEmpty() ? 0 : FilterHardwareDevices)\n );\n }\n defaultList += list;\n }\n\n return listSortedByConfig(backendConfig, category, defaultList);\n}\n\nint GlobalConfig::audioCaptureDeviceFor(Phonon::Category category) const\n{\n QList ret = audioCaptureDeviceListFor(category);\n if (ret.isEmpty())\n return -1;\n return ret.first();\n}\n\n} \/\/ namespace Phonon\n\nQT_END_NAMESPACE\n\n#include \"moc_globalconfig_p.cpp\"\n\n\/\/ vim: sw=4 ts=4\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2011\n * Alessio Sclocco \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\n *\/\n\n#define __CL_ENABLE_EXCEPTIONS\n#include \n#include \n#include \n\nusing std::string;\nusing std::make_pair;\n\n#include \n#include \n#include \n#include \n\nusing isa::OpenCL::Kernel;\nusing isa::OpenCL::GPUData;\nusing isa::Exceptions::OpenCLError;\nusing isa::utils::toStringValue;\n\n\n#ifndef MEMSET_HPP\n#define MEMSET_HPP\n\nnamespace isa {\n\nnamespace OpenCL {\n\ntemplate < typename T > class Memset : public Kernel< T > {\npublic:\n\tMemset(string dataType);\n\n\tvoid generateCode() throw (OpenCLError);\n\tvoid operator()(T value, GPUData< T > *memory) throw (OpenCLError);\n\n\tinline void setNrThreadsPerBlock(unsigned int threads);\n\tinline void setNrThreads(unsigned int threads);\n\tinline void setNrRows(unsigned int rows);\n\t\nprivate:\n\tstring *code;\n\tunsigned int nrThreadsPerBlock;\n\tunsigned int nrThreads;\n\tunsigned int nrRows;\n};\n\n\n\/\/ Implementation\n\ntemplate< typename T > Memset< T >::Memset(string dataType) : Kernel< T >(\"Memset\", dataType), code(0), nrThreadsPerBlock(0), nrThreads(0), nrRows(0) {}\n\n\ntemplate< typename T > void Memset< T >::generateCode() throw (OpenCLError) {\n\tif ( this->code != 0 ) {\n\t\tdelete this->code;\n\t}\n\tthis->code = new string();\n\t*(this->code) = \"__kernel void \" + this->name + \"(\" + this->dataType + \" value, __global \" + this->dataType + \" *mem) {\\n\"\n\t\t\"unsigned int id = (get_group_id(1) * get_num_groups(0) * get_local_size(0)) + (get_group_id(0) * get_local_size(0)) + get_local_id(0);\\n\"\n\t\t\"mem[id] = value;\\n\"\n\t\t\"}\";\n\n\tthis->setAsync(true);\n\tthis->compile();\n}\n\n\ntemplate< typename T > void Memset< T >::operator()(T value, GPUData< T > *memory) throw (OpenCLError) {\n\tcl::NDRange globalSize(nrThreads \/ nrRows, nrRows);\n\tcl::NDRange localSize(nrThreadsPerBlock, 1);\n\n\tthis->setArgument(0, value);\n\tthis->setArgument(1, *(memory->getDeviceData()));\n\n\tthis->run(globalSize, localSize);\n}\n\n\ntemplate< typename T > inline void Memset< T >::setNrThreadsPerBlock(unsigned int threads) {\n\tnrThreadsPerBlock = threads;\n}\n\n\ntemplate< typename T > inline void Memset< T >::setNrThreads(unsigned int threads) {\n\tnrThreads = threads;\n}\n\n\ntemplate< typename T > inline void Memset< T >::setNrRows(unsigned int rows) {\n\tnrRows = rows;\n}\n\n\n} \/\/ OpenCL\n} \/\/ isa\n\n#endif \/\/ MEMSET_HPP\n\nA small bug in Memset. Solved now.\/*\n * Copyright (C) 2011\n * Alessio Sclocco \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\n *\/\n\n#define __CL_ENABLE_EXCEPTIONS\n#include \n#include \n#include \n\nusing std::string;\nusing std::make_pair;\n\n#include \n#include \n#include \n#include \n\nusing isa::OpenCL::Kernel;\nusing isa::OpenCL::GPUData;\nusing isa::Exceptions::OpenCLError;\nusing isa::utils::toStringValue;\n\n\n#ifndef MEMSET_HPP\n#define MEMSET_HPP\n\nnamespace isa {\n\nnamespace OpenCL {\n\ntemplate < typename T > class Memset : public Kernel< T > {\npublic:\n\tMemset(string dataType);\n\n\tvoid generateCode() throw (OpenCLError);\n\tvoid operator()(T value, GPUData< T > *memory) throw (OpenCLError);\n\n\tinline void setNrThreadsPerBlock(unsigned int threads);\n\tinline void setNrThreads(unsigned int threads);\n\tinline void setNrRows(unsigned int rows);\n\t\nprivate:\n\tunsigned int nrThreadsPerBlock;\n\tunsigned int nrThreads;\n\tunsigned int nrRows;\n};\n\n\n\/\/ Implementation\n\ntemplate< typename T > Memset< T >::Memset(string dataType) : Kernel< T >(\"Memset\", dataType), nrThreadsPerBlock(0), nrThreads(0), nrRows(0) {}\n\n\ntemplate< typename T > void Memset< T >::generateCode() throw (OpenCLError) {\n\tif ( this->code != 0 ) {\n\t\tdelete this->code;\n\t}\n\tthis->code = new string();\n\t*(this->code) = \"__kernel void \" + this->name + \"(\" + this->dataType + \" value, __global \" + this->dataType + \" *mem) {\\n\"\n\t\t\"unsigned int id = (get_group_id(1) * get_num_groups(0) * get_local_size(0)) + (get_group_id(0) * get_local_size(0)) + get_local_id(0);\\n\"\n\t\t\"mem[id] = value;\\n\"\n\t\t\"}\";\n\n\tthis->setAsync(true);\n\tthis->compile();\n}\n\n\ntemplate< typename T > void Memset< T >::operator()(T value, GPUData< T > *memory) throw (OpenCLError) {\n\tcl::NDRange globalSize(nrThreads \/ nrRows, nrRows);\n\tcl::NDRange localSize(nrThreadsPerBlock, 1);\n\n\tthis->setArgument(0, value);\n\tthis->setArgument(1, *(memory->getDeviceData()));\n\n\tthis->run(globalSize, localSize);\n}\n\n\ntemplate< typename T > inline void Memset< T >::setNrThreadsPerBlock(unsigned int threads) {\n\tnrThreadsPerBlock = threads;\n}\n\n\ntemplate< typename T > inline void Memset< T >::setNrThreads(unsigned int threads) {\n\tnrThreads = threads;\n}\n\n\ntemplate< typename T > inline void Memset< T >::setNrRows(unsigned int rows) {\n\tnrRows = rows;\n}\n\n\n} \/\/ OpenCL\n} \/\/ isa\n\n#endif \/\/ MEMSET_HPP\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2011, Peter Thorson. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the WebSocket++ Project nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *\/\n\n#ifndef WEBSOCKET_CONSTANTS_HPP\n#define WEBSOCKET_CONSTANTS_HPP\n\n#ifndef __STDC_LIMIT_MACROS\n #define __STDC_LIMIT_MACROS\n#endif\n#include \n\n\/\/ SIZE_MAX appears to be a compiler thing not an OS header thing.\n\/\/ make sure it is defined.\n#ifndef SIZE_MAX\n #define SIZE_MAX ((size_t)(-1))\n#endif\n\n#ifdef _MSC_VER\n #ifndef _WEBSOCKETPP_CPP11_FRIEND_\n #define _WEBSOCKETPP_CPP11_FRIEND_\n #endif\n#endif\n\n#include \n#include \n#include \n\n#include \n\n\/\/ Defaults\nnamespace websocketpp {\n static const std::string USER_AGENT = \"WebSocket++\/0.2.0dev\";\n \n typedef std::vector binary_string;\n typedef boost::shared_ptr binary_string_ptr;\n \n typedef std::string utf8_string;\n typedef boost::shared_ptr utf8_string_ptr;\n \n const uint64_t DEFAULT_MAX_MESSAGE_SIZE = 0xFFFFFF; \/\/ ~16MB\n \n const size_t DEFAULT_READ_THRESHOLD = 1; \/\/ 512 would be a more sane value for this\n const bool DEFAULT_SILENT_CLOSE = false; \/\/ true\n \n const size_t MAX_THREAD_POOL_SIZE = 64;\n \n const uint16_t DEFAULT_PORT = 80;\n const uint16_t DEFAULT_SECURE_PORT = 443;\n \n inline uint16_t default_port(bool secure) {\n return (secure ? DEFAULT_SECURE_PORT : DEFAULT_PORT);\n } \n \n namespace session {\n namespace state {\n enum value {\n CONNECTING = 0,\n OPEN = 1,\n CLOSING = 2,\n CLOSED = 3\n };\n }\n }\n \n namespace close {\n namespace status {\n enum value {\n INVALID_END = 999,\n NORMAL = 1000,\n GOING_AWAY = 1001,\n PROTOCOL_ERROR = 1002,\n UNSUPPORTED_DATA = 1003,\n RSV_ADHOC_1 = 1004,\n NO_STATUS = 1005,\n ABNORMAL_CLOSE = 1006,\n INVALID_PAYLOAD = 1007,\n POLICY_VIOLATION = 1008,\n MESSAGE_TOO_BIG = 1009,\n EXTENSION_REQUIRE = 1010,\n INTERNAL_ENDPOINT_ERROR = 1011,\n RSV_ADHOC_2 = 1012,\n RSV_ADHOC_3 = 1013,\n RSV_ADHOC_4 = 1014,\n TLS_HANDSHAKE = 1015,\n RSV_START = 1016,\n RSV_END = 2999,\n INVALID_START = 5000\n };\n \n inline bool reserved(value s) {\n return ((s >= RSV_START && s <= RSV_END) || s == RSV_ADHOC_1 \n || s == RSV_ADHOC_2 || s == RSV_ADHOC_3 || s == RSV_ADHOC_4);\n }\n \n \/\/ Codes invalid on the wire\n inline bool invalid(value s) {\n return ((s <= INVALID_END || s >= INVALID_START) || \n s == NO_STATUS || \n s == ABNORMAL_CLOSE || \n s == TLS_HANDSHAKE);\n }\n \n \/\/ TODO functions for application ranges?\n } \/\/ namespace status\n } \/\/ namespace close\n \n namespace fail {\n namespace status {\n enum value {\n GOOD = 0, \/\/ no failure yet!\n SYSTEM = 1, \/\/ system call returned error, check that code\n WEBSOCKET = 2, \/\/ websocket close codes contain error\n UNKNOWN = 3, \/\/ No failure information is avaliable\n TIMEOUT_TLS = 4, \/\/ TLS handshake timed out\n TIMEOUT_WS = 5 \/\/ WS handshake timed out\n };\n } \/\/ namespace status\n } \/\/ namespace fail\n \n namespace frame {\n \/\/ Opcodes are 4 bits\n \/\/ See spec section 5.2\n namespace opcode {\n enum value {\n CONTINUATION = 0x0,\n TEXT = 0x1,\n BINARY = 0x2,\n RSV3 = 0x3,\n RSV4 = 0x4,\n RSV5 = 0x5,\n RSV6 = 0x6,\n RSV7 = 0x7,\n CLOSE = 0x8,\n PING = 0x9,\n PONG = 0xA,\n CONTROL_RSVB = 0xB,\n CONTROL_RSVC = 0xC,\n CONTROL_RSVD = 0xD,\n CONTROL_RSVE = 0xE,\n CONTROL_RSVF = 0xF\n };\n \n inline bool reserved(value v) {\n return (v >= RSV3 && v <= RSV7) || \n (v >= CONTROL_RSVB && v <= CONTROL_RSVF);\n }\n \n inline bool invalid(value v) {\n return (v > 0xF || v < 0);\n }\n \n inline bool is_control(value v) {\n return v >= 0x8;\n }\n }\n \n namespace limits {\n static const uint8_t PAYLOAD_SIZE_BASIC = 125;\n static const uint16_t PAYLOAD_SIZE_EXTENDED = 0xFFFF; \/\/ 2^16, 65535\n static const uint64_t PAYLOAD_SIZE_JUMBO = 0x7FFFFFFFFFFFFFFFLL;\/\/2^63\n }\n } \/\/ namespace frame\n \n \/\/ exception class for errors that should be propogated back to the user.\n namespace error {\n enum value {\n GENERIC = 0,\n \/\/ send attempted when endpoint write queue was full\n SEND_QUEUE_FULL = 1,\n PAYLOAD_VIOLATION = 2,\n ENDPOINT_UNSECURE = 3,\n ENDPOINT_UNAVAILABLE = 4,\n INVALID_URI = 5,\n NO_OUTGOING_MESSAGES = 6,\n INVALID_STATE = 7\n };\n }\n \n class exception : public std::exception {\n public: \n exception(const std::string& msg,\n error::value code = error::GENERIC) \n : m_msg(msg),m_code(code) {}\n ~exception() throw() {}\n \n virtual const char* what() const throw() {\n return m_msg.c_str();\n }\n \n error::value code() const throw() {\n return m_code;\n }\n \n std::string m_msg;\n error::value m_code;\n };\n}\n\n#endif \/\/ WEBSOCKET_CONSTANTS_HPP\nUpdates user agent\/version string\/*\n * Copyright (c) 2011, Peter Thorson. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the WebSocket++ Project nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *\/\n\n#ifndef WEBSOCKET_CONSTANTS_HPP\n#define WEBSOCKET_CONSTANTS_HPP\n\n#ifndef __STDC_LIMIT_MACROS\n #define __STDC_LIMIT_MACROS\n#endif\n#include \n\n\/\/ SIZE_MAX appears to be a compiler thing not an OS header thing.\n\/\/ make sure it is defined.\n#ifndef SIZE_MAX\n #define SIZE_MAX ((size_t)(-1))\n#endif\n\n#ifdef _MSC_VER\n #ifndef _WEBSOCKETPP_CPP11_FRIEND_\n #define _WEBSOCKETPP_CPP11_FRIEND_\n #endif\n#endif\n\n#include \n#include \n#include \n\n#include \n\n\/\/ Defaults\nnamespace websocketpp {\n static const std::string USER_AGENT = \"WebSocket++\/0.2.1dev\";\n \n typedef std::vector binary_string;\n typedef boost::shared_ptr binary_string_ptr;\n \n typedef std::string utf8_string;\n typedef boost::shared_ptr utf8_string_ptr;\n \n const uint64_t DEFAULT_MAX_MESSAGE_SIZE = 0xFFFFFF; \/\/ ~16MB\n \n const size_t DEFAULT_READ_THRESHOLD = 1; \/\/ 512 would be a more sane value for this\n const bool DEFAULT_SILENT_CLOSE = false; \/\/ true\n \n const size_t MAX_THREAD_POOL_SIZE = 64;\n \n const uint16_t DEFAULT_PORT = 80;\n const uint16_t DEFAULT_SECURE_PORT = 443;\n \n inline uint16_t default_port(bool secure) {\n return (secure ? DEFAULT_SECURE_PORT : DEFAULT_PORT);\n } \n \n namespace session {\n namespace state {\n enum value {\n CONNECTING = 0,\n OPEN = 1,\n CLOSING = 2,\n CLOSED = 3\n };\n }\n }\n \n namespace close {\n namespace status {\n enum value {\n INVALID_END = 999,\n NORMAL = 1000,\n GOING_AWAY = 1001,\n PROTOCOL_ERROR = 1002,\n UNSUPPORTED_DATA = 1003,\n RSV_ADHOC_1 = 1004,\n NO_STATUS = 1005,\n ABNORMAL_CLOSE = 1006,\n INVALID_PAYLOAD = 1007,\n POLICY_VIOLATION = 1008,\n MESSAGE_TOO_BIG = 1009,\n EXTENSION_REQUIRE = 1010,\n INTERNAL_ENDPOINT_ERROR = 1011,\n RSV_ADHOC_2 = 1012,\n RSV_ADHOC_3 = 1013,\n RSV_ADHOC_4 = 1014,\n TLS_HANDSHAKE = 1015,\n RSV_START = 1016,\n RSV_END = 2999,\n INVALID_START = 5000\n };\n \n inline bool reserved(value s) {\n return ((s >= RSV_START && s <= RSV_END) || s == RSV_ADHOC_1 \n || s == RSV_ADHOC_2 || s == RSV_ADHOC_3 || s == RSV_ADHOC_4);\n }\n \n \/\/ Codes invalid on the wire\n inline bool invalid(value s) {\n return ((s <= INVALID_END || s >= INVALID_START) || \n s == NO_STATUS || \n s == ABNORMAL_CLOSE || \n s == TLS_HANDSHAKE);\n }\n \n \/\/ TODO functions for application ranges?\n } \/\/ namespace status\n } \/\/ namespace close\n \n namespace fail {\n namespace status {\n enum value {\n GOOD = 0, \/\/ no failure yet!\n SYSTEM = 1, \/\/ system call returned error, check that code\n WEBSOCKET = 2, \/\/ websocket close codes contain error\n UNKNOWN = 3, \/\/ No failure information is avaliable\n TIMEOUT_TLS = 4, \/\/ TLS handshake timed out\n TIMEOUT_WS = 5 \/\/ WS handshake timed out\n };\n } \/\/ namespace status\n } \/\/ namespace fail\n \n namespace frame {\n \/\/ Opcodes are 4 bits\n \/\/ See spec section 5.2\n namespace opcode {\n enum value {\n CONTINUATION = 0x0,\n TEXT = 0x1,\n BINARY = 0x2,\n RSV3 = 0x3,\n RSV4 = 0x4,\n RSV5 = 0x5,\n RSV6 = 0x6,\n RSV7 = 0x7,\n CLOSE = 0x8,\n PING = 0x9,\n PONG = 0xA,\n CONTROL_RSVB = 0xB,\n CONTROL_RSVC = 0xC,\n CONTROL_RSVD = 0xD,\n CONTROL_RSVE = 0xE,\n CONTROL_RSVF = 0xF\n };\n \n inline bool reserved(value v) {\n return (v >= RSV3 && v <= RSV7) || \n (v >= CONTROL_RSVB && v <= CONTROL_RSVF);\n }\n \n inline bool invalid(value v) {\n return (v > 0xF || v < 0);\n }\n \n inline bool is_control(value v) {\n return v >= 0x8;\n }\n }\n \n namespace limits {\n static const uint8_t PAYLOAD_SIZE_BASIC = 125;\n static const uint16_t PAYLOAD_SIZE_EXTENDED = 0xFFFF; \/\/ 2^16, 65535\n static const uint64_t PAYLOAD_SIZE_JUMBO = 0x7FFFFFFFFFFFFFFFLL;\/\/2^63\n }\n } \/\/ namespace frame\n \n \/\/ exception class for errors that should be propogated back to the user.\n namespace error {\n enum value {\n GENERIC = 0,\n \/\/ send attempted when endpoint write queue was full\n SEND_QUEUE_FULL = 1,\n PAYLOAD_VIOLATION = 2,\n ENDPOINT_UNSECURE = 3,\n ENDPOINT_UNAVAILABLE = 4,\n INVALID_URI = 5,\n NO_OUTGOING_MESSAGES = 6,\n INVALID_STATE = 7\n };\n }\n \n class exception : public std::exception {\n public: \n exception(const std::string& msg,\n error::value code = error::GENERIC) \n : m_msg(msg),m_code(code) {}\n ~exception() throw() {}\n \n virtual const char* what() const throw() {\n return m_msg.c_str();\n }\n \n error::value code() const throw() {\n return m_code;\n }\n \n std::string m_msg;\n error::value m_code;\n };\n}\n\n#endif \/\/ WEBSOCKET_CONSTANTS_HPP\n<|endoftext|>"} {"text":"\/\/ UjoImro, 2013\n\/\/ Experimental code for the CARP Project\n\/\/ Copyright (c) RealEyes, 2013\n\/\/ This version tests the responseMap calculation with input dumps\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cast.h\"\n#include \"mlp.hpp\"\n#include \"mlp_impl.h\"\n\n\/*\nextern int EF_ALIGNMENT = 0;\nextern int EF_PROTECT_BELOW = 0;\nextern int EF_PROTECT_FREE = 0;\nextern int EF_ALLOW_MALLOC_0 = 1;\nextern int EF_FILL = 1922;\n*\/\n\nnamespace { struct hack_t; }\nMatChar convertCVToMatChar ( const cv::Mat_ & input );\nmlp * convertHackToMlp ( const hack_t & hack );\nvoid freeClassifiers( mlp * classifiers[], int size );\nMatChar convertCVToMatChar ( const cv::Mat_ & input );\nMatFloat convertCVToMatFloat ( const cv::Mat_ & input );\ncv::Mat_ convertMatFloatToCV( MatFloat input );\nvoid allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] );\nvoid freeResponseMaps( MatFloat * responseMaps[], int size );\n\n\nnamespace {\n \n struct hack_t {\n int m_visibleLandmarks_size;\n int m_mapSize;\n \n cv::Mat_ shape;\n cv::Mat_ alignedImage;\n std::vector > m_classifiers;\n std::vector > responseMaps;\n \n template \n void serialize( MT0 & archiver, unsigned int ) {\n GEL_EXPORT_VAR( archiver, m_visibleLandmarks_size );\n GEL_EXPORT_VAR( archiver, m_mapSize );\n GEL_EXPORT_VAR( archiver, shape );\n GEL_EXPORT_VAR( archiver, alignedImage );\n GEL_EXPORT_VAR( archiver, m_classifiers );\n GEL_EXPORT_VAR( archiver, responseMaps ); \n } \/\/ serialize\n \n }; \/\/ struct hack_t\n \n class conductor_t {\n public:\n int id;\n hack_t hack;\n std::ifstream dumpStream;\n boost::archive::binary_iarchive importer;\n\n public:\n \n conductor_t() : id(0), dumpStream(\"response_dumps.bin\", std::ios::in | std::ios::binary ), importer(dumpStream) {\n \n }; \/\/ conductor_t\n \n }; \/\/ conductor_t\n\n} \/\/ unnamed namespace \n\n\n\nmlp *\nconvertHackToMlp ( const hack_t & hack )\n{\n assert(hack.m_visibleLandmarks_size==hack.m_classifiers.size());\n assert(hack.m_visibleLandmarks_size==hack.responseMaps.size());\n \n mlp * result;\n result = reinterpret_cast( malloc( sizeof(mlp) * hack.m_visibleLandmarks_size ) );\n\n \/\/ we export each classifier\n for (int q=0; q & input )\n{\n MatChar result = CreateMatChar( input.rows, input.cols );\n\n for ( int q=0; q & input )\n{\n MatFloat result = CreateMatFloat( input.rows, input.cols );\n \n for ( int q=0; q convertMatFloatToCV( MatFloat input )\n{\n cv::Mat_ result( input.rows, input.cols );\n \n for ( int q=0; q\nauto\nmicroseconds( T0 t0 ) -> decltype(std::chrono::duration_cast(t0).count())\n{\n return std::chrono::duration_cast(t0).count();\n}\n\n\nint main()\n{\n conductor_t conductor;\n int fail = 0;\n long int elapsed_time = 0;\n \n\n for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id); \n ((conductor.id != -1) and (conductor.id != 25));\n \/\/ conductor.id != -1;\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id)\n )\n {\n PRINT(conductor.id);\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n\n \/\/ here comes the function call\n {\n \/\/ preparing the inputs\n MatChar alignedImage = convertCVToMatChar(conductor.hack.alignedImage);\n MatFloat shape = convertCVToMatFloat(conductor.hack.shape);\n mlp * m_classifiers = convertHackToMlp(conductor.hack);\n MatFloat * responseMaps;\n allocateResponseMaps( conductor.hack.m_mapSize, conductor.hack.m_visibleLandmarks_size, &responseMaps );\n\n auto start = std::chrono::high_resolution_clock::now();\n calculateMaps(\n conductor.hack.m_visibleLandmarks_size,\n conductor.hack.m_mapSize,\n alignedImage,\n shape,\n m_classifiers,\n &responseMaps\n );\n auto end = std::chrono::high_resolution_clock::now();\n elapsed_time = microseconds(end - start); \n \n \/\/ releasing the inputs\n freeMatChar(&alignedImage);\n freeMatFloat(&shape);\n freeClassifiers(&m_classifiers, conductor.hack.m_classifiers.size());\n\n \/\/ converting the outputs\n std::vector< cv::Mat_ > calculatedResults;\n for (int q=0; q nextResult;\n nextResult = convertMatFloatToCV( responseMaps[q] );\n calculatedResults.push_back(nextResult); \n }\n \n \/\/ testing the output\n for (int q=0; q 0.5 ) fail++;\n \/\/ PRINT(fail);\n int tolerance = 49 * conductor.id * 0.005 + 3;\n \/\/ PRINT(tolerance); \n assert(fail < tolerance);\n }\n \n \/\/ releasing the outputs\n freeResponseMaps( &responseMaps, conductor.hack.m_visibleLandmarks_size );\n\n }\n \/\/ here comes the test\n \/\/ PRINT(cv::norm( ));\n }\n \n std::cout << \"total elapsed time = \" << elapsed_time \/ 1000000. << \" s.\" << std::endl; \n \/\/conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n \n return EXIT_SUCCESS;\n}\n\n\n\n\/\/ LuM end of file\ntesting the precision by outliers in test_mlp\/\/ UjoImro, 2013\n\/\/ Experimental code for the CARP Project\n\/\/ Copyright (c) RealEyes, 2013\n\/\/ This version tests the responseMap calculation with input dumps\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cast.h\"\n#include \"mlp.hpp\"\n#include \"mlp_impl.h\"\n\n\/*\nextern int EF_ALIGNMENT = 0;\nextern int EF_PROTECT_BELOW = 0;\nextern int EF_PROTECT_FREE = 0;\nextern int EF_ALLOW_MALLOC_0 = 1;\nextern int EF_FILL = 1922;\n*\/\n\nnamespace { struct hack_t; }\nMatChar convertCVToMatChar ( const cv::Mat_ & input );\nmlp * convertHackToMlp ( const hack_t & hack );\nvoid freeClassifiers( mlp * classifiers[], int size );\nMatChar convertCVToMatChar ( const cv::Mat_ & input );\nMatFloat convertCVToMatFloat ( const cv::Mat_ & input );\ncv::Mat_ convertMatFloatToCV( MatFloat input );\nvoid allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] );\nvoid freeResponseMaps( MatFloat * responseMaps[], int size );\n\n\nnamespace {\n \n struct hack_t {\n int m_visibleLandmarks_size;\n int m_mapSize;\n \n cv::Mat_ shape;\n cv::Mat_ alignedImage;\n std::vector > m_classifiers;\n std::vector > responseMaps;\n \n template \n void serialize( MT0 & archiver, unsigned int ) {\n GEL_EXPORT_VAR( archiver, m_visibleLandmarks_size );\n GEL_EXPORT_VAR( archiver, m_mapSize );\n GEL_EXPORT_VAR( archiver, shape );\n GEL_EXPORT_VAR( archiver, alignedImage );\n GEL_EXPORT_VAR( archiver, m_classifiers );\n GEL_EXPORT_VAR( archiver, responseMaps ); \n } \/\/ serialize\n \n }; \/\/ struct hack_t\n \n class conductor_t {\n public:\n int id;\n hack_t hack;\n std::ifstream dumpStream;\n boost::archive::binary_iarchive importer;\n\n public:\n \n conductor_t() : id(0), dumpStream(\"response_dumps.bin\", std::ios::in | std::ios::binary ), importer(dumpStream) {\n \n }; \/\/ conductor_t\n \n }; \/\/ conductor_t\n\n} \/\/ unnamed namespace \n\n\n\nmlp *\nconvertHackToMlp ( const hack_t & hack )\n{\n assert(hack.m_visibleLandmarks_size==hack.m_classifiers.size());\n assert(hack.m_visibleLandmarks_size==hack.responseMaps.size());\n \n mlp * result;\n result = reinterpret_cast( malloc( sizeof(mlp) * hack.m_visibleLandmarks_size ) );\n\n \/\/ we export each classifier\n for (int q=0; q & input )\n{\n MatChar result = CreateMatChar( input.rows, input.cols );\n\n for ( int q=0; q & input )\n{\n MatFloat result = CreateMatFloat( input.rows, input.cols );\n \n for ( int q=0; q convertMatFloatToCV( MatFloat input )\n{\n cv::Mat_ result( input.rows, input.cols );\n \n for ( int q=0; q\nauto\nmicroseconds( T0 t0 ) -> decltype(std::chrono::duration_cast(t0).count())\n{\n return std::chrono::duration_cast(t0).count();\n}\n\n\nint main()\n{\n conductor_t conductor;\n int fail = 0;\n long int elapsed_time = 0;\n \n\n for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id); \n ((conductor.id != -1) and (conductor.id != 25));\n \/\/ conductor.id != -1;\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id)\n )\n {\n PRINT(conductor.id);\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n\n \/\/ here comes the function call\n {\n \/\/ preparing the inputs\n MatChar alignedImage = convertCVToMatChar(conductor.hack.alignedImage);\n MatFloat shape = convertCVToMatFloat(conductor.hack.shape);\n mlp * m_classifiers = convertHackToMlp(conductor.hack);\n MatFloat * responseMaps;\n allocateResponseMaps( conductor.hack.m_mapSize, conductor.hack.m_visibleLandmarks_size, &responseMaps );\n\n auto start = std::chrono::high_resolution_clock::now();\n calculateMaps(\n conductor.hack.m_visibleLandmarks_size,\n conductor.hack.m_mapSize,\n alignedImage,\n shape,\n m_classifiers,\n &responseMaps\n );\n auto end = std::chrono::high_resolution_clock::now();\n elapsed_time = microseconds(end - start); \n \n \/\/ releasing the inputs\n freeMatChar(&alignedImage);\n freeMatFloat(&shape);\n freeClassifiers(&m_classifiers, conductor.hack.m_classifiers.size());\n\n \/\/ converting the outputs\n std::vector< cv::Mat_ > calculatedResults;\n for (int q=0; q nextResult;\n nextResult = convertMatFloatToCV( responseMaps[q] );\n calculatedResults.push_back(nextResult); \n }\n \n \/\/ testing the output\n for (int q=0; q 0.5 )\n {\n fail++;\n std::cout << \"cv::norm( conductor.hack.responseMaps[\" << q << \"] - calculatedResults[\" << q << \"] ) = \"\n << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl;\n \n }\n \n \/\/ PRINT(fail);\n int tolerance = 49 * conductor.id * 0.005 + 3;\n \/\/ PRINT(tolerance); \n assert(fail < tolerance);\n }\n \n \/\/ releasing the outputs\n freeResponseMaps( &responseMaps, conductor.hack.m_visibleLandmarks_size );\n\n }\n \/\/ here comes the test\n \/\/ PRINT(cv::norm( ));\n }\n \n std::cout << \"total elapsed time = \" << elapsed_time \/ 1000000. << \" s.\" << std::endl; \n \/\/conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n \n return EXIT_SUCCESS;\n}\n\n\n\n\/\/ LuM end of file\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/sync\/engine\/post_commit_message_command.h\"\n\n#include \n\n#include \"chrome\/browser\/sync\/engine\/syncer_proto_util.h\"\n#include \"chrome\/browser\/sync\/engine\/syncproto.h\"\n#include \"chrome\/browser\/sync\/sessions\/sync_session.h\"\n#include \"chrome\/browser\/sync\/syncable\/directory_manager.h\"\n#include \"chrome\/browser\/sync\/util\/sync_types.h\"\n\nusing std::vector;\n\nnamespace browser_sync {\n\nPostCommitMessageCommand::PostCommitMessageCommand() {}\nPostCommitMessageCommand::~PostCommitMessageCommand() {}\n\nvoid PostCommitMessageCommand::ExecuteImpl(sessions::SyncSession* session) {\n if (session->status_controller()->commit_ids().empty())\n return; \/\/ Nothing to commit.\n ClientToServerResponse response;\n syncable::ScopedDirLookup dir(session->context()->directory_manager(),\n session->context()->account_name());\n if (!dir.good())\n return;\n sessions::StatusController* status = session->status_controller();\n if (!SyncerProtoUtil::PostClientToServerMessage(\n status->mutable_commit_message(), &response, session)) {\n \/\/ None of our changes got through, let's clear sync flags and wait for\n \/\/ another list update.\n status->increment_num_consecutive_problem_commits();\n status->increment_num_consecutive_errors();\n syncable::WriteTransaction trans(dir, syncable::SYNCER, __FILE__, __LINE__);\n \/\/ TODO(sync): why set this flag, it seems like a bad side-effect?\n const vector& commit_ids = status->commit_ids();\n for (size_t i = 0; i < commit_ids.size(); i++) {\n syncable::MutableEntry entry(&trans, syncable::GET_BY_ID, commit_ids[i]);\n entry.Put(syncable::SYNCING, false);\n }\n return;\n } else {\n status->set_items_committed(true);\n }\n status->mutable_commit_response()->CopyFrom(response);\n}\n\n} \/\/ namespace browser_sync\nRemove a TODO in post_commit_command.cc. Clarify what's going on.\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/sync\/engine\/post_commit_message_command.h\"\n\n#include \n\n#include \"chrome\/browser\/sync\/engine\/syncer_proto_util.h\"\n#include \"chrome\/browser\/sync\/engine\/syncproto.h\"\n#include \"chrome\/browser\/sync\/sessions\/sync_session.h\"\n#include \"chrome\/browser\/sync\/syncable\/directory_manager.h\"\n#include \"chrome\/browser\/sync\/util\/sync_types.h\"\n\nusing std::vector;\n\nnamespace browser_sync {\n\nPostCommitMessageCommand::PostCommitMessageCommand() {}\nPostCommitMessageCommand::~PostCommitMessageCommand() {}\n\nvoid PostCommitMessageCommand::ExecuteImpl(sessions::SyncSession* session) {\n if (session->status_controller()->commit_ids().empty())\n return; \/\/ Nothing to commit.\n ClientToServerResponse response;\n syncable::ScopedDirLookup dir(session->context()->directory_manager(),\n session->context()->account_name());\n if (!dir.good())\n return;\n sessions::StatusController* status = session->status_controller();\n if (!SyncerProtoUtil::PostClientToServerMessage(\n status->mutable_commit_message(), &response, session)) {\n \/\/ None of our changes got through. Clear the SYNCING bit which was\n \/\/ set to true during BuildCommitCommand, and which may still be true.\n \/\/ Not to be confused with IS_UNSYNCED. This bit is used to detect local\n \/\/ changes to items that happen during the server Commit operation.\n status->increment_num_consecutive_problem_commits();\n status->increment_num_consecutive_errors();\n syncable::WriteTransaction trans(dir, syncable::SYNCER, __FILE__, __LINE__);\n const vector& commit_ids = status->commit_ids();\n for (size_t i = 0; i < commit_ids.size(); i++) {\n syncable::MutableEntry entry(&trans, syncable::GET_BY_ID, commit_ids[i]);\n entry.Put(syncable::SYNCING, false);\n }\n return;\n } else {\n status->set_items_committed(true);\n }\n status->mutable_commit_response()->CopyFrom(response);\n}\n\n} \/\/ namespace browser_sync\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_FEATURE_HPP\n#define MAPNIK_FEATURE_HPP\n\n\/\/ mapnik\n#include \n#include \n#include \n\n\/\/ boost\n#include \n#if BOOST_VERSION >= 104000\n#include \n#else\n#include \n#endif\n#include \n#include \n#include \n\n\/\/ stl\n#include \n\nnamespace mapnik {\n\n\ntypedef boost::shared_ptr raster_ptr; \ntypedef std::map map_type;\ntypedef boost::associative_property_map base_type;\n\nclass feature_impl;\n\nclass context : private boost::noncopyable, \n public base_type\n\n{\n friend class feature_impl; \npublic:\n\n context()\n : base_type(mapping_) {}\n \n void insert(std::string const& name,int index)\n {\n mapping_.insert(std::make_pair(name,index));\n }\n \nprivate:\n map_type mapping_;\n};\n\ntypedef boost::shared_ptr context_ptr;\n\nclass feature_impl : private boost::noncopyable\n{\npublic:\n typedef mapnik::value value_type; \n typedef std::vector cont_type;\n \n feature_impl(context_ptr const& ctx, int id) \n : id_(id),\n ctx_(ctx),\n data_(ctx_->mapping_.size())\n {}\n \n inline int id() const { return id_;}\n void set_id(int id) { id_ = id;}\n template \n void set(std::string const& key, T const& val)\n {\n map_type::const_iterator itr = ctx_->mapping_.find(key);\n if (itr != ctx_->mapping_.end())\n {\n data_[itr->second] = value(val);\n }\n } \n \n value_type const& get(std::string const& key) const\n {\n map_type::const_iterator itr = ctx_->mapping_.find(key);\n if (itr != ctx_->mapping_.end())\n {\n return data_[itr->second];\n }\n static const value_type default_value;\n return default_value;\n }\n\n boost::ptr_vector & paths() \n {\n return geom_cont_;\n }\n \n void add_geometry(geometry_type * geom)\n {\n geom_cont_.push_back(geom);\n }\n \n unsigned num_geometries() const\n {\n return geom_cont_.size();\n }\n \n geometry_type const& get_geometry(unsigned index) const\n {\n return geom_cont_[index];\n }\n \n geometry_type& get_geometry(unsigned index)\n {\n return geom_cont_[index];\n }\n \n const raster_ptr& get_raster() const\n {\n return raster_;\n }\n\n \n void set_raster(raster_ptr const& raster)\n {\n raster_ = raster;\n }\n\n std::string to_string() const\n { \n std::stringstream ss;\n ss << \"Feature (\" << std::endl;\n map_type::const_iterator itr = ctx_->mapping_.begin();\n map_type::const_iterator end = ctx_->mapping_.end();\n for ( ;itr!=end; ++itr)\n {\n ss << \" \" << itr->first << \":\" << data_[itr->second] << std::endl;\n }\n ss << \")\" << std::endl;\n return ss.str();\n }\n\nprivate:\n context_ptr ctx_;\n int id_;\n boost::ptr_vector geom_cont_;\n raster_ptr raster_;\n \n cont_type data_;\n};\n\n \ninline std::ostream& operator<< (std::ostream & out,feature_impl const& f)\n{\n out << f.to_string();\n return out;\n}\n\ntypedef feature_impl Feature;\n\n}\n\n#endif \/\/ MAPNIK_FEATURE_HPP\nmore friendly interface\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_FEATURE_HPP\n#define MAPNIK_FEATURE_HPP\n\n\/\/ mapnik\n#include \n#include \n#include \n\n\/\/ boost\n#include \n#if BOOST_VERSION >= 104000\n#include \n#else\n#include \n#endif\n#include \n#include \n#include \n\n\/\/ stl\n#include \n\nnamespace mapnik {\n\n\ntypedef boost::shared_ptr raster_ptr; \ntypedef std::map map_type;\ntypedef boost::associative_property_map base_type;\n\nclass feature_impl;\n\nclass context : private boost::noncopyable, \n public base_type\n\n{\n friend class feature_impl; \npublic:\n\n context()\n : base_type(mapping_) {}\n \n void push(std::string const& name)\n {\n mapping_.insert(std::make_pair(name,mapping_.size()));\n }\n \nprivate:\n map_type mapping_;\n};\n\ntypedef boost::shared_ptr context_ptr;\n\nclass feature_impl : private boost::noncopyable\n{\npublic:\n typedef mapnik::value value_type; \n typedef std::vector cont_type;\n \n feature_impl(context_ptr const& ctx, int id) \n : id_(id),\n ctx_(ctx),\n data_(ctx_->mapping_.size())\n {}\n \n inline int id() const { return id_;}\n void set_id(int id) { id_ = id;}\n template \n void set(std::string const& key, T const& val)\n {\n map_type::const_iterator itr = ctx_->mapping_.find(key);\n if (itr != ctx_->mapping_.end())\n {\n data_[itr->second] = value(val);\n }\n } \n \n value_type const& get(std::string const& key) const\n {\n map_type::const_iterator itr = ctx_->mapping_.find(key);\n if (itr != ctx_->mapping_.end())\n {\n return data_[itr->second];\n }\n static const value_type default_value;\n return default_value;\n }\n\n boost::ptr_vector & paths() \n {\n return geom_cont_;\n }\n \n void add_geometry(geometry_type * geom)\n {\n geom_cont_.push_back(geom);\n }\n \n unsigned num_geometries() const\n {\n return geom_cont_.size();\n }\n \n geometry_type const& get_geometry(unsigned index) const\n {\n return geom_cont_[index];\n }\n \n geometry_type& get_geometry(unsigned index)\n {\n return geom_cont_[index];\n }\n \n const raster_ptr& get_raster() const\n {\n return raster_;\n }\n\n \n void set_raster(raster_ptr const& raster)\n {\n raster_ = raster;\n }\n\n std::string to_string() const\n { \n std::stringstream ss;\n ss << \"Feature (\" << std::endl;\n map_type::const_iterator itr = ctx_->mapping_.begin();\n map_type::const_iterator end = ctx_->mapping_.end();\n for ( ;itr!=end; ++itr)\n {\n ss << \" \" << itr->first << \":\" << data_[itr->second] << std::endl;\n }\n ss << \")\" << std::endl;\n return ss.str();\n }\n\nprivate:\n context_ptr ctx_;\n int id_;\n boost::ptr_vector geom_cont_;\n raster_ptr raster_;\n \n cont_type data_;\n};\n\n \ninline std::ostream& operator<< (std::ostream & out,feature_impl const& f)\n{\n out << f.to_string();\n return out;\n}\n\ntypedef feature_impl Feature;\n\n}\n\n#endif \/\/ MAPNIK_FEATURE_HPP\n<|endoftext|>"} {"text":"\/*************************************************************************\/\n\/* editor_run_native.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"editor_run_native.h\"\n\n#include \"editor_export.h\"\n#include \"editor_node.h\"\n#include \"editor_scale.h\"\n\nvoid EditorRunNative::_notification(int p_what) {\n\n\tif (p_what == NOTIFICATION_ENTER_TREE) {\n\n\t\tfor (int i = 0; i < EditorExport::get_singleton()->get_export_platform_count(); i++) {\n\n\t\t\tRef eep = EditorExport::get_singleton()->get_export_platform(i);\n\t\t\tif (eep.is_null())\n\t\t\t\tcontinue;\n\t\t\tRef icon = eep->get_run_icon();\n\t\t\tif (!icon.is_null()) {\n\t\t\t\tRef im = icon->get_data();\n\t\t\t\tim = im->duplicate();\n\t\t\t\tim->clear_mipmaps();\n\t\t\t\tif (!im->empty()) {\n\n\t\t\t\t\tim->resize(16 * EDSCALE, 16 * EDSCALE);\n\t\t\t\t\tRef small_icon;\n\t\t\t\t\tsmall_icon.instance();\n\t\t\t\t\tsmall_icon->create_from_image(im, 0);\n\t\t\t\t\tMenuButton *mb = memnew(MenuButton);\n\t\t\t\t\tmb->get_popup()->connect(\"id_pressed\", this, \"_run_native\", varray(i));\n\t\t\t\t\t\/\/mb->connect(\"pressed\", this, \"_run_native\", varray(-1, i));\n\t\t\t\t\tmb->set_icon(small_icon);\n\t\t\t\t\tadd_child(mb);\n\t\t\t\t\tmenus[i] = mb;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (p_what == NOTIFICATION_PROCESS) {\n\n\t\tbool changed = EditorExport::get_singleton()->poll_export_platforms() || first;\n\n\t\tif (changed) {\n\n\t\t\tfor (Map::Element *E = menus.front(); E; E = E->next()) {\n\n\t\t\t\tRef eep = EditorExport::get_singleton()->get_export_platform(E->key());\n\t\t\t\tMenuButton *mb = E->get();\n\t\t\t\tint dc = eep->get_device_count();\n\n\t\t\t\tif (dc == 0) {\n\t\t\t\t\tmb->hide();\n\t\t\t\t} else {\n\t\t\t\t\tmb->get_popup()->clear();\n\t\t\t\t\tmb->show();\n\t\t\t\t\tmb->set_tooltip(TTR(\"Select device from the list\"));\n\t\t\t\t\tfor (int i = 0; i < dc; i++) {\n\t\t\t\t\t\tmb->get_popup()->add_icon_item(get_icon(\"Play\", \"EditorIcons\"), eep->get_device_name(i));\n\t\t\t\t\t\tmb->get_popup()->set_item_tooltip(mb->get_popup()->get_item_count() - 1, eep->get_device_info(i).strip_edges());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfirst = false;\n\t\t}\n\t}\n}\n\nvoid EditorRunNative::_run_native(int p_idx, int p_platform) {\n\n\tRef eep = EditorExport::get_singleton()->get_export_platform(p_platform);\n\tERR_FAIL_COND(eep.is_null());\n\t\/*if (p_idx == -1) {\n\t\tif (eep->get_device_count() == 1) {\n\t\t\tmenus[p_platform]->get_popup()->hide();\n\t\t\tp_idx = 0;\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\t}*\/\n\n\tRef preset;\n\n\tfor (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {\n\n\t\tRef ep = EditorExport::get_singleton()->get_export_preset(i);\n\t\tif (ep->is_runnable() && ep->get_platform() == eep) {\n\t\t\tpreset = ep;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (preset.is_null()) {\n\t\tEditorNode::get_singleton()->show_warning(TTR(\"No runnable export preset found for this platform.\\nPlease add a runnable preset in the export menu.\"));\n\t\treturn;\n\t}\n\n\temit_signal(\"native_run\");\n\n\tint flags = 0;\n\tif (deploy_debug_remote)\n\t\tflags |= EditorExportPlatform::DEBUG_FLAG_REMOTE_DEBUG;\n\tif (deploy_dumb)\n\t\tflags |= EditorExportPlatform::DEBUG_FLAG_DUMB_CLIENT;\n\tif (debug_collisions)\n\t\tflags |= EditorExportPlatform::DEBUG_FLAG_VIEW_COLLISONS;\n\tif (debug_navigation)\n\t\tflags |= EditorExportPlatform::DEBUG_FLAG_VIEW_NAVIGATION;\n\n\teep->run(preset, p_idx, flags);\n}\n\nvoid EditorRunNative::_bind_methods() {\n\n\tClassDB::bind_method(\"_run_native\", &EditorRunNative::_run_native);\n\n\tADD_SIGNAL(MethodInfo(\"native_run\"));\n}\n\nvoid EditorRunNative::set_deploy_dumb(bool p_enabled) {\n\n\tdeploy_dumb = p_enabled;\n}\n\nbool EditorRunNative::is_deploy_dumb_enabled() const {\n\n\treturn deploy_dumb;\n}\n\nvoid EditorRunNative::set_deploy_debug_remote(bool p_enabled) {\n\n\tdeploy_debug_remote = p_enabled;\n}\n\nbool EditorRunNative::is_deploy_debug_remote_enabled() const {\n\n\treturn deploy_debug_remote;\n}\n\nvoid EditorRunNative::set_debug_collisions(bool p_debug) {\n\n\tdebug_collisions = p_debug;\n}\n\nbool EditorRunNative::get_debug_collisions() const {\n\n\treturn debug_collisions;\n}\n\nvoid EditorRunNative::set_debug_navigation(bool p_debug) {\n\n\tdebug_navigation = p_debug;\n}\n\nbool EditorRunNative::get_debug_navigation() const {\n\n\treturn debug_navigation;\n}\n\nEditorRunNative::EditorRunNative() {\n\tset_process(true);\n\tfirst = true;\n\tdeploy_dumb = false;\n\tdeploy_debug_remote = false;\n\tdebug_collisions = false;\n\tdebug_navigation = false;\n}\nRequire only one click to deploy to Android if one device is connected\/*************************************************************************\/\n\/* editor_run_native.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"editor_run_native.h\"\n\n#include \"editor_export.h\"\n#include \"editor_node.h\"\n#include \"editor_scale.h\"\n\nvoid EditorRunNative::_notification(int p_what) {\n\n\tif (p_what == NOTIFICATION_ENTER_TREE) {\n\n\t\tfor (int i = 0; i < EditorExport::get_singleton()->get_export_platform_count(); i++) {\n\n\t\t\tRef eep = EditorExport::get_singleton()->get_export_platform(i);\n\t\t\tif (eep.is_null())\n\t\t\t\tcontinue;\n\t\t\tRef icon = eep->get_run_icon();\n\t\t\tif (!icon.is_null()) {\n\t\t\t\tRef im = icon->get_data();\n\t\t\t\tim = im->duplicate();\n\t\t\t\tim->clear_mipmaps();\n\t\t\t\tif (!im->empty()) {\n\n\t\t\t\t\tim->resize(16 * EDSCALE, 16 * EDSCALE);\n\t\t\t\t\tRef small_icon;\n\t\t\t\t\tsmall_icon.instance();\n\t\t\t\t\tsmall_icon->create_from_image(im, 0);\n\t\t\t\t\tMenuButton *mb = memnew(MenuButton);\n\t\t\t\t\tmb->get_popup()->connect(\"id_pressed\", this, \"_run_native\", varray(i));\n\t\t\t\t\tmb->connect(\"pressed\", this, \"_run_native\", varray(-1, i));\n\t\t\t\t\tmb->set_icon(small_icon);\n\t\t\t\t\tadd_child(mb);\n\t\t\t\t\tmenus[i] = mb;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (p_what == NOTIFICATION_PROCESS) {\n\n\t\tbool changed = EditorExport::get_singleton()->poll_export_platforms() || first;\n\n\t\tif (changed) {\n\n\t\t\tfor (Map::Element *E = menus.front(); E; E = E->next()) {\n\n\t\t\t\tRef eep = EditorExport::get_singleton()->get_export_platform(E->key());\n\t\t\t\tMenuButton *mb = E->get();\n\t\t\t\tint dc = eep->get_device_count();\n\n\t\t\t\tif (dc == 0) {\n\t\t\t\t\tmb->hide();\n\t\t\t\t} else {\n\t\t\t\t\tmb->get_popup()->clear();\n\t\t\t\t\tmb->show();\n\t\t\t\t\tif (dc == 1) {\n\t\t\t\t\t\tmb->set_tooltip(eep->get_device_name(0) + \"\\n\\n\" + eep->get_device_info(0).strip_edges());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmb->set_tooltip(\"Select device from the list\");\n\t\t\t\t\t\tfor (int i = 0; i < dc; i++) {\n\t\t\t\t\t\t\tmb->get_popup()->add_icon_item(get_icon(\"Play\", \"EditorIcons\"), eep->get_device_name(i));\n\t\t\t\t\t\t\tmb->get_popup()->set_item_tooltip(mb->get_popup()->get_item_count() - 1, eep->get_device_info(i).strip_edges());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfirst = false;\n\t\t}\n\t}\n}\n\nvoid EditorRunNative::_run_native(int p_idx, int p_platform) {\n\n\tRef eep = EditorExport::get_singleton()->get_export_platform(p_platform);\n\tERR_FAIL_COND(eep.is_null());\n\n\tif (p_idx == -1) {\n\t\tif (eep->get_device_count() == 1) {\n\t\t\tmenus[p_platform]->get_popup()->hide();\n\t\t\tp_idx = 0;\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tRef preset;\n\n\tfor (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {\n\n\t\tRef ep = EditorExport::get_singleton()->get_export_preset(i);\n\t\tif (ep->is_runnable() && ep->get_platform() == eep) {\n\t\t\tpreset = ep;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (preset.is_null()) {\n\t\tEditorNode::get_singleton()->show_warning(TTR(\"No runnable export preset found for this platform.\\nPlease add a runnable preset in the export menu.\"));\n\t\treturn;\n\t}\n\n\temit_signal(\"native_run\");\n\n\tint flags = 0;\n\tif (deploy_debug_remote)\n\t\tflags |= EditorExportPlatform::DEBUG_FLAG_REMOTE_DEBUG;\n\tif (deploy_dumb)\n\t\tflags |= EditorExportPlatform::DEBUG_FLAG_DUMB_CLIENT;\n\tif (debug_collisions)\n\t\tflags |= EditorExportPlatform::DEBUG_FLAG_VIEW_COLLISONS;\n\tif (debug_navigation)\n\t\tflags |= EditorExportPlatform::DEBUG_FLAG_VIEW_NAVIGATION;\n\n\teep->run(preset, p_idx, flags);\n}\n\nvoid EditorRunNative::_bind_methods() {\n\n\tClassDB::bind_method(\"_run_native\", &EditorRunNative::_run_native);\n\n\tADD_SIGNAL(MethodInfo(\"native_run\"));\n}\n\nvoid EditorRunNative::set_deploy_dumb(bool p_enabled) {\n\n\tdeploy_dumb = p_enabled;\n}\n\nbool EditorRunNative::is_deploy_dumb_enabled() const {\n\n\treturn deploy_dumb;\n}\n\nvoid EditorRunNative::set_deploy_debug_remote(bool p_enabled) {\n\n\tdeploy_debug_remote = p_enabled;\n}\n\nbool EditorRunNative::is_deploy_debug_remote_enabled() const {\n\n\treturn deploy_debug_remote;\n}\n\nvoid EditorRunNative::set_debug_collisions(bool p_debug) {\n\n\tdebug_collisions = p_debug;\n}\n\nbool EditorRunNative::get_debug_collisions() const {\n\n\treturn debug_collisions;\n}\n\nvoid EditorRunNative::set_debug_navigation(bool p_debug) {\n\n\tdebug_navigation = p_debug;\n}\n\nbool EditorRunNative::get_debug_navigation() const {\n\n\treturn debug_navigation;\n}\n\nEditorRunNative::EditorRunNative() {\n\tset_process(true);\n\tfirst = true;\n\tdeploy_dumb = false;\n\tdeploy_debug_remote = false;\n\tdebug_collisions = false;\n\tdebug_navigation = false;\n}\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n#include \n#include \"mtao\/iterator\/zip.hpp\"\n\n\nnamespace mtao {\n template \n struct ReIndexer {\n IndexType add_index(IndexType idx) {\n if(auto it = m_forward.find(idx); it != m_forward.end()) {\n return it->second;\n } else {\n IndexType new_idx = m_forward.size();\n return m_forward[idx] = new_idx;\n }\n }\n\n IndexType operator()(IndexType idx) {\n return add_index(idx);\n }\n IndexType get(IndexType idx) const {\n return m_forward[idx]; \n }\n bool has_index(IndexType idx) const {\n return m_forward.find(idx) != m_forward.end();\n }\n std::vector inverse() const {\n std::vector ret(m_forward.size());\n for(auto&& [k,v]: m_forward) {\n ret[v] = k;\n }\n return ret;\n }\n auto&& map() const { return m_forward; }\n size_t size() const { return m_forward.size(); }\n private:\n std::map m_forward;\n };\n template \n struct StackedReIndexer {\n using RET = ReIndexer;\n template \n void add_index(IndexType idx) {\n indexers[D].add_index(idx);\n for(size_t i = D; i < Size; ++i) {\n offsets[i+1] = offsets[i] + indexers[i].size();\n }\n }\n size_t size() const {\n return offsets[Size];\n }\n template \n bool has_index(IndexType idx) const {\n return indexers[D].has_index(idx);\n }\n std::vector inverse() const {\n std::vector ret(size());\n for(auto&& [i,o]: mtao::iterator::zip(indexers,offsets)) {\n for(auto&& [k,v]: i.map()) {\n ret[v + o] = k;\n }\n }\n return ret;\n }\n std::array indexers;\n std::array offsets = {};\n\n };\n}\nupdated reindexer#pragma once\n#include \n#include \n#include \n#include \"mtao\/iterator\/zip.hpp\"\n\n\nnamespace mtao {\n template \n struct ReIndexer {\n IndexType add_index(IndexType idx) {\n if(auto it = m_forward.find(idx); it != m_forward.end()) {\n return it->second;\n } else {\n IndexType new_idx = m_forward.size();\n return m_forward[idx] = new_idx;\n }\n }\n IndexType set(IndexType idx, IndexType target) {\n return m_forward[idx] = target;\n }\n\n IndexType operator()(IndexType idx) {\n return add_index(idx);\n }\n IndexType get(IndexType idx) const {\n return m_forward[idx]; \n }\n bool has_index(IndexType idx) const {\n return m_forward.find(idx) != m_forward.end();\n }\n std::vector inverse() const {\n std::vector ret(m_forward.size());\n for(auto&& [k,v]: m_forward) {\n ret[v] = k;\n }\n return ret;\n }\n auto&& map() const { return m_forward; }\n size_t size() const { return m_forward.size(); }\n private:\n std::map m_forward;\n };\n template \n struct StackedReIndexer {\n using RET = ReIndexer;\n template \n void add_index(IndexType idx) {\n indexers[D].add_index(idx);\n update_offsets(D);\n }\n template \n IndexType set(IndexType idx, IndexType target) {\n indexers[D].set(idx,target);\n update_offsets(D);\n }\n void add_index(IndexType idx, size_t D) {\n indexers[D].add_index(idx);\n update_offsets(D);\n }\n IndexType set(IndexType idx, IndexType target, size_t D) {\n indexers[D].set(idx,target);\n update_offsets(D);\n }\n void update_offsets(size_t D) {\n for(size_t i = D; i < Size; ++i) {\n offsets[i+1] = offsets[i] + indexers[i].size();\n }\n }\n size_t size() const {\n return offsets[Size];\n }\n template \n bool has_index(IndexType idx) const {\n return indexers[D].has_index(idx);\n }\n std::vector inverse() const {\n std::vector ret(size());\n for(auto&& [i,o]: mtao::iterator::zip(indexers,offsets)) {\n for(auto&& [k,v]: i.map()) {\n ret[v + o] = k;\n }\n }\n return ret;\n }\n std::array indexers;\n std::array offsets = {};\n\n };\n}\n<|endoftext|>"} {"text":"\/\/----------------------------------------------------------------------------\n\/\/\/ \\file stream_io.hpp\n\/\/\/ \\author Serge Aleynikov\n\/\/----------------------------------------------------------------------------\n\/\/\/ Defines functions for stream input\/output\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (C) 2016 Serge Aleynikov \n\/\/ Created: 2016-02-26\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is a part of utxx open-source project.\n\nCopyright (C) 2016 Serge Aleynikov \n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n#pragma once\n\n#include \n#include \n#include \n\nnamespace utxx {\n\n\/\/------------------------------------------------------------------------------\n\/\/\/ Read \\a a_cnt values from the input stream.\n\/\/\/ @param in input stream.\n\/\/\/ @param a_output array of \\a a_cnt double values.\n\/\/\/ @param a_fields array of \\a a_cnt field positions (ascending order). If this\n\/\/\/ value is NULL, the values are read from the input stream\n\/\/\/ in consequitive order disregarding field positions.\n\/\/\/ @param a_cnt count of values to read.\n\/\/\/ @param a_convert lambda used to convert a string value to type \\a T:\n\/\/\/ const char* (const char* begin, const char* end, T& outout);<\/code>\n\/\/\/ The function must return NULL if conversion is unsuccessful, or a pointer\n\/\/\/ past last successfully parsed character otherwise.\n\/\/\/ @return true if successfully read \\a a_cnt values.\n\/\/------------------------------------------------------------------------------\ntemplate \nbool read_values(std::istream& in, T* a_output, int* a_fields, int a_cnt,\n const Convert& a_convert)\n{\n basic_stack_string str;\n\n auto& line = str.container();\n\n if (a_fields == nullptr) {\n for (int i=0; i < a_cnt; ++i) {\n if (in.eof()) return false;\n in >> *a_output++;\n }\n }\n else if (!std::getline(in, line))\n return false;\n else {\n const char* p = &*line.begin();\n const char* e = &*line.end();\n\n int fld = 0;\n\n auto ws = [](char c) { return c == ' ' || c == '\\t'; };\n auto skip_ws = [&p, e, &ws]() { while (ws(*p) && p != e) p++; };\n\n for (int i=0; i < a_cnt; ++i, ++a_fields, ++a_output) {\n while (p != e) {\n skip_ws();\n if (++fld == *a_fields)\n break;\n while (!ws(*p) && p != e) p++;\n }\n\n if (fld != *a_fields)\n return false;\n\n p = a_convert(p, e, *a_output);\n\n if (!p)\n return false;\n }\n }\n\n return true;\n}\n\n} \/\/ namespace utxxRequire count to be greater than 0\/\/----------------------------------------------------------------------------\n\/\/\/ \\file stream_io.hpp\n\/\/\/ \\author Serge Aleynikov\n\/\/----------------------------------------------------------------------------\n\/\/\/ Defines functions for stream input\/output\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (C) 2016 Serge Aleynikov \n\/\/ Created: 2016-02-26\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is a part of utxx open-source project.\n\nCopyright (C) 2016 Serge Aleynikov \n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n#pragma once\n\n#include \n#include \n#include \n\nnamespace utxx {\n\n\/\/------------------------------------------------------------------------------\n\/\/\/ Read \\a a_cnt values from the input stream.\n\/\/\/ @param in input stream.\n\/\/\/ @param a_output array of \\a a_cnt double values.\n\/\/\/ @param a_fields array of \\a a_cnt field positions (ascending order). If this\n\/\/\/ value is NULL, the values are read from the input stream\n\/\/\/ in consequitive order disregarding field positions.\n\/\/\/ @param a_cnt count of values to read (must be > 0).\n\/\/\/ @param a_convert lambda used to convert a string value to type \\a T:\n\/\/\/ const char* (const char* begin, const char* end, T& outout);<\/code>\n\/\/\/ The function must return NULL if conversion is unsuccessful, or a pointer\n\/\/\/ past last successfully parsed character otherwise.\n\/\/\/ @return true if successfully read \\a a_cnt values.\n\/\/------------------------------------------------------------------------------\ntemplate \nbool read_values(std::istream& in, T* a_output, int* a_fields, int a_cnt,\n const Convert& a_convert)\n{\n assert(a_cnt);\n\n basic_stack_string str;\n\n auto& line = str.container();\n\n if (a_fields == nullptr) {\n for (int i=0; i < a_cnt; ++i) {\n if (in.eof()) return false;\n in >> *a_output++;\n }\n }\n else if (!std::getline(in, line))\n return false;\n else {\n const char* p = &*line.begin();\n const char* e = &*line.end();\n\n int fld = 0;\n\n auto ws = [](char c) { return c == ' ' || c == '\\t'; };\n auto skip_ws = [&p, e, &ws]() { while (ws(*p) && p != e) p++; };\n\n for (int i=0; i < a_cnt; ++i, ++a_fields, ++a_output) {\n while (p != e) {\n skip_ws();\n if (++fld == *a_fields)\n break;\n while (!ws(*p) && p != e) p++;\n }\n\n if (fld != *a_fields)\n return false;\n\n p = a_convert(p, e, *a_output);\n\n if (!p)\n return false;\n }\n }\n\n return true;\n}\n\n} \/\/ namespace utxx<|endoftext|>"} {"text":"Fix up tangents in MeshAssimp to help with #528.<|endoftext|>"} {"text":"\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see .\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE test_navimake\n#include \n#include \"boost\/date_time\/posix_time\/posix_time_types.hpp\"\n#include \"type\/pt_data.h\"\n#include \"type\/type.h\"\n#include \"type\/response.pb.h\"\n#include \"ed\/build_helper.h\"\n#include \"type\/pb_converter.h\"\n\nusing namespace navitia::type;\nBOOST_AUTO_TEST_CASE(test_pt_displayinfo_destination) {\n ed::builder b(\"20120614\");\n b.vj(\"A\")(\"stop1\", 8000, 8050);\n b.vj(\"A\")(\"stop1\", 8000, 8050);\n b.vj(\"V\")(\"stop2\", 8000, 8050);\n b.finish();\n b.data->build_uri();\n b.data->pt_data->index();\n b.data->build_raptor();\n\n auto pt_display_info = new pbnavitia::PtDisplayInfo();\n const Route* r = b.data->pt_data->routes_map[\"A:0\"];\n boost::gregorian::date d1(2014,06,14);\n boost::posix_time::ptime t1(d1, boost::posix_time::seconds(10)); \/\/10 sec after midnight\n boost::posix_time::ptime t2(d1, boost::posix_time::hours(10)); \/\/10 hours after midnight\n boost::posix_time::time_period period(t1, t2);\n navitia::fill_pb_object(r, *b.data,\n pt_display_info, 0,\n {}, period, nullptr);\n BOOST_CHECK_EQUAL(pt_display_info->direction(), \"stop1\");\n pt_display_info->Clear();\n\n auto sp = new StopPoint();\n sp->name = \"bob\";\n navitia::fill_pb_object(r, *b.data,\n pt_display_info, 0,\n {}, period, sp);\n BOOST_CHECK_EQUAL(pt_display_info->direction(), \"bob\");\n}\nkraken: add a test on fill_pb_object for route without vj\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see .\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE test_navimake\n#include \n#include \"boost\/date_time\/posix_time\/posix_time_types.hpp\"\n#include \"type\/pt_data.h\"\n#include \"type\/type.h\"\n#include \"type\/response.pb.h\"\n#include \"ed\/build_helper.h\"\n#include \"type\/pb_converter.h\"\n\nusing namespace navitia::type;\nBOOST_AUTO_TEST_CASE(test_pt_displayinfo_destination) {\n ed::builder b(\"20120614\");\n b.vj(\"A\")(\"stop1\", 8000, 8050);\n b.vj(\"A\")(\"stop1\", 8000, 8050);\n b.vj(\"V\")(\"stop2\", 8000, 8050);\n b.finish();\n b.data->build_uri();\n b.data->pt_data->index();\n b.data->build_raptor();\n\n auto pt_display_info = new pbnavitia::PtDisplayInfo();\n const Route* r = b.data->pt_data->routes_map[\"A:0\"];\n boost::gregorian::date d1(2014,06,14);\n boost::posix_time::ptime t1(d1, boost::posix_time::seconds(10)); \/\/10 sec after midnight\n boost::posix_time::ptime t2(d1, boost::posix_time::hours(10)); \/\/10 hours after midnight\n boost::posix_time::time_period period(t1, t2);\n navitia::fill_pb_object(r, *b.data,\n pt_display_info, 0,\n {}, period, nullptr);\n BOOST_CHECK_EQUAL(pt_display_info->direction(), \"stop1\");\n pt_display_info->Clear();\n\n auto sp = new StopPoint();\n sp->name = \"bob\";\n navitia::fill_pb_object(r, *b.data,\n pt_display_info, 0,\n {}, period, sp);\n BOOST_CHECK_EQUAL(pt_display_info->direction(), \"bob\");\n}\n\nBOOST_AUTO_TEST_CASE(test_pt_displayinfo_destination_without_vj) {\n ed::builder b(\"20120614\");\n auto* route = new Route();\n b.data->pt_data->routes.push_back(route);\n b.finish();\n b.data->build_uri();\n b.data->pt_data->index();\n b.data->build_raptor();\n\n auto pt_display_info = new pbnavitia::PtDisplayInfo();\n boost::gregorian::date d1(2014,06,14);\n boost::posix_time::ptime t1(d1, boost::posix_time::seconds(10)); \/\/10 sec after midnight\n boost::posix_time::ptime t2(d1, boost::posix_time::hours(10)); \/\/10 hours after midnight\n boost::posix_time::time_period period(t1, t2);\n navitia::fill_pb_object(route, *b.data,\n pt_display_info, 0,\n {}, period, nullptr);\n BOOST_CHECK_EQUAL(pt_display_info->direction(), \"\");\n pt_display_info->Clear();\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"components\/copresence\/handlers\/audio\/audio_directive_handler.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/time\/time.h\"\n#include \"components\/copresence\/mediums\/audio\/audio_player.h\"\n#include \"components\/copresence\/mediums\/audio\/audio_recorder.h\"\n#include \"components\/copresence\/proto\/data.pb.h\"\n#include \"media\/base\/audio_bus.h\"\n\nnamespace {\n\n\/\/ UrlSafe is defined as:\n\/\/ '\/' represented by a '_' and '+' represented by a '-'\n\/\/ TODO(rkc): Move this processing to the whispernet wrapper.\nstd::string FromUrlSafe(std::string token) {\n base::ReplaceChars(token, \"-\", \"+\", &token);\n base::ReplaceChars(token, \"_\", \"\/\", &token);\n return token;\n}\n\nconst int kSampleExpiryTimeMs = 60 * 60 * 1000; \/\/ 60 minutes.\nconst int kMaxSamples = 10000;\n\n} \/\/ namespace\n\nnamespace copresence {\n\n\/\/ Public methods.\n\nAudioDirectiveHandler::AudioDirectiveHandler(\n const AudioRecorder::DecodeSamplesCallback& decode_cb,\n const AudioDirectiveHandler::EncodeTokenCallback& encode_cb)\n : player_audible_(NULL),\n player_inaudible_(NULL),\n recorder_(NULL),\n decode_cb_(decode_cb),\n encode_cb_(encode_cb),\n samples_cache_audible_(\n base::TimeDelta::FromMilliseconds(kSampleExpiryTimeMs),\n kMaxSamples),\n samples_cache_inaudible_(\n base::TimeDelta::FromMilliseconds(kSampleExpiryTimeMs),\n kMaxSamples) {\n}\n\nAudioDirectiveHandler::~AudioDirectiveHandler() {\n if (player_audible_)\n player_audible_->Finalize();\n if (player_inaudible_)\n player_inaudible_->Finalize();\n if (recorder_)\n recorder_->Finalize();\n}\n\nvoid AudioDirectiveHandler::Initialize() {\n player_audible_ = new AudioPlayer();\n player_audible_->Initialize();\n\n player_inaudible_ = new AudioPlayer();\n player_inaudible_->Initialize();\n\n recorder_ = new AudioRecorder(decode_cb_);\n recorder_->Initialize();\n}\n\nvoid AudioDirectiveHandler::AddInstruction(const TokenInstruction& instruction,\n const std::string& op_id,\n base::TimeDelta ttl) {\n switch (instruction.token_instruction_type()) {\n case TRANSMIT:\n DVLOG(2) << \"Audio Transmit Directive received. Token: \"\n << instruction.token_id()\n << \" with TTL=\" << ttl.InMilliseconds();\n switch (instruction.medium()) {\n case AUDIO_ULTRASOUND_PASSBAND:\n transmits_list_inaudible_.AddDirective(op_id, ttl);\n PlayToken(instruction.token_id(), false);\n break;\n case AUDIO_AUDIBLE_DTMF:\n transmits_list_audible_.AddDirective(op_id, ttl);\n PlayToken(instruction.token_id(), true);\n break;\n default:\n NOTREACHED();\n }\n break;\n case RECEIVE:\n DVLOG(2) << \"Audio Receive Directive received. TTL=\"\n << ttl.InMilliseconds();\n receives_list_.AddDirective(op_id, ttl);\n ProcessNextReceive();\n break;\n case UNKNOWN_TOKEN_INSTRUCTION_TYPE:\n default:\n LOG(WARNING) << \"Unknown Audio Transmit Directive received.\";\n }\n}\n\nvoid AudioDirectiveHandler::RemoveInstructions(const std::string& op_id) {\n transmits_list_audible_.RemoveDirective(op_id);\n transmits_list_inaudible_.RemoveDirective(op_id);\n receives_list_.RemoveDirective(op_id);\n\n ProcessNextTransmit();\n ProcessNextReceive();\n}\n\n\/\/ Private methods.\n\nvoid AudioDirectiveHandler::ProcessNextTransmit() {\n \/\/ If we have an active directive for audible or inaudible audio, ensure that\n \/\/ we are playing our respective token; if we do not have a directive, then\n \/\/ make sure we aren't playing. This is duplicate code, but for just two\n \/\/ elements, it has hard to make a case for processing a loop instead.\n\n scoped_ptr audible_transmit(\n transmits_list_audible_.GetActiveDirective());\n if (audible_transmit && !player_audible_->IsPlaying()) {\n DVLOG(3) << \"Playing audible for op_id: \" << audible_transmit->op_id;\n player_audible_->Play(\n samples_cache_audible_.GetValue(current_token_audible_));\n stop_audible_playback_timer_.Start(\n FROM_HERE,\n audible_transmit->end_time - base::Time::Now(),\n this,\n &AudioDirectiveHandler::ProcessNextTransmit);\n } else if (!audible_transmit && player_audible_->IsPlaying()) {\n DVLOG(3) << \"Stopping audible playback.\";\n current_token_audible_.clear();\n stop_audible_playback_timer_.Stop();\n player_audible_->Stop();\n }\n\n scoped_ptr inaudible_transmit(\n transmits_list_inaudible_.GetActiveDirective());\n if (inaudible_transmit && !player_inaudible_->IsPlaying()) {\n DVLOG(3) << \"Playing inaudible for op_id: \" << inaudible_transmit->op_id;\n player_inaudible_->Play(\n samples_cache_inaudible_.GetValue(current_token_inaudible_));\n stop_inaudible_playback_timer_.Start(\n FROM_HERE,\n inaudible_transmit->end_time - base::Time::Now(),\n this,\n &AudioDirectiveHandler::ProcessNextTransmit);\n } else if (!inaudible_transmit && player_inaudible_->IsPlaying()) {\n DVLOG(3) << \"Stopping inaudible playback.\";\n current_token_inaudible_.clear();\n stop_inaudible_playback_timer_.Stop();\n player_inaudible_->Stop();\n }\n}\n\nvoid AudioDirectiveHandler::ProcessNextReceive() {\n scoped_ptr receive(receives_list_.GetActiveDirective());\n\n if (receive && !recorder_->IsRecording()) {\n DVLOG(3) << \"Recording for op_id: \" << receive->op_id;\n recorder_->Record();\n stop_recording_timer_.Start(FROM_HERE,\n receive->end_time - base::Time::Now(),\n this,\n &AudioDirectiveHandler::ProcessNextReceive);\n } else if (!receive && recorder_->IsRecording()) {\n DVLOG(3) << \"Stopping Recording\";\n stop_recording_timer_.Stop();\n recorder_->Stop();\n }\n}\n\nvoid AudioDirectiveHandler::PlayToken(const std::string token, bool audible) {\n std::string valid_token = FromUrlSafe(token);\n\n \/\/ If the token has been encoded already, use the cached samples.\n if (audible && samples_cache_audible_.HasKey(valid_token)) {\n current_token_audible_ = token;\n ProcessNextTransmit();\n } else if (!audible && samples_cache_inaudible_.HasKey(valid_token)) {\n current_token_inaudible_ = token;\n ProcessNextTransmit();\n } else {\n \/\/ Otherwise, encode the token and then play it.\n encode_cb_.Run(valid_token,\n audible,\n base::Bind(&AudioDirectiveHandler::PlayEncodedToken,\n base::Unretained(this)));\n }\n}\n\nvoid AudioDirectiveHandler::PlayEncodedToken(\n const std::string& token,\n bool audible,\n const scoped_refptr& samples) {\n DVLOG(3) << \"Token \" << token << \"[audible:\" << audible << \"] encoded.\";\n if (audible) {\n samples_cache_audible_.Add(token, samples);\n current_token_audible_ = token;\n \/\/ Force process transmits to pick up the new token.\n if (player_audible_->IsPlaying())\n player_audible_->Stop();\n } else {\n samples_cache_inaudible_.Add(token, samples);\n current_token_inaudible_ = token;\n \/\/ Force process transmits to pick up the new token.\n if (player_inaudible_->IsPlaying())\n player_inaudible_->Stop();\n }\n\n ProcessNextTransmit();\n}\n\n} \/\/ namespace copresence\nFix race in audio playback.\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"components\/copresence\/handlers\/audio\/audio_directive_handler.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/time\/time.h\"\n#include \"components\/copresence\/mediums\/audio\/audio_player.h\"\n#include \"components\/copresence\/mediums\/audio\/audio_recorder.h\"\n#include \"components\/copresence\/proto\/data.pb.h\"\n#include \"media\/base\/audio_bus.h\"\n\nnamespace {\n\n\/\/ UrlSafe is defined as:\n\/\/ '\/' represented by a '_' and '+' represented by a '-'\n\/\/ TODO(rkc): Move this processing to the whispernet wrapper.\nstd::string FromUrlSafe(std::string token) {\n base::ReplaceChars(token, \"-\", \"+\", &token);\n base::ReplaceChars(token, \"_\", \"\/\", &token);\n return token;\n}\n\nconst int kSampleExpiryTimeMs = 60 * 60 * 1000; \/\/ 60 minutes.\nconst int kMaxSamples = 10000;\n\n} \/\/ namespace\n\nnamespace copresence {\n\n\/\/ Public methods.\n\nAudioDirectiveHandler::AudioDirectiveHandler(\n const AudioRecorder::DecodeSamplesCallback& decode_cb,\n const AudioDirectiveHandler::EncodeTokenCallback& encode_cb)\n : player_audible_(NULL),\n player_inaudible_(NULL),\n recorder_(NULL),\n decode_cb_(decode_cb),\n encode_cb_(encode_cb),\n samples_cache_audible_(\n base::TimeDelta::FromMilliseconds(kSampleExpiryTimeMs),\n kMaxSamples),\n samples_cache_inaudible_(\n base::TimeDelta::FromMilliseconds(kSampleExpiryTimeMs),\n kMaxSamples) {\n}\n\nAudioDirectiveHandler::~AudioDirectiveHandler() {\n if (player_audible_)\n player_audible_->Finalize();\n if (player_inaudible_)\n player_inaudible_->Finalize();\n if (recorder_)\n recorder_->Finalize();\n}\n\nvoid AudioDirectiveHandler::Initialize() {\n player_audible_ = new AudioPlayer();\n player_audible_->Initialize();\n\n player_inaudible_ = new AudioPlayer();\n player_inaudible_->Initialize();\n\n recorder_ = new AudioRecorder(decode_cb_);\n recorder_->Initialize();\n}\n\nvoid AudioDirectiveHandler::AddInstruction(const TokenInstruction& instruction,\n const std::string& op_id,\n base::TimeDelta ttl) {\n switch (instruction.token_instruction_type()) {\n case TRANSMIT:\n DVLOG(2) << \"Audio Transmit Directive received. Token: \"\n << instruction.token_id()\n << \" with TTL=\" << ttl.InMilliseconds();\n switch (instruction.medium()) {\n case AUDIO_ULTRASOUND_PASSBAND:\n transmits_list_inaudible_.AddDirective(op_id, ttl);\n PlayToken(instruction.token_id(), false);\n break;\n case AUDIO_AUDIBLE_DTMF:\n transmits_list_audible_.AddDirective(op_id, ttl);\n PlayToken(instruction.token_id(), true);\n break;\n default:\n NOTREACHED();\n }\n break;\n case RECEIVE:\n DVLOG(2) << \"Audio Receive Directive received. TTL=\"\n << ttl.InMilliseconds();\n receives_list_.AddDirective(op_id, ttl);\n ProcessNextReceive();\n break;\n case UNKNOWN_TOKEN_INSTRUCTION_TYPE:\n default:\n LOG(WARNING) << \"Unknown Audio Transmit Directive received.\";\n }\n}\n\nvoid AudioDirectiveHandler::RemoveInstructions(const std::string& op_id) {\n transmits_list_audible_.RemoveDirective(op_id);\n transmits_list_inaudible_.RemoveDirective(op_id);\n receives_list_.RemoveDirective(op_id);\n\n ProcessNextTransmit();\n ProcessNextReceive();\n}\n\n\/\/ Private methods.\n\nvoid AudioDirectiveHandler::ProcessNextTransmit() {\n \/\/ If we have an active directive for audible or inaudible audio, ensure that\n \/\/ we are playing our respective token; if we do not have a directive, then\n \/\/ make sure we aren't playing. This is duplicate code, but for just two\n \/\/ elements, it has hard to make a case for processing a loop instead.\n\n scoped_ptr audible_transmit(\n transmits_list_audible_.GetActiveDirective());\n if (audible_transmit && !player_audible_->IsPlaying() &&\n samples_cache_audible_.HasKey(current_token_audible_)) {\n DVLOG(3) << \"Playing audible for op_id: \" << audible_transmit->op_id;\n player_audible_->Play(\n samples_cache_audible_.GetValue(current_token_audible_));\n stop_audible_playback_timer_.Start(\n FROM_HERE,\n audible_transmit->end_time - base::Time::Now(),\n this,\n &AudioDirectiveHandler::ProcessNextTransmit);\n } else if (!audible_transmit && player_audible_->IsPlaying()) {\n DVLOG(3) << \"Stopping audible playback.\";\n current_token_audible_.clear();\n stop_audible_playback_timer_.Stop();\n player_audible_->Stop();\n }\n\n scoped_ptr inaudible_transmit(\n transmits_list_inaudible_.GetActiveDirective());\n if (inaudible_transmit && !player_inaudible_->IsPlaying() &&\n samples_cache_inaudible_.HasKey(current_token_inaudible_)) {\n DVLOG(3) << \"Playing inaudible for op_id: \" << inaudible_transmit->op_id;\n player_inaudible_->Play(\n samples_cache_inaudible_.GetValue(current_token_inaudible_));\n stop_inaudible_playback_timer_.Start(\n FROM_HERE,\n inaudible_transmit->end_time - base::Time::Now(),\n this,\n &AudioDirectiveHandler::ProcessNextTransmit);\n } else if (!inaudible_transmit && player_inaudible_->IsPlaying()) {\n DVLOG(3) << \"Stopping inaudible playback.\";\n current_token_inaudible_.clear();\n stop_inaudible_playback_timer_.Stop();\n player_inaudible_->Stop();\n }\n}\n\nvoid AudioDirectiveHandler::ProcessNextReceive() {\n scoped_ptr receive(receives_list_.GetActiveDirective());\n\n if (receive && !recorder_->IsRecording()) {\n DVLOG(3) << \"Recording for op_id: \" << receive->op_id;\n recorder_->Record();\n stop_recording_timer_.Start(FROM_HERE,\n receive->end_time - base::Time::Now(),\n this,\n &AudioDirectiveHandler::ProcessNextReceive);\n } else if (!receive && recorder_->IsRecording()) {\n DVLOG(3) << \"Stopping Recording\";\n stop_recording_timer_.Stop();\n recorder_->Stop();\n }\n}\n\nvoid AudioDirectiveHandler::PlayToken(const std::string token, bool audible) {\n std::string valid_token = FromUrlSafe(token);\n\n \/\/ If the token has been encoded already, use the cached samples.\n if (audible && samples_cache_audible_.HasKey(valid_token)) {\n current_token_audible_ = token;\n ProcessNextTransmit();\n } else if (!audible && samples_cache_inaudible_.HasKey(valid_token)) {\n current_token_inaudible_ = token;\n ProcessNextTransmit();\n } else {\n \/\/ Otherwise, encode the token and then play it.\n encode_cb_.Run(valid_token,\n audible,\n base::Bind(&AudioDirectiveHandler::PlayEncodedToken,\n base::Unretained(this)));\n }\n}\n\nvoid AudioDirectiveHandler::PlayEncodedToken(\n const std::string& token,\n bool audible,\n const scoped_refptr& samples) {\n DVLOG(3) << \"Token \" << token << \"[audible:\" << audible << \"] encoded.\";\n if (audible) {\n samples_cache_audible_.Add(token, samples);\n current_token_audible_ = token;\n \/\/ Force process transmits to pick up the new token.\n if (player_audible_->IsPlaying())\n player_audible_->Stop();\n } else {\n samples_cache_inaudible_.Add(token, samples);\n current_token_inaudible_ = token;\n \/\/ Force process transmits to pick up the new token.\n if (player_inaudible_->IsPlaying())\n player_inaudible_->Stop();\n }\n\n ProcessNextTransmit();\n}\n\n} \/\/ namespace copresence\n<|endoftext|>"} {"text":"\/\/---------------------------- mg_dof_handler.cc ---------------------------\n\/\/ $Id$\n\/\/ Version: $Name$ \n\/\/\n\/\/ Copyright (C) 2005, 2006 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------- mg_dof_handler.cc ---------------------------\n\n\n\/* Author: Ralf Hartmann, 2005, O. Kayser-Herold, simply modified\n the mg_dof_handler.cc test for the hp::DoFHandler. *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nint main ()\n{\n std::ofstream logfile(\"hp_dof_handler\/output\");\n logfile.precision(2);\n \n deallog.attach(logfile);\n deallog.depth_console(0);\n deallog.threshold_double(1.e-10);\n\n const unsigned int dim=2;\n Triangulation tria;\n GridGenerator::hyper_cube(tria);\n\n FECollection fe_collection;\n fe_collection.add_fe (FE_DGQ (1));\n\n hp::DoFHandler dof_handler(tria);\n \n tria.begin_active()->set_refine_flag();\n tria.execute_coarsening_and_refinement();\n\n Triangulation::active_cell_iterator\n cell=tria.begin_active(),\n endc=tria.end();\n for (; cell!=endc; ++cell)\n cell->set_coarsen_flag();\n tria.execute_coarsening_and_refinement();\n\n dof_handler.distribute_dofs(fe_collection);\n\n deallog << \"OK\" << std::endl;\n}\nUse proper namespace.\/\/---------------------------- mg_dof_handler.cc ---------------------------\n\/\/ $Id$\n\/\/ Version: $Name$ \n\/\/\n\/\/ Copyright (C) 2005, 2006 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------- mg_dof_handler.cc ---------------------------\n\n\n\/* Author: Ralf Hartmann, 2005, O. Kayser-Herold, simply modified\n the mg_dof_handler.cc test for the hp::DoFHandler. *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nint main ()\n{\n std::ofstream logfile(\"hp_dof_handler\/output\");\n logfile.precision(2);\n \n deallog.attach(logfile);\n deallog.depth_console(0);\n deallog.threshold_double(1.e-10);\n\n const unsigned int dim=2;\n Triangulation tria;\n GridGenerator::hyper_cube(tria);\n\n hp::FECollection fe_collection;\n fe_collection.add_fe (FE_DGQ (1));\n\n hp::DoFHandler dof_handler(tria);\n \n tria.begin_active()->set_refine_flag();\n tria.execute_coarsening_and_refinement();\n\n Triangulation::active_cell_iterator\n cell=tria.begin_active(),\n endc=tria.end();\n for (; cell!=endc; ++cell)\n cell->set_coarsen_flag();\n tria.execute_coarsening_and_refinement();\n\n dof_handler.distribute_dofs(fe_collection);\n\n deallog << \"OK\" << std::endl;\n}\n<|endoftext|>"} {"text":"#ifndef __UTILS2_HPP__\n#define __UTILS2_HPP__\n\n\/* utils2.hpp is a collection of utility functions and types that sits below the IO layer.\nThe reason it is separate from utils.hpp is that the IO layer needs some of the things in\nutils2.hpp, but utils.hpp needs some things in the IO layer. *\/\n\n#include \"config\/args.hpp\"\n#include \n#include \n#include \"errors.hpp\"\n\ntypedef uint64_t cas_t;\n\nint get_cpu_count();\nlong get_available_ram();\nlong get_total_ram();\n\n\/\/ This may be surprising to some people.\ntypedef char byte;\n\n\/\/ for safety TODO: move this to a different file\nstruct repli_timestamp {\n uint32_t time;\n\n static const repli_timestamp invalid;\n};\n\nstruct initialized_repli_timestamp {\n uint32_t time;\n explicit initialized_repli_timestamp(uint32_t _time) : time(_time) { }\n initialized_repli_timestamp(repli_timestamp timestamp) : time(timestamp.time) { }\n\n operator repli_timestamp() const {\n repli_timestamp ret = { time };\n return ret;\n }\n};\n\nstruct charslice {\n char *beg, *end;\n charslice(char *beg_, char *end_) : beg(beg_), end(end_) { }\n charslice() : beg(NULL), end(NULL) { }\n};\n\nstruct const_charslice {\n const char *beg, *end;\n const_charslice(const char *beg_, const char *end_) : beg(beg_), end(end_) { }\n const_charslice() : beg(NULL), end(NULL) { }\n};\n\n\n\n\/\/ Converts a time_t (in seconds) to a repli_timestamp, but avoids\n\/\/ returning the invalid repli_timestamp value, which might matter\n\/\/ once every 116 years.\nrepli_timestamp repli_time(time_t t);\n\n\/\/ TODO: move this to a different file\nrepli_timestamp current_time();\n\ntypedef uint64_t microtime_t;\n\nmicrotime_t current_microtime();\n\n\/\/ This is not a transitive operation. It compares times \"locally.\"\n\/\/ Imagine a comparison function that compares angles, in the range\n\/\/ [0, 2*pi), that is invariant with respect to rotation. How would\n\/\/ you implement that? This is a function that compares timestamps in\n\/\/ [0, 2**32), that is invariant with respect to translation.\nint repli_compare(repli_timestamp x, repli_timestamp y);\n\n\/\/ Like std::max, except it's technically not associative because it\n\/\/ uses repli_compare.\nrepli_timestamp repli_max(repli_timestamp x, repli_timestamp y);\n\n\nvoid *malloc_aligned(size_t size, size_t alignment = 64);\n\ntemplate \nT1 ceil_aligned(T1 value, T2 alignment) {\n return value + alignment - (((value + alignment - 1) % alignment) + 1);\n}\n\ntemplate \nT1 ceil_divide(T1 dividend, T2 alignment) {\n return (dividend + alignment - 1) \/ alignment;\n}\n\ntemplate \nT1 floor_aligned(T1 value, T2 alignment) {\n return value - (value % alignment);\n}\n\ntypedef unsigned long long ticks_t;\nticks_t secs_to_ticks(float secs);\nticks_t get_ticks();\nlong get_ticks_res();\nfloat ticks_to_secs(ticks_t ticks);\nfloat ticks_to_ms(ticks_t ticks);\nfloat ticks_to_us(ticks_t ticks);\n\n\/* Functions to create random delays. These must be in utils2.hpp instead of in\nutils.hpp because the mock IO layer uses random delays. Internally, they\nsecretly use the IO layer, but it is safe to include utils2.hpp from within the\nIO layer. *\/\n\nvoid random_delay(void (*)(void*), void*);\n\ntemplate\nvoid random_delay(cb_t *cb, void (cb_t::*method)());\n\ntemplate\nvoid random_delay(cb_t *cb, void (cb_t::*method)(arg1_t), arg1_t arg);\n\ntemplate\nbool maybe_random_delay(cb_t *cb, void (cb_t::*method)());\n\ntemplate\nbool maybe_random_delay(cb_t *cb, void (cb_t::*method)(arg1_t), arg1_t arg);\n\n\/* Debugging printing API (prints current thread in addition to message) *\/\n\nvoid debugf(const char *msg, ...) __attribute__((format (printf, 1, 2)));\n\n\/\/ Returns a random number in [0, n). Is not perfectly uniform; the\n\/\/ bias tends to get worse when RAND_MAX is far from a multiple of n.\nint randint(int n);\n\n\/\/ The existence of these functions does not constitute an endorsement\n\/\/ for casts. These constitute an endorsement for the use of\n\/\/ reinterpret_cast, rather than C-style casts. The latter can break\n\/\/ const correctness.\ntemplate \ninline const T* ptr_cast(const void *p) { return reinterpret_cast(p); }\n\ntemplate \ninline T* ptr_cast(void *p) { return reinterpret_cast(p); }\n\nbool begins_with_minus(const char *string);\n\/\/ strtoul() and strtoull() will for some reason not fail if the input begins with a minus\n\/\/ sign. strtoul_strict() and strtoull_strict() do.\nlong strtol_strict(const char *string, char **end, int base);\nunsigned long strtoul_strict(const char *string, char **end, int base);\nunsigned long long strtoull_strict(const char *string, char **end, int base);\nbool strtobool_strict(const char *string, char **end);\n\n\/\/ Put this in a private: section.\n#define DISABLE_COPYING(T) \\\n T(const T&); \\\n void operator=(const T&)\n\n\/\/ This is inefficient, it calls vsnprintf twice and copies the\n\/\/ arglist and output buffer excessively.\nstd::string strprintf(const char *format, ...) __attribute__ ((format (printf, 1, 2)));\n\n\/\/ Pad a value to the size of a cache line to avoid false sharing.\n\/\/ TODO: This is implemented as a struct with subtraction rather than a union\n\/\/ so that it gives an error when trying to pad a value bigger than\n\/\/ CACHE_LINE_SIZE. If that's needed, this may have to be done differently.\n\/\/ TODO: Use this in the rest of the perfmons, if it turns out to make any\n\/\/ difference.\n\ntemplate\nstruct cache_line_padded_t {\n value_t value;\n byte padding[CACHE_LINE_SIZE - sizeof value];\n};\n\n#include \"utils2.tcc\"\n\n#endif \/* __UTILS2_HPP__ *\/\nHopefully fix a compile bug :\/.#ifndef __UTILS2_HPP__\n#define __UTILS2_HPP__\n\n\/* utils2.hpp is a collection of utility functions and types that sits below the IO layer.\nThe reason it is separate from utils.hpp is that the IO layer needs some of the things in\nutils2.hpp, but utils.hpp needs some things in the IO layer. *\/\n\n#include \"config\/args.hpp\"\n#include \n#include \n#include \"errors.hpp\"\n\ntypedef uint64_t cas_t;\n\nint get_cpu_count();\nlong get_available_ram();\nlong get_total_ram();\n\n\/\/ This may be surprising to some people.\ntypedef char byte;\n\n\/\/ for safety TODO: move this to a different file\nstruct repli_timestamp {\n uint32_t time;\n\n static const repli_timestamp invalid;\n};\n\nstruct initialized_repli_timestamp {\n uint32_t time;\n explicit initialized_repli_timestamp(uint32_t _time) : time(_time) { }\n initialized_repli_timestamp(repli_timestamp timestamp) : time(timestamp.time) { }\n\n operator repli_timestamp() const {\n repli_timestamp ret = { time };\n return ret;\n }\n};\n\nstruct charslice {\n char *beg, *end;\n charslice(char *beg_, char *end_) : beg(beg_), end(end_) { }\n charslice() : beg(NULL), end(NULL) { }\n};\n\nstruct const_charslice {\n const char *beg, *end;\n const_charslice(const char *beg_, const char *end_) : beg(beg_), end(end_) { }\n const_charslice() : beg(NULL), end(NULL) { }\n};\n\n\n\n\/\/ Converts a time_t (in seconds) to a repli_timestamp, but avoids\n\/\/ returning the invalid repli_timestamp value, which might matter\n\/\/ once every 116 years.\nrepli_timestamp repli_time(time_t t);\n\n\/\/ TODO: move this to a different file\nrepli_timestamp current_time();\n\ntypedef uint64_t microtime_t;\n\nmicrotime_t current_microtime();\n\n\/\/ This is not a transitive operation. It compares times \"locally.\"\n\/\/ Imagine a comparison function that compares angles, in the range\n\/\/ [0, 2*pi), that is invariant with respect to rotation. How would\n\/\/ you implement that? This is a function that compares timestamps in\n\/\/ [0, 2**32), that is invariant with respect to translation.\nint repli_compare(repli_timestamp x, repli_timestamp y);\n\n\/\/ Like std::max, except it's technically not associative because it\n\/\/ uses repli_compare.\nrepli_timestamp repli_max(repli_timestamp x, repli_timestamp y);\n\n\nvoid *malloc_aligned(size_t size, size_t alignment = 64);\n\ntemplate \nT1 ceil_aligned(T1 value, T2 alignment) {\n return value + alignment - (((value + alignment - 1) % alignment) + 1);\n}\n\ntemplate \nT1 ceil_divide(T1 dividend, T2 alignment) {\n return (dividend + alignment - 1) \/ alignment;\n}\n\ntemplate \nT1 floor_aligned(T1 value, T2 alignment) {\n return value - (value % alignment);\n}\n\ntypedef unsigned long long ticks_t;\nticks_t secs_to_ticks(float secs);\nticks_t get_ticks();\nlong get_ticks_res();\nfloat ticks_to_secs(ticks_t ticks);\nfloat ticks_to_ms(ticks_t ticks);\nfloat ticks_to_us(ticks_t ticks);\n\n\/* Functions to create random delays. These must be in utils2.hpp instead of in\nutils.hpp because the mock IO layer uses random delays. Internally, they\nsecretly use the IO layer, but it is safe to include utils2.hpp from within the\nIO layer. *\/\n\nvoid random_delay(void (*)(void*), void*);\n\ntemplate\nvoid random_delay(cb_t *cb, void (cb_t::*method)());\n\ntemplate\nvoid random_delay(cb_t *cb, void (cb_t::*method)(arg1_t), arg1_t arg);\n\ntemplate\nbool maybe_random_delay(cb_t *cb, void (cb_t::*method)());\n\ntemplate\nbool maybe_random_delay(cb_t *cb, void (cb_t::*method)(arg1_t), arg1_t arg);\n\n\/* Debugging printing API (prints current thread in addition to message) *\/\n\nvoid debugf(const char *msg, ...) __attribute__((format (printf, 1, 2)));\n\n\/\/ Returns a random number in [0, n). Is not perfectly uniform; the\n\/\/ bias tends to get worse when RAND_MAX is far from a multiple of n.\nint randint(int n);\n\n\/\/ The existence of these functions does not constitute an endorsement\n\/\/ for casts. These constitute an endorsement for the use of\n\/\/ reinterpret_cast, rather than C-style casts. The latter can break\n\/\/ const correctness.\ntemplate \ninline const T* ptr_cast(const void *p) { return reinterpret_cast(p); }\n\ntemplate \ninline T* ptr_cast(void *p) { return reinterpret_cast(p); }\n\nbool begins_with_minus(const char *string);\n\/\/ strtoul() and strtoull() will for some reason not fail if the input begins with a minus\n\/\/ sign. strtoul_strict() and strtoull_strict() do.\nlong strtol_strict(const char *string, char **end, int base);\nunsigned long strtoul_strict(const char *string, char **end, int base);\nunsigned long long strtoull_strict(const char *string, char **end, int base);\nbool strtobool_strict(const char *string, char **end);\n\n\/\/ Put this in a private: section.\n#define DISABLE_COPYING(T) \\\n T(const T&); \\\n void operator=(const T&)\n\n\/\/ This is inefficient, it calls vsnprintf twice and copies the\n\/\/ arglist and output buffer excessively.\nstd::string strprintf(const char *format, ...) __attribute__ ((format (printf, 1, 2)));\n\n\/\/ Pad a value to the size of a cache line to avoid false sharing.\n\/\/ TODO: This is implemented as a struct with subtraction rather than a union\n\/\/ so that it gives an error when trying to pad a value bigger than\n\/\/ CACHE_LINE_SIZE. If that's needed, this may have to be done differently.\n\/\/ TODO: Use this in the rest of the perfmons, if it turns out to make any\n\/\/ difference.\n\ntemplate\nstruct cache_line_padded_t {\n value_t value;\n byte padding[CACHE_LINE_SIZE - sizeof value_t];\n};\n\n#include \"utils2.tcc\"\n\n#endif \/* __UTILS2_HPP__ *\/\n<|endoftext|>"} {"text":"#include \"json.h\"\n\n#include \"cc\/misc\/strings.h\"\n\nnamespace json {\n\nObject::Object() {\n type_ = JOT_NULL;\n data_ = NULL;\n}\n\nObject::Object(int64_t n) {\n type_ = JOT_INT;\n auto data = new int(n);\n data_ = reinterpret_cast(data);\n}\n\nObject::Object(const string& s) {\n type_ = JOT_STR;\n auto data = new string(s);\n data_ = reinterpret_cast(data);\n}\n\nObject::Object(const vector& vec) {\n vector v;\n v.reserve(vec.size());\n for (auto& it : vec) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const unordered_set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const vector& vec) {\n vector v;\n v.reserve(vec.size());\n for (auto& it : vec) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const unordered_set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const vector& v) {\n InitFromStrings(v);\n}\n\nObject::Object(const set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n v.emplace_back(it);\n }\n InitFromStrings(v);\n}\n\nObject::Object(const unordered_set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n v.emplace_back(it);\n }\n InitFromStrings(v);\n}\n\nObject::Object(const vector& v) {\n type_ = JOT_ARRAY;\n auto data = new vector(v);\n data_ = reinterpret_cast(data);\n}\n\nObject::Object(const map& d) {\n type_ = JOT_OBJ;\n auto data = new map();\n for (auto& it : d) {\n (*data)[it.first] = it.second;\n }\n data_ = reinterpret_cast(data);\n}\n\nObject::~Object() {\n switch (type_) {\n case JOT_NULL:\n break;\n case JOT_BOOL:\n delete reinterpret_cast(data_);\n break;\n case JOT_INT:\n delete reinterpret_cast(data_);\n break;\n case JOT_STR:\n delete reinterpret_cast(data_);\n break;\n case JOT_ARRAY:\n {\n auto* data = reinterpret_cast*>(data_);\n for (auto& obj : *data) {\n delete obj;\n }\n delete data;\n break;\n }\n case JOT_OBJ:\n {\n auto* data = reinterpret_cast*>(data_);\n for (auto& it : *data) {\n delete it.second;\n }\n delete data;\n break;\n }\n }\n}\n\nstatic void Quote(const string& in, string* out) {\n out->clear();\n out->reserve(in.size() + 2);\n *out += \"\\\"\";\n for (auto& c : in) {\n if (c == '\"') {\n *out += \"\\\\\\\"\";\n } else {\n *out += c;\n }\n }\n *out += \"\\\"\";\n}\n\nvoid Object::AppendToString(\n string* out, size_t spaces_per_indent, size_t offset_spaces,\n bool leading_indent) const {\n string indent0(offset_spaces, ' ');\n string indent1(offset_spaces + spaces_per_indent, ' ');\n\n if (leading_indent) {\n *out += indent0;\n }\n\n switch (type_) {\n case JOT_NULL: {\n *out += \"null\";\n break;\n }\n case JOT_BOOL: {\n auto& b = *reinterpret_cast(data_);\n *out += (b ? \"true\" : \"false\");\n break;\n }\n case JOT_INT: {\n auto& n = *reinterpret_cast(data_);\n *out += strings::StringPrintf(\"%ld\", n);\n break;\n }\n case JOT_STR: {\n auto& orig_s = *reinterpret_cast(data_);\n string quoted_s;\n Quote(orig_s, "ed_s);\n *out += quoted_s;\n break;\n }\n case JOT_ARRAY: {\n auto& v = *reinterpret_cast*>(data_);\n *out += \"[\";\n if (v.size()) {\n *out += \"\\n\";\n }\n for (auto i = 0u; i < v.size(); ++i) {\n auto& obj = v[i];\n obj->AppendToString(\n out, spaces_per_indent, offset_spaces + spaces_per_indent,\n true);\n if (i != v.size() - 1) {\n *out += \",\";\n }\n *out += \"\\n\";\n }\n if (v.size()) {\n *out += indent0;\n }\n *out += \"]\";\n break;\n }\n case JOT_OBJ: {\n auto& d = *reinterpret_cast*>(data_);\n *out += \"{\";\n if (d.size()) {\n *out += \"\\n\";\n }\n size_t count = 0;\n for (auto& it : d) {\n auto& orig_s = it.first;\n string quoted_s;\n Quote(orig_s, "ed_s);\n *out += indent1 + quoted_s + \": \";\n auto& obj = it.second;\n obj->AppendToString(\n out, spaces_per_indent, offset_spaces + spaces_per_indent,\n false);\n if (count != d.size() - 1) {\n *out += \",\";\n }\n *out += \"\\n\";\n }\n if (d.size()) {\n *out += indent0;\n }\n *out += \"}\";\n break;\n }\n }\n}\n\nvoid Object::InitFromInts(const vector& v) {\n type_ = JOT_ARRAY;\n auto data = new vector();\n data->reserve(v.size());\n for (auto& n : v) {\n data->emplace_back(new Object(n));\n }\n data_ = reinterpret_cast(data);\n}\n\nvoid Object::InitFromStrings(const vector& v) {\n type_ = JOT_ARRAY;\n auto data = new vector();\n data->reserve(v.size());\n for (auto& s : v) {\n data->emplace_back(new Object(s));\n }\n data_ = reinterpret_cast(data);\n}\n\n} \/\/ namespace json\nFix int64 init.#include \"json.h\"\n\n#include \"cc\/misc\/strings.h\"\n\nnamespace json {\n\nObject::Object() {\n type_ = JOT_NULL;\n data_ = NULL;\n}\n\nObject::Object(int64_t n) {\n type_ = JOT_INT;\n auto data = new int64_t(n);\n data_ = reinterpret_cast(data);\n}\n\nObject::Object(const string& s) {\n type_ = JOT_STR;\n auto data = new string(s);\n data_ = reinterpret_cast(data);\n}\n\nObject::Object(const vector& vec) {\n vector v;\n v.reserve(vec.size());\n for (auto& it : vec) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const unordered_set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const vector& vec) {\n vector v;\n v.reserve(vec.size());\n for (auto& it : vec) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const unordered_set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n auto n = static_cast(it);\n v.emplace_back(n);\n }\n InitFromInts(v);\n}\n\nObject::Object(const vector& v) {\n InitFromStrings(v);\n}\n\nObject::Object(const set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n v.emplace_back(it);\n }\n InitFromStrings(v);\n}\n\nObject::Object(const unordered_set& set) {\n vector v;\n v.reserve(set.size());\n for (auto& it : set) {\n v.emplace_back(it);\n }\n InitFromStrings(v);\n}\n\nObject::Object(const vector& v) {\n type_ = JOT_ARRAY;\n auto data = new vector(v);\n data_ = reinterpret_cast(data);\n}\n\nObject::Object(const map& d) {\n type_ = JOT_OBJ;\n auto data = new map();\n for (auto& it : d) {\n (*data)[it.first] = it.second;\n }\n data_ = reinterpret_cast(data);\n}\n\nObject::~Object() {\n switch (type_) {\n case JOT_NULL:\n break;\n case JOT_BOOL:\n delete reinterpret_cast(data_);\n break;\n case JOT_INT:\n delete reinterpret_cast(data_);\n break;\n case JOT_STR:\n delete reinterpret_cast(data_);\n break;\n case JOT_ARRAY:\n {\n auto* data = reinterpret_cast*>(data_);\n for (auto& obj : *data) {\n delete obj;\n }\n delete data;\n break;\n }\n case JOT_OBJ:\n {\n auto* data = reinterpret_cast*>(data_);\n for (auto& it : *data) {\n delete it.second;\n }\n delete data;\n break;\n }\n }\n}\n\nstatic void Quote(const string& in, string* out) {\n out->clear();\n out->reserve(in.size() + 2);\n *out += \"\\\"\";\n for (auto& c : in) {\n if (c == '\"') {\n *out += \"\\\\\\\"\";\n } else {\n *out += c;\n }\n }\n *out += \"\\\"\";\n}\n\nvoid Object::AppendToString(\n string* out, size_t spaces_per_indent, size_t offset_spaces,\n bool leading_indent) const {\n string indent0(offset_spaces, ' ');\n string indent1(offset_spaces + spaces_per_indent, ' ');\n\n if (leading_indent) {\n *out += indent0;\n }\n\n switch (type_) {\n case JOT_NULL: {\n *out += \"null\";\n break;\n }\n case JOT_BOOL: {\n auto& b = *reinterpret_cast(data_);\n *out += (b ? \"true\" : \"false\");\n break;\n }\n case JOT_INT: {\n auto& n = *reinterpret_cast(data_);\n *out += strings::StringPrintf(\"%ld\", n);\n break;\n }\n case JOT_STR: {\n auto& orig_s = *reinterpret_cast(data_);\n string quoted_s;\n Quote(orig_s, "ed_s);\n *out += quoted_s;\n break;\n }\n case JOT_ARRAY: {\n auto& v = *reinterpret_cast*>(data_);\n *out += \"[\";\n if (v.size()) {\n *out += \"\\n\";\n }\n for (auto i = 0u; i < v.size(); ++i) {\n auto& obj = v[i];\n obj->AppendToString(\n out, spaces_per_indent, offset_spaces + spaces_per_indent,\n true);\n if (i != v.size() - 1) {\n *out += \",\";\n }\n *out += \"\\n\";\n }\n if (v.size()) {\n *out += indent0;\n }\n *out += \"]\";\n break;\n }\n case JOT_OBJ: {\n auto& d = *reinterpret_cast*>(data_);\n *out += \"{\";\n if (d.size()) {\n *out += \"\\n\";\n }\n size_t count = 0;\n for (auto& it : d) {\n auto& orig_s = it.first;\n string quoted_s;\n Quote(orig_s, "ed_s);\n *out += indent1 + quoted_s + \": \";\n auto& obj = it.second;\n obj->AppendToString(\n out, spaces_per_indent, offset_spaces + spaces_per_indent,\n false);\n if (count != d.size() - 1) {\n *out += \",\";\n }\n *out += \"\\n\";\n }\n if (d.size()) {\n *out += indent0;\n }\n *out += \"}\";\n break;\n }\n }\n}\n\nvoid Object::InitFromInts(const vector& v) {\n type_ = JOT_ARRAY;\n auto data = new vector();\n data->reserve(v.size());\n for (auto& n : v) {\n data->emplace_back(new Object(n));\n }\n data_ = reinterpret_cast(data);\n}\n\nvoid Object::InitFromStrings(const vector& v) {\n type_ = JOT_ARRAY;\n auto data = new vector();\n data->reserve(v.size());\n for (auto& s : v) {\n data->emplace_back(new Object(s));\n }\n data_ = reinterpret_cast(data);\n}\n\n} \/\/ namespace json\n<|endoftext|>"} {"text":"\/\/call this script like this to have live scores:\n\/\/while true; do git pull; make -j grades.html; sleep 15; done;\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"..\/code\/util.cpp\"\n\nusing namespace std;\n\n\/\/grade one single test case\nint gradeFile(ifstream& in, ifstream& ans) {\n \/\/read input\n Input input;\n readInput(input, in);\n \n \/\/read answer\n \/\/TODO read answer\n\n \/\/compute score\n \/\/TODO compute score\n\n return -1;\n}\n\n\/\/iterate over all test cases\nint main() {\n \/\/open data directory\n DIR* datadir = opendir(\"data\");\n if(!datadir) {\n cerr << \"can't find data directory\" << endl;\n return 1;\n }\n \/\/save result data\n set algorithms, testcases;\n map, int> scores;\n map maxscores;\n \/\/iterate over all files\n struct dirent* file;\n ifstream in, ans;\n while(0 != (file = readdir(datadir))) {\n string ansname = file->d_name;\n if(ansname.size() > 4 && !ansname.compare(ansname.size() - 4, 4, \".ans\")) {\n cerr << \"solving file \" << ansname << endl;\n string testcase = ansname.substr(ansname.find_first_of(\".\") + 1, ansname.find_last_of(\".\") - ansname.find_first_of(\".\") - 1);\n testcases.insert(testcase);\n string algorithm = ansname.substr(0, ansname.find_first_of(\".\"));\n algorithms.insert(algorithm);\n in.open(\"data\/\" + testcase + \".in\");\n ans.open(\"data\/\" + ansname);\n scores[make_pair(algorithm, testcase)] = gradeFile(in, ans);\n maxscores[testcase] = max(maxscores[testcase], scores[make_pair(algorithm, testcase)]);\n in.close();\n ans.close();\n }\n }\n \/\/print header\n cout << \"\"\n \"\"\n \"\"\n \"