{"text":"\/************************************************************************\n*\n* Copyright (C) 2017 by Peter Harrison. www.micromouseonline.com\n*\n* Permission is hereby granted, free of charge, to any person obtaining a\n* copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without l> imitation 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 included\n* in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\n************************************************************************\/\n\n#include \n#include \"maze.h\"\n#include \"mazesearcher.h\"\n#include \"mazeprinter.h\"\n\/\/#include \"stddef.h\"\n\nMazeSearcher::MazeSearcher() :\n mLocation(0),\n mHeading(NORTH),\n mMap(NULL),\n mRealMaze(NULL),\n mVerbose(false),\n mSearchMethod(SEARCH_NORMAL) {\n mMap = new Maze(16);\n mMap->setFloodType(Maze::MANHATTAN_FLOOD);\n}\n\nMazeSearcher::~MazeSearcher() {\n delete mMap;\n}\n\nbool MazeSearcher::isVerbose() const {\n return mVerbose;\n}\n\nvoid MazeSearcher::setVerbose(bool mVerbose) {\n MazeSearcher::mVerbose = mVerbose;\n}\n\nuint16_t MazeSearcher::location() const {\n return mLocation;\n}\n\nvoid MazeSearcher::setLocation(uint16_t location) {\n MazeSearcher::mLocation = location;\n}\n\nuint8_t MazeSearcher::heading() const {\n return mHeading;\n}\n\nvoid MazeSearcher::setHeading(uint8_t heading) {\n MazeSearcher::mHeading = heading;\n}\n\nvoid MazeSearcher::move() {\n mLocation = mMap->neighbour(mLocation, mHeading);\n}\n\nvoid MazeSearcher::setMapFromFileData(const uint8_t *mazeWalls, uint16_t cellCount) {\n mMap->copyMazeFromFileData(mazeWalls, cellCount);\n}\n\nMaze *MazeSearcher::map() {\n return mMap;\n}\n\nconst Maze *MazeSearcher::realMaze() const {\n return mRealMaze;\n}\n\nvoid MazeSearcher::setRealMaze(const Maze *maze) {\n mRealMaze = maze;\n}\n\nint MazeSearcher::runTo(uint16_t target) {\n int steps = 0;\n mMap->flood(target);\n while (mLocation != target) {\n uint8_t heading = mMap->direction(mLocation);\n if (heading == INVALID_DIRECTION) {\n steps = -1;\n break;\n }\n\n setHeading(heading);\n move();\n steps++;\n if (steps > 256) {\n steps = -2;\n break;\n }\n if (isVerbose()) {\n MazePrinter::printVisitedDirs(mMap);\n }\n }\n return steps;\n}\n\n\/\/ TODO: this needs looking at.\n\/\/ the returned number of steps may be inconsistent\nint MazeSearcher::searchTo(uint16_t target) {\n int stepCount = 0;\n while (mLocation != target) {\n mMap->updateMap(mLocation, mRealMaze->walls(mLocation));\n uint8_t newHeading;\n switch (mSearchMethod) {\n case SEARCH_LEFT_WALL:\n newHeading = followLeftWall();\n break;\n case SEARCH_RIGHT_WALL:\n newHeading = followRightWall();\n break;\n case SEARCH_ALTERNATE:\n newHeading = followAlternateWall();\n break;\n case SEARCH_NORMAL:\n mMap->flood(target);\n newHeading = mMap->direction(mLocation);\n break;\n default:\n newHeading = INVALID_DIRECTION;\n break;\n }\n if (newHeading == INVALID_DIRECTION) {\n stepCount = E_NO_ROUTE;\n break;\n }\n setHeading(newHeading);\n stepCount++;\n if (stepCount > mMap->numCells()) {\n stepCount = E_ROUTE_TOO_LONG;\n break;\n }\n move();\n if (isVerbose()) {\n MazePrinter::printVisitedDirs(mMap);\n }\n }\n return stepCount;\n}\n\nuint8_t MazeSearcher::followLeftWall() const {\n uint8_t newHeading;\n if (mMap->hasExit(mLocation, Maze::leftOf(mHeading))) {\n newHeading = Maze::leftOf(mHeading);\n } else if (mMap->hasExit(mLocation, Maze::ahead(mHeading))) {\n newHeading = Maze::ahead(mHeading);\n } else if (mMap->hasExit(mLocation, Maze::rightOf(mHeading))) {\n newHeading = Maze::rightOf(mHeading);\n } else {\n newHeading = Maze::behind(mHeading);\n }\n return newHeading;\n}\n\nuint8_t MazeSearcher::followRightWall() const {\n uint8_t newHeading;\n if (mMap->hasExit(mLocation, Maze::rightOf(mHeading))) {\n newHeading = Maze::rightOf(mHeading);\n } else if (mMap->hasExit(mLocation, Maze::ahead(mHeading))) {\n newHeading = Maze::ahead(mHeading);\n } else if (mMap->hasExit(mLocation, Maze::leftOf(mHeading))) {\n newHeading = Maze::leftOf(mHeading);\n } else {\n newHeading = Maze::behind(mHeading);\n }\n return newHeading;\n}\n\nuint8_t MazeSearcher::followAlternateWall() const {\n static bool useLeft = true;\n uint8_t newHeading;\n newHeading = useLeft ? followLeftWall() : followRightWall();\n useLeft = !useLeft;\n return newHeading;\n}\n\nvoid MazeSearcher::setSearchMethod(int mSearchMethod) {\n MazeSearcher::mSearchMethod = mSearchMethod;\n}\n\nvoid MazeSearcher::turnRight() {\n mHeading = Maze::rightOf(mHeading);\n}\n\nvoid MazeSearcher::turnLeft() {\n mHeading = Maze::leftOf(mHeading);\n}\n\nvoid MazeSearcher::turnAround() {\n mHeading = Maze::behind(mHeading);\n}\nreinstate stddef.h to get a definition for NULL\/************************************************************************\n*\n* Copyright (C) 2017 by Peter Harrison. www.micromouseonline.com\n*\n* Permission is hereby granted, free of charge, to any person obtaining a\n* copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without l> imitation 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 included\n* in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\n************************************************************************\/\n\n#include \n#include \"maze.h\"\n#include \"mazesearcher.h\"\n#include \"mazeprinter.h\"\n#include \"stddef.h\"\n\nMazeSearcher::MazeSearcher() :\n mLocation(0),\n mHeading(NORTH),\n mMap(NULL),\n mRealMaze(NULL),\n mVerbose(false),\n mSearchMethod(SEARCH_NORMAL) {\n mMap = new Maze(16);\n mMap->setFloodType(Maze::MANHATTAN_FLOOD);\n}\n\nMazeSearcher::~MazeSearcher() {\n delete mMap;\n}\n\nbool MazeSearcher::isVerbose() const {\n return mVerbose;\n}\n\nvoid MazeSearcher::setVerbose(bool mVerbose) {\n MazeSearcher::mVerbose = mVerbose;\n}\n\nuint16_t MazeSearcher::location() const {\n return mLocation;\n}\n\nvoid MazeSearcher::setLocation(uint16_t location) {\n MazeSearcher::mLocation = location;\n}\n\nuint8_t MazeSearcher::heading() const {\n return mHeading;\n}\n\nvoid MazeSearcher::setHeading(uint8_t heading) {\n MazeSearcher::mHeading = heading;\n}\n\nvoid MazeSearcher::move() {\n mLocation = mMap->neighbour(mLocation, mHeading);\n}\n\nvoid MazeSearcher::setMapFromFileData(const uint8_t *mazeWalls, uint16_t cellCount) {\n mMap->copyMazeFromFileData(mazeWalls, cellCount);\n}\n\nMaze *MazeSearcher::map() {\n return mMap;\n}\n\nconst Maze *MazeSearcher::realMaze() const {\n return mRealMaze;\n}\n\nvoid MazeSearcher::setRealMaze(const Maze *maze) {\n mRealMaze = maze;\n}\n\nint MazeSearcher::runTo(uint16_t target) {\n int steps = 0;\n mMap->flood(target);\n while (mLocation != target) {\n uint8_t heading = mMap->direction(mLocation);\n if (heading == INVALID_DIRECTION) {\n steps = -1;\n break;\n }\n\n setHeading(heading);\n move();\n steps++;\n if (steps > 256) {\n steps = -2;\n break;\n }\n if (isVerbose()) {\n MazePrinter::printVisitedDirs(mMap);\n }\n }\n return steps;\n}\n\n\/\/ TODO: this needs looking at.\n\/\/ the returned number of steps may be inconsistent\nint MazeSearcher::searchTo(uint16_t target) {\n int stepCount = 0;\n while (mLocation != target) {\n mMap->updateMap(mLocation, mRealMaze->walls(mLocation));\n uint8_t newHeading;\n switch (mSearchMethod) {\n case SEARCH_LEFT_WALL:\n newHeading = followLeftWall();\n break;\n case SEARCH_RIGHT_WALL:\n newHeading = followRightWall();\n break;\n case SEARCH_ALTERNATE:\n newHeading = followAlternateWall();\n break;\n case SEARCH_NORMAL:\n mMap->flood(target);\n newHeading = mMap->direction(mLocation);\n break;\n default:\n newHeading = INVALID_DIRECTION;\n break;\n }\n if (newHeading == INVALID_DIRECTION) {\n stepCount = E_NO_ROUTE;\n break;\n }\n setHeading(newHeading);\n stepCount++;\n if (stepCount > mMap->numCells()) {\n stepCount = E_ROUTE_TOO_LONG;\n break;\n }\n move();\n if (isVerbose()) {\n MazePrinter::printVisitedDirs(mMap);\n }\n }\n return stepCount;\n}\n\nuint8_t MazeSearcher::followLeftWall() const {\n uint8_t newHeading;\n if (mMap->hasExit(mLocation, Maze::leftOf(mHeading))) {\n newHeading = Maze::leftOf(mHeading);\n } else if (mMap->hasExit(mLocation, Maze::ahead(mHeading))) {\n newHeading = Maze::ahead(mHeading);\n } else if (mMap->hasExit(mLocation, Maze::rightOf(mHeading))) {\n newHeading = Maze::rightOf(mHeading);\n } else {\n newHeading = Maze::behind(mHeading);\n }\n return newHeading;\n}\n\nuint8_t MazeSearcher::followRightWall() const {\n uint8_t newHeading;\n if (mMap->hasExit(mLocation, Maze::rightOf(mHeading))) {\n newHeading = Maze::rightOf(mHeading);\n } else if (mMap->hasExit(mLocation, Maze::ahead(mHeading))) {\n newHeading = Maze::ahead(mHeading);\n } else if (mMap->hasExit(mLocation, Maze::leftOf(mHeading))) {\n newHeading = Maze::leftOf(mHeading);\n } else {\n newHeading = Maze::behind(mHeading);\n }\n return newHeading;\n}\n\nuint8_t MazeSearcher::followAlternateWall() const {\n static bool useLeft = true;\n uint8_t newHeading;\n newHeading = useLeft ? followLeftWall() : followRightWall();\n useLeft = !useLeft;\n return newHeading;\n}\n\nvoid MazeSearcher::setSearchMethod(int mSearchMethod) {\n MazeSearcher::mSearchMethod = mSearchMethod;\n}\n\nvoid MazeSearcher::turnRight() {\n mHeading = Maze::rightOf(mHeading);\n}\n\nvoid MazeSearcher::turnLeft() {\n mHeading = Maze::leftOf(mHeading);\n}\n\nvoid MazeSearcher::turnAround() {\n mHeading = Maze::behind(mHeading);\n}\n<|endoftext|>"} {"text":"#include \n#include \n\/\/#include \n\/\/#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MainWin.h\"\n#include \"ui_Main.h\"\nusing namespace std;\n\n\/\/ types\nusing eth::bytes;\nusing eth::bytesConstRef;\nusing eth::h160;\nusing eth::h256;\nusing eth::u160;\nusing eth::u256;\nusing eth::Address;\nusing eth::BlockInfo;\nusing eth::Client;\nusing eth::Instruction;\nusing eth::KeyPair;\nusing eth::NodeMode;\nusing eth::PeerInfo;\nusing eth::RLP;\nusing eth::Secret;\nusing eth::Transaction;\n\n\/\/ functions\nusing eth::asHex;\nusing eth::assemble;\nusing eth::compileLisp;\nusing eth::disassemble;\nusing eth::formatBalance;\nusing eth::fromUserHex;\nusing eth::right160;\nusing eth::simpleDebugOut;\nusing eth::toLog2;\nusing eth::toString;\nusing eth::units;\n\n\/\/ vars\nusing eth::g_logPost;\nusing eth::g_logVerbosity;\nusing eth::c_instructionInfo;\n\n\/\/ Horrible global for the mainwindow. Needed for the QEthereums to find the Main window which acts as multiplexer for now.\n\/\/ Can get rid of this once we've sorted out ITC for signalling & multiplexed querying.\nMain* g_main = nullptr;\n\n#define ADD_QUOTES_HELPER(s) #s\n#define ADD_QUOTES(s) ADD_QUOTES_HELPER(s)\n\nQEthereum::QEthereum(QObject* _p): QObject(_p)\n{\n\tconnect(g_main, SIGNAL(changed()), SIGNAL(changed()));\n}\n\nQEthereum::~QEthereum()\n{\n}\n\nClient* QEthereum::client() const\n{\n\treturn g_main->client();\n}\n\nAddress QEthereum::coinbase() const\n{\n\treturn client()->address();\n}\n\nvoid QEthereum::setCoinbase(Address _a)\n{\n\tif (client()->address() != _a)\n\t{\n\t\tclient()->setAddress(_a);\n\t\tchanged();\n\t}\n}\n\nQAccount::QAccount(QObject* _p)\n{\n}\n\nQAccount::~QAccount()\n{\n}\n\nvoid QAccount::setEthereum(QEthereum* _eth)\n{\n\tif (m_eth == _eth)\n\t\treturn;\n\tif (m_eth)\n\t\tdisconnect(m_eth, SIGNAL(changed()), this, SIGNAL(changed()));\n\tm_eth = _eth;\n\tif (m_eth)\n\t\tconnect(m_eth, SIGNAL(changed()), this, SIGNAL(changed()));\n\tethChanged();\n\tchanged();\n}\n\nu256 QAccount::balance() const\n{\n\tif (m_eth)\n\t\treturn m_eth->balanceAt(m_address);\n\treturn 0;\n}\n\nuint64_t QAccount::txCount() const\n{\n\tif (m_eth)\n\t\treturn m_eth->txCountAt(m_address);\n\treturn 0;\n}\n\nbool QAccount::isContract() const\n{\n\tif (m_eth)\n\t\treturn m_eth->isContractAt(m_address);\n\treturn 0;\n}\n\nu256 QEthereum::balanceAt(Address _a) const\n{\n\treturn client()->postState().balance(_a);\n}\n\nbool QEthereum::isContractAt(Address _a) const\n{\n\treturn client()->postState().isContractAddress(_a);\n}\n\nbool QEthereum::isMining() const\n{\n\treturn client()->isMining();\n}\n\nbool QEthereum::isListening() const\n{\n\treturn client()->haveNetwork();\n}\n\nvoid QEthereum::setMining(bool _l)\n{\n\tif (_l)\n\t\tclient()->startMining();\n\telse\n\t\tclient()->stopMining();\n}\n\nvoid QEthereum::setListening(bool _l)\n{\n\tif (_l)\n\t\tclient()->startNetwork();\n\telse\n\t\tclient()->stopNetwork();\n}\n\nuint64_t QEthereum::txCountAt(Address _a) const\n{\n\treturn (uint64_t)client()->postState().transactionsFrom(_a);\n}\n\nunsigned QEthereum::peerCount() const\n{\n\treturn client()->peerCount();\n}\n\nvoid QEthereum::transact(Secret _secret, Address _dest, u256 _amount)\n{\n\tclient()->transact(_secret, _dest, _amount);\n}\n\nMain::Main(QWidget *parent) :\n\tQMainWindow(parent),\n\tui(new Ui::Main)\n{\n\tsetWindowFlags(Qt::Window);\n\tui->setupUi(this);\n\tsetWindowIcon(QIcon(\":\/Ethereum.png\"));\n\n\tg_main = this;\n\n\tm_client.reset(new Client(\"Walleth\", Address(), eth::getDataDir() + \"\/Walleth\"));\n\n\tqRegisterMetaType(\"eth::u256\");\n\tqRegisterMetaType(\"eth::KeyPair\");\n\tqRegisterMetaType(\"eth::Secret\");\n\tqRegisterMetaType(\"eth::Address\");\n\tqRegisterMetaType(\"QAccount*\");\n\tqRegisterMetaType(\"QEthereum*\");\n\n\tqmlRegisterType(\"org.ethereum\", 1, 0, \"Ethereum\");\n\tqmlRegisterType(\"org.ethereum\", 1, 0, \"Account\");\n\tqmlRegisterSingletonType(\"org.ethereum\", 1, 0, \"Balance\", QEthereum::constructU256Helper);\n\tqmlRegisterSingletonType(\"org.ethereum\", 1, 0, \"Key\", QEthereum::constructKeyHelper);\n\n\t\/*\n\tui->librariesView->setModel(m_libraryMan);\n\tui->graphsView->setModel(m_graphMan);\n\t*\/\n\n\tm_view = new QQuickView();\n\n\/\/\tQQmlContext* context = m_view->rootContext();\n\/\/\tcontext->setContextProperty(\"u256\", new U256Helper(this));\n\n\tm_view->setSource(QUrl(\"qrc:\/Simple.qml\"));\n\n\tQWidget* w = QWidget::createWindowContainer(m_view);\n\tm_view->setResizeMode(QQuickView::SizeRootObjectToView);\n\tui->fullDisplay->insertWidget(0, w);\n\tm_view->create();\n\n\/\/\tm_timelinesItem = m_view->rootObject()->findChild(\"timelines\");\n\n\treadSettings();\n\trefresh();\n\n\tm_refreshNetwork = new QTimer(this);\n\tconnect(m_refreshNetwork, SIGNAL(timeout()), SLOT(refreshNetwork()));\n\tm_refreshNetwork->start(1000);\n\n\tconnect(this, SIGNAL(changed()), SLOT(refresh()));\n\n\tconnect(&m_webCtrl, &QNetworkAccessManager::finished, [&](QNetworkReply* _r)\n\t{\n\t\tm_servers = QString::fromUtf8(_r->readAll()).split(\"\\n\", QString::SkipEmptyParts);\n\t\tif (m_servers.size())\n\t\t{\n\t\t\tui->net->setChecked(true);\n\t\t\ton_net_triggered(true);\n\t\t}\n\t});\n\tQNetworkRequest r(QUrl(\"http:\/\/www.ethereum.org\/servers.poc3.txt\"));\n\tr.setHeader(QNetworkRequest::UserAgentHeader, \"Mozilla\/5.0 (Windows NT 6.3; WOW64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/33.0.1712.0 Safari\/537.36\");\n\tm_webCtrl.get(r);\n\tsrand(time(0));\n\n\tstartTimer(200);\n\n\tstatusBar()->addPermanentWidget(ui->balance);\n\tstatusBar()->addPermanentWidget(ui->peerCount);\n\tstatusBar()->addPermanentWidget(ui->blockCount);\n}\n\nMain::~Main()\n{\n\twriteSettings();\n}\n\nvoid Main::timerEvent(QTimerEvent *)\n{\n\tif (m_client->changed())\n\t\tchanged();\n}\n\nvoid Main::on_about_triggered()\n{\n\tQMessageBox::about(this, \"About Walleth PoC-\" + QString(ADD_QUOTES(ETH_VERSION)).section('.', 1, 1), \"Walleth\/v\" ADD_QUOTES(ETH_VERSION) \"\/\" ADD_QUOTES(ETH_BUILD_TYPE) \"\/\" ADD_QUOTES(ETH_BUILD_PLATFORM) \"\\nBy Gav Wood, 2014.\\nBased on a design by Vitalik Buterin.\\n\\nTeam Ethereum++ includes: Tim Hughes, Eric Lombrozo, Marko Simovic, Alex Leverington and several others.\");\n}\n\nvoid Main::writeSettings()\n{\n\tQSettings s(\"ethereum\", \"walleth\");\n\tQByteArray b;\n\tb.resize(sizeof(Secret) * m_myKeys.size());\n\tauto p = b.data();\n\tfor (auto i: m_myKeys)\n\t{\n\t\tmemcpy(p, &(i.secret()), sizeof(Secret));\n\t\tp += sizeof(Secret);\n\t}\n\ts.setValue(\"address\", b);\n\n\ts.setValue(\"upnp\", ui->upnp->isChecked());\n\ts.setValue(\"clientName\", m_clientName);\n\ts.setValue(\"idealPeers\", m_idealPeers);\n\ts.setValue(\"port\", m_port);\n\n\tif (client()->peerServer())\n\t{\n\t\tbytes d = client()->peerServer()->savePeers();\n\t\tm_peers = QByteArray((char*)d.data(), (int)d.size());\n\n\t}\n\ts.setValue(\"peers\", m_peers);\n\n\ts.setValue(\"geometry\", saveGeometry());\n\ts.setValue(\"windowState\", saveState());\n}\n\nvoid Main::readSettings()\n{\n\tQSettings s(\"ethereum\", \"walleth\");\n\n\trestoreGeometry(s.value(\"geometry\").toByteArray());\n\trestoreState(s.value(\"windowState\").toByteArray());\n\n\n\tQByteArray b = s.value(\"address\").toByteArray();\n\tif (b.isEmpty())\n\t\tm_myKeys.append(KeyPair::create());\n\telse\n\t{\n\t\th256 k;\n\t\tfor (unsigned i = 0; i < b.size() \/ sizeof(Secret); ++i)\n\t\t{\n\t\t\tmemcpy(&k, b.data() + i * sizeof(Secret), sizeof(Secret));\n\t\t\tm_myKeys.append(KeyPair(k));\n\t\t}\n\t}\n\t\/\/m_eth->setAddress(m_myKeys.last().address());\n\tm_peers = s.value(\"peers\").toByteArray();\n\tui->upnp->setChecked(s.value(\"upnp\", true).toBool());\n\tm_clientName = s.value(\"clientName\", \"\").toString();\n\tm_idealPeers = s.value(\"idealPeers\", 5).toInt();\n\tm_port = s.value(\"port\", 30303).toInt();\n}\n\nvoid Main::refreshNetwork()\n{\n\tauto ps = client()->peers();\n\tui->peerCount->setText(QString::fromStdString(toString(ps.size())) + \" peer(s)\");\n}\n\neth::State const& Main::state() const\n{\n\treturn ui->preview->isChecked() ? client()->postState() : client()->state();\n}\n\nvoid Main::refresh()\n{\n\teth::ClientGuard l(client());\n\tauto const& st = state();\n\n\tauto d = client()->blockChain().details();\n\tauto diff = BlockInfo(client()->blockChain().block()).difficulty;\n\tui->blockCount->setText(QString(\"#%1 @%3 T%2\").arg(d.number).arg(toLog2(d.totalDifficulty)).arg(toLog2(diff)));\n\n\tm_keysChanged = false;\n\tu256 totalBalance = 0;\n\tfor (auto i: m_myKeys)\n\t{\n\t\tu256 b = st.balance(i.address());\n\t\ttotalBalance += b;\n\t}\n\tui->balance->setText(QString::fromStdString(formatBalance(totalBalance)));\n}\n\nvoid Main::on_net_triggered(bool _auto)\n{\n\tstring n = \"Walleth\/v\" ADD_QUOTES(ETH_VERSION);\n\tif (m_clientName.size())\n\t\tn += \"\/\" + m_clientName.toStdString();\n\tn += \"\/\" ADD_QUOTES(ETH_BUILD_TYPE) \"\/\" ADD_QUOTES(ETH_BUILD_PLATFORM);\n\tclient()->setClientVersion(n);\n\tif (ui->net->isChecked())\n\t{\n\t\tif (_auto)\n\t\t{\n\t\t\tQString s = m_servers[rand() % m_servers.size()];\n\t\t\tclient()->startNetwork(m_port, s.section(':', 0, 0).toStdString(), s.section(':', 1).toInt(), NodeMode::Full, m_idealPeers, std::string(), ui->upnp->isChecked());\n\t\t}\n\t\telse\n\t\t\tclient()->startNetwork(m_port, string(), 0, NodeMode::Full, m_idealPeers, std::string(), ui->upnp->isChecked());\n\t\tif (m_peers.size())\n\t\t\tclient()->peerServer()->restorePeers(bytesConstRef((byte*)m_peers.data(), m_peers.size()));\n\t}\n\telse\n\t\tclient()->stopNetwork();\n}\n\nvoid Main::on_connect_triggered()\n{\n\tif (!ui->net->isChecked())\n\t{\n\t\tui->net->setChecked(true);\n\t\ton_net_triggered();\n\t}\n\tbool ok = false;\n\tQString s = QInputDialog::getItem(this, \"Connect to a Network Peer\", \"Enter a peer to which a connection may be made:\", m_servers, m_servers.count() ? rand() % m_servers.count() : 0, true, &ok);\n\tif (ok && s.contains(\":\"))\n\t{\n\t\tstring host = s.section(\":\", 0, 0).toStdString();\n\t\tunsigned short port = s.section(\":\", 1).toInt();\n\t\tclient()->connect(host, port);\n\t}\n}\n\nvoid Main::on_mine_triggered()\n{\n\tif (ui->mine->isChecked())\n\t{\n\t\tclient()->setAddress(m_myKeys.last().address());\n\t\tclient()->startMining();\n\t}\n\telse\n\t\tclient()->stopMining();\n}\n\nvoid Main::on_create_triggered()\n{\n\tm_myKeys.append(KeyPair::create());\n\tm_keysChanged = true;\n}\n\n\/\/ extra bits needed to link on VS\n#ifdef _MSC_VER\n\n\/\/ include moc file, ofuscated to hide from automoc\n#include\\\n\"moc_MainWin.cpp\"\n\n\/\/ specify library dependencies, it's easier to do here than in the project since we can control the \"d\" debug suffix\n#ifdef _DEBUG\n#define QTLIB(x) x\"d.lib\"\n#else \n#define QTLIB(x) x\".lib\"\n#endif\n\n#pragma comment(lib, QTLIB(\"Qt5PlatformSupport\"))\n#pragma comment(lib, QTLIB(\"Qt5Core\"))\n#pragma comment(lib, QTLIB(\"Qt5GUI\"))\n#pragma comment(lib, QTLIB(\"Qt5Widgets\"))\n#pragma comment(lib, QTLIB(\"Qt5Network\"))\n#pragma comment(lib, QTLIB(\"qwindows\"))\n#pragma comment(lib, \"Imm32.lib\")\n#pragma comment(lib, \"opengl32.lib\")\n#pragma comment(lib, \"winmm.lib\")\n\n\n#endif\nUse BuildInfo.h#include \n#include \n\/\/#include \n\/\/#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"BuildInfo.h\"\n#include \"MainWin.h\"\n#include \"ui_Main.h\"\nusing namespace std;\n\n\/\/ types\nusing eth::bytes;\nusing eth::bytesConstRef;\nusing eth::h160;\nusing eth::h256;\nusing eth::u160;\nusing eth::u256;\nusing eth::Address;\nusing eth::BlockInfo;\nusing eth::Client;\nusing eth::Instruction;\nusing eth::KeyPair;\nusing eth::NodeMode;\nusing eth::PeerInfo;\nusing eth::RLP;\nusing eth::Secret;\nusing eth::Transaction;\n\n\/\/ functions\nusing eth::asHex;\nusing eth::assemble;\nusing eth::compileLisp;\nusing eth::disassemble;\nusing eth::formatBalance;\nusing eth::fromUserHex;\nusing eth::right160;\nusing eth::simpleDebugOut;\nusing eth::toLog2;\nusing eth::toString;\nusing eth::units;\n\n\/\/ vars\nusing eth::g_logPost;\nusing eth::g_logVerbosity;\nusing eth::c_instructionInfo;\n\n\/\/ Horrible global for the mainwindow. Needed for the QEthereums to find the Main window which acts as multiplexer for now.\n\/\/ Can get rid of this once we've sorted out ITC for signalling & multiplexed querying.\nMain* g_main = nullptr;\n\nQEthereum::QEthereum(QObject* _p): QObject(_p)\n{\n\tconnect(g_main, SIGNAL(changed()), SIGNAL(changed()));\n}\n\nQEthereum::~QEthereum()\n{\n}\n\nClient* QEthereum::client() const\n{\n\treturn g_main->client();\n}\n\nAddress QEthereum::coinbase() const\n{\n\treturn client()->address();\n}\n\nvoid QEthereum::setCoinbase(Address _a)\n{\n\tif (client()->address() != _a)\n\t{\n\t\tclient()->setAddress(_a);\n\t\tchanged();\n\t}\n}\n\nQAccount::QAccount(QObject* _p)\n{\n}\n\nQAccount::~QAccount()\n{\n}\n\nvoid QAccount::setEthereum(QEthereum* _eth)\n{\n\tif (m_eth == _eth)\n\t\treturn;\n\tif (m_eth)\n\t\tdisconnect(m_eth, SIGNAL(changed()), this, SIGNAL(changed()));\n\tm_eth = _eth;\n\tif (m_eth)\n\t\tconnect(m_eth, SIGNAL(changed()), this, SIGNAL(changed()));\n\tethChanged();\n\tchanged();\n}\n\nu256 QAccount::balance() const\n{\n\tif (m_eth)\n\t\treturn m_eth->balanceAt(m_address);\n\treturn 0;\n}\n\nuint64_t QAccount::txCount() const\n{\n\tif (m_eth)\n\t\treturn m_eth->txCountAt(m_address);\n\treturn 0;\n}\n\nbool QAccount::isContract() const\n{\n\tif (m_eth)\n\t\treturn m_eth->isContractAt(m_address);\n\treturn 0;\n}\n\nu256 QEthereum::balanceAt(Address _a) const\n{\n\treturn client()->postState().balance(_a);\n}\n\nbool QEthereum::isContractAt(Address _a) const\n{\n\treturn client()->postState().isContractAddress(_a);\n}\n\nbool QEthereum::isMining() const\n{\n\treturn client()->isMining();\n}\n\nbool QEthereum::isListening() const\n{\n\treturn client()->haveNetwork();\n}\n\nvoid QEthereum::setMining(bool _l)\n{\n\tif (_l)\n\t\tclient()->startMining();\n\telse\n\t\tclient()->stopMining();\n}\n\nvoid QEthereum::setListening(bool _l)\n{\n\tif (_l)\n\t\tclient()->startNetwork();\n\telse\n\t\tclient()->stopNetwork();\n}\n\nuint64_t QEthereum::txCountAt(Address _a) const\n{\n\treturn (uint64_t)client()->postState().transactionsFrom(_a);\n}\n\nunsigned QEthereum::peerCount() const\n{\n\treturn client()->peerCount();\n}\n\nvoid QEthereum::transact(Secret _secret, Address _dest, u256 _amount)\n{\n\tclient()->transact(_secret, _dest, _amount);\n}\n\nMain::Main(QWidget *parent) :\n\tQMainWindow(parent),\n\tui(new Ui::Main)\n{\n\tsetWindowFlags(Qt::Window);\n\tui->setupUi(this);\n\tsetWindowIcon(QIcon(\":\/Ethereum.png\"));\n\n\tg_main = this;\n\n\tm_client.reset(new Client(\"Walleth\", Address(), eth::getDataDir() + \"\/Walleth\"));\n\n\tqRegisterMetaType(\"eth::u256\");\n\tqRegisterMetaType(\"eth::KeyPair\");\n\tqRegisterMetaType(\"eth::Secret\");\n\tqRegisterMetaType(\"eth::Address\");\n\tqRegisterMetaType(\"QAccount*\");\n\tqRegisterMetaType(\"QEthereum*\");\n\n\tqmlRegisterType(\"org.ethereum\", 1, 0, \"Ethereum\");\n\tqmlRegisterType(\"org.ethereum\", 1, 0, \"Account\");\n\tqmlRegisterSingletonType(\"org.ethereum\", 1, 0, \"Balance\", QEthereum::constructU256Helper);\n\tqmlRegisterSingletonType(\"org.ethereum\", 1, 0, \"Key\", QEthereum::constructKeyHelper);\n\n\t\/*\n\tui->librariesView->setModel(m_libraryMan);\n\tui->graphsView->setModel(m_graphMan);\n\t*\/\n\n\tm_view = new QQuickView();\n\n\/\/\tQQmlContext* context = m_view->rootContext();\n\/\/\tcontext->setContextProperty(\"u256\", new U256Helper(this));\n\n\tm_view->setSource(QUrl(\"qrc:\/Simple.qml\"));\n\n\tQWidget* w = QWidget::createWindowContainer(m_view);\n\tm_view->setResizeMode(QQuickView::SizeRootObjectToView);\n\tui->fullDisplay->insertWidget(0, w);\n\tm_view->create();\n\n\/\/\tm_timelinesItem = m_view->rootObject()->findChild(\"timelines\");\n\n\treadSettings();\n\trefresh();\n\n\tm_refreshNetwork = new QTimer(this);\n\tconnect(m_refreshNetwork, SIGNAL(timeout()), SLOT(refreshNetwork()));\n\tm_refreshNetwork->start(1000);\n\n\tconnect(this, SIGNAL(changed()), SLOT(refresh()));\n\n\tconnect(&m_webCtrl, &QNetworkAccessManager::finished, [&](QNetworkReply* _r)\n\t{\n\t\tm_servers = QString::fromUtf8(_r->readAll()).split(\"\\n\", QString::SkipEmptyParts);\n\t\tif (m_servers.size())\n\t\t{\n\t\t\tui->net->setChecked(true);\n\t\t\ton_net_triggered(true);\n\t\t}\n\t});\n\tQNetworkRequest r(QUrl(\"http:\/\/www.ethereum.org\/servers.poc3.txt\"));\n\tr.setHeader(QNetworkRequest::UserAgentHeader, \"Mozilla\/5.0 (Windows NT 6.3; WOW64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/33.0.1712.0 Safari\/537.36\");\n\tm_webCtrl.get(r);\n\tsrand(time(0));\n\n\tstartTimer(200);\n\n\tstatusBar()->addPermanentWidget(ui->balance);\n\tstatusBar()->addPermanentWidget(ui->peerCount);\n\tstatusBar()->addPermanentWidget(ui->blockCount);\n}\n\nMain::~Main()\n{\n\twriteSettings();\n}\n\nvoid Main::timerEvent(QTimerEvent *)\n{\n\tif (m_client->changed())\n\t\tchanged();\n}\n\nvoid Main::on_about_triggered()\n{\n\tQMessageBox::about(this, \"About Walleth PoC-\" + QString(ETH_QUOTED(ETH_VERSION)).section('.', 1, 1), \"Walleth\/v\" ETH_QUOTED(ETH_VERSION) \"\/\" ETH_QUOTED(ETH_BUILD_TYPE) \"\/\" ETH_QUOTED(ETH_BUILD_PLATFORM) \"\\nBy Gav Wood, 2014.\\nBased on a design by Vitalik Buterin.\\n\\nTeam Ethereum++ includes: Tim Hughes, Eric Lombrozo, Marko Simovic, Alex Leverington and several others.\");\n}\n\nvoid Main::writeSettings()\n{\n\tQSettings s(\"ethereum\", \"walleth\");\n\tQByteArray b;\n\tb.resize(sizeof(Secret) * m_myKeys.size());\n\tauto p = b.data();\n\tfor (auto i: m_myKeys)\n\t{\n\t\tmemcpy(p, &(i.secret()), sizeof(Secret));\n\t\tp += sizeof(Secret);\n\t}\n\ts.setValue(\"address\", b);\n\n\ts.setValue(\"upnp\", ui->upnp->isChecked());\n\ts.setValue(\"clientName\", m_clientName);\n\ts.setValue(\"idealPeers\", m_idealPeers);\n\ts.setValue(\"port\", m_port);\n\n\tif (client()->peerServer())\n\t{\n\t\tbytes d = client()->peerServer()->savePeers();\n\t\tm_peers = QByteArray((char*)d.data(), (int)d.size());\n\n\t}\n\ts.setValue(\"peers\", m_peers);\n\n\ts.setValue(\"geometry\", saveGeometry());\n\ts.setValue(\"windowState\", saveState());\n}\n\nvoid Main::readSettings()\n{\n\tQSettings s(\"ethereum\", \"walleth\");\n\n\trestoreGeometry(s.value(\"geometry\").toByteArray());\n\trestoreState(s.value(\"windowState\").toByteArray());\n\n\n\tQByteArray b = s.value(\"address\").toByteArray();\n\tif (b.isEmpty())\n\t\tm_myKeys.append(KeyPair::create());\n\telse\n\t{\n\t\th256 k;\n\t\tfor (unsigned i = 0; i < b.size() \/ sizeof(Secret); ++i)\n\t\t{\n\t\t\tmemcpy(&k, b.data() + i * sizeof(Secret), sizeof(Secret));\n\t\t\tm_myKeys.append(KeyPair(k));\n\t\t}\n\t}\n\t\/\/m_eth->setAddress(m_myKeys.last().address());\n\tm_peers = s.value(\"peers\").toByteArray();\n\tui->upnp->setChecked(s.value(\"upnp\", true).toBool());\n\tm_clientName = s.value(\"clientName\", \"\").toString();\n\tm_idealPeers = s.value(\"idealPeers\", 5).toInt();\n\tm_port = s.value(\"port\", 30303).toInt();\n}\n\nvoid Main::refreshNetwork()\n{\n\tauto ps = client()->peers();\n\tui->peerCount->setText(QString::fromStdString(toString(ps.size())) + \" peer(s)\");\n}\n\neth::State const& Main::state() const\n{\n\treturn ui->preview->isChecked() ? client()->postState() : client()->state();\n}\n\nvoid Main::refresh()\n{\n\teth::ClientGuard l(client());\n\tauto const& st = state();\n\n\tauto d = client()->blockChain().details();\n\tauto diff = BlockInfo(client()->blockChain().block()).difficulty;\n\tui->blockCount->setText(QString(\"#%1 @%3 T%2\").arg(d.number).arg(toLog2(d.totalDifficulty)).arg(toLog2(diff)));\n\n\tm_keysChanged = false;\n\tu256 totalBalance = 0;\n\tfor (auto i: m_myKeys)\n\t{\n\t\tu256 b = st.balance(i.address());\n\t\ttotalBalance += b;\n\t}\n\tui->balance->setText(QString::fromStdString(formatBalance(totalBalance)));\n}\n\nvoid Main::on_net_triggered(bool _auto)\n{\n\tstring n = \"Walleth\/v\" ETH_QUOTED(ETH_VERSION);\n\tif (m_clientName.size())\n\t\tn += \"\/\" + m_clientName.toStdString();\n\tn += \"\/\" ETH_QUOTED(ETH_BUILD_TYPE) \"\/\" ETH_QUOTED(ETH_BUILD_PLATFORM);\n\tclient()->setClientVersion(n);\n\tif (ui->net->isChecked())\n\t{\n\t\tif (_auto)\n\t\t{\n\t\t\tQString s = m_servers[rand() % m_servers.size()];\n\t\t\tclient()->startNetwork(m_port, s.section(':', 0, 0).toStdString(), s.section(':', 1).toInt(), NodeMode::Full, m_idealPeers, std::string(), ui->upnp->isChecked());\n\t\t}\n\t\telse\n\t\t\tclient()->startNetwork(m_port, string(), 0, NodeMode::Full, m_idealPeers, std::string(), ui->upnp->isChecked());\n\t\tif (m_peers.size())\n\t\t\tclient()->peerServer()->restorePeers(bytesConstRef((byte*)m_peers.data(), m_peers.size()));\n\t}\n\telse\n\t\tclient()->stopNetwork();\n}\n\nvoid Main::on_connect_triggered()\n{\n\tif (!ui->net->isChecked())\n\t{\n\t\tui->net->setChecked(true);\n\t\ton_net_triggered();\n\t}\n\tbool ok = false;\n\tQString s = QInputDialog::getItem(this, \"Connect to a Network Peer\", \"Enter a peer to which a connection may be made:\", m_servers, m_servers.count() ? rand() % m_servers.count() : 0, true, &ok);\n\tif (ok && s.contains(\":\"))\n\t{\n\t\tstring host = s.section(\":\", 0, 0).toStdString();\n\t\tunsigned short port = s.section(\":\", 1).toInt();\n\t\tclient()->connect(host, port);\n\t}\n}\n\nvoid Main::on_mine_triggered()\n{\n\tif (ui->mine->isChecked())\n\t{\n\t\tclient()->setAddress(m_myKeys.last().address());\n\t\tclient()->startMining();\n\t}\n\telse\n\t\tclient()->stopMining();\n}\n\nvoid Main::on_create_triggered()\n{\n\tm_myKeys.append(KeyPair::create());\n\tm_keysChanged = true;\n}\n\n\/\/ extra bits needed to link on VS\n#ifdef _MSC_VER\n\n\/\/ include moc file, ofuscated to hide from automoc\n#include\\\n\"moc_MainWin.cpp\"\n\n\/\/ specify library dependencies, it's easier to do here than in the project since we can control the \"d\" debug suffix\n#ifdef _DEBUG\n#define QTLIB(x) x\"d.lib\"\n#else \n#define QTLIB(x) x\".lib\"\n#endif\n\n#pragma comment(lib, QTLIB(\"Qt5PlatformSupport\"))\n#pragma comment(lib, QTLIB(\"Qt5Core\"))\n#pragma comment(lib, QTLIB(\"Qt5GUI\"))\n#pragma comment(lib, QTLIB(\"Qt5Widgets\"))\n#pragma comment(lib, QTLIB(\"Qt5Network\"))\n#pragma comment(lib, QTLIB(\"qwindows\"))\n#pragma comment(lib, \"Imm32.lib\")\n#pragma comment(lib, \"opengl32.lib\")\n#pragma comment(lib, \"winmm.lib\")\n\n\n#endif\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n\nnamespace warpcoil\n{\n struct use_future_type\n {\n };\n\n constexpr use_future_type use_future;\n\n namespace detail\n {\n template \n struct future_handler\n {\n std::shared_ptr, Result>> state;\n\n explicit future_handler(use_future_type)\n : state(std::make_shared<\n Si::variant, Result>>())\n {\n }\n\n void operator()(Result result)\n {\n Si::visit(*state,\n [this, &result](Si::unit)\n {\n *state = std::move(result);\n },\n [&result](std::function &handler)\n {\n handler(std::move(result));\n },\n [](Result &)\n {\n SILICIUM_UNREACHABLE();\n });\n }\n };\n }\n\n namespace detail\n {\n template \n struct apply_transform\n {\n template \n static void apply(Transformation &&transform, Input &&input,\n HandleResult &&handle_result)\n {\n std::forward(handle_result)(\n std::forward(transform)(std::forward(input)));\n }\n\n template \n static void apply(Transformation &&transform, HandleResult &&handle_result)\n {\n std::forward(handle_result)(\n std::forward(transform)());\n }\n };\n\n template <>\n struct apply_transform\n {\n template \n static void apply(Transformation &&transform, Input &&input,\n HandleResult &&handle_result)\n {\n std::forward(transform)(std::forward(input));\n std::forward(handle_result)();\n }\n\n template \n static void apply(Transformation &&transform, HandleResult &&handle_result)\n {\n std::forward(transform)();\n std::forward(handle_result)();\n }\n };\n }\n\n template \n struct future\n {\n explicit future(std::function)> wait)\n : _wait(std::move(wait))\n {\n }\n\n template \n auto async_wait(CompletionToken &&token)\n {\n assert(_wait);\n using handler_type =\n typename boost::asio::handler_type::type;\n handler_type handler(std::forward(token));\n boost::asio::async_result result(handler);\n _wait(std::move(handler));\n return result.get();\n }\n\n template \n auto then(Transformation &&transform)\n {\n using transformed_result = decltype(transform(std::declval()));\n auto wait = std::move(_wait);\n assert(!_wait);\n return future(\n [ wait = std::move(wait), transform = std::forward(transform) ](\n std::function on_result) mutable\n {\n wait([\n on_result = std::move(on_result),\n transform = std::forward(transform)\n ](Result intermediate) mutable\n {\n detail::apply_transform::apply(\n std::forward(transform),\n std::forward(intermediate), std::move(on_result));\n });\n });\n }\n\n private:\n std::function)> _wait;\n };\n\n template <>\n struct future\n {\n explicit future(std::function)> wait)\n : _wait(std::move(wait))\n {\n }\n\n template \n auto async_wait(CompletionToken &&token)\n {\n assert(_wait);\n using handler_type = typename boost::asio::handler_type::type;\n handler_type handler(std::forward(token));\n boost::asio::async_result result(handler);\n _wait(std::move(handler));\n return result.get();\n }\n\n template \n auto then(Transformation &&transform)\n {\n using transformed_result = decltype(transform());\n auto wait = std::move(_wait);\n assert(!_wait);\n return future(\n [ wait = std::move(wait), transform = std::forward(transform) ](\n std::function on_result) mutable\n {\n wait([\n on_result = std::move(on_result),\n transform = std::forward(transform)\n ]() mutable\n {\n detail::apply_transform::apply(\n std::forward(transform), std::move(on_result));\n });\n });\n }\n\n private:\n std::function)> _wait;\n };\n\n template \n auto when_all(Futures &&... futures)\n {\n size_t completed = 0;\n return future(std::function)>(std::bind(\n [completed](auto &&on_result, auto &&... futures) mutable\n {\n static constexpr size_t future_count = sizeof...(futures);\n using expand_type = int[];\n expand_type{(futures.async_wait([&completed, on_result]()\n {\n ++completed;\n if (completed == future_count)\n {\n on_result();\n }\n }),\n 0)...};\n },\n std::placeholders::_1, std::forward(futures)...)));\n }\n}\n\nnamespace boost\n{\n namespace asio\n {\n template \n struct async_result>\n {\n using type = warpcoil::future;\n\n explicit async_result(warpcoil::detail::future_handler const &handler)\n : _handler(handler)\n {\n assert(_handler.state);\n }\n\n warpcoil::future get()\n {\n assert(_handler.state);\n return warpcoil::future([state = std::move(_handler.state)](\n std::function handle_result)\n {\n Si::visit(\n *state,\n [&state, &handle_result](Si::unit)\n {\n *state = std::move(handle_result);\n },\n [](std::function &)\n {\n SILICIUM_UNREACHABLE();\n },\n [&handle_result](Result &result)\n {\n handle_result(std::move(result));\n });\n });\n }\n\n private:\n warpcoil::detail::future_handler _handler;\n };\n\n template \n struct handler_type\n {\n using type = warpcoil::detail::future_handler;\n };\n }\n}\ntry to fix GCC build#pragma once\n\n#include \n#include \n#include \n\nnamespace warpcoil\n{\n struct use_future_type\n {\n };\n\n constexpr use_future_type use_future;\n\n namespace detail\n {\n template \n struct future_handler\n {\n std::shared_ptr, Result>> state;\n\n explicit future_handler(use_future_type)\n : state(std::make_shared<\n Si::variant, Result>>())\n {\n }\n\n void operator()(Result result)\n {\n Si::visit(*state,\n [this, &result](Si::unit)\n {\n *state = std::move(result);\n },\n [&result](std::function &handler)\n {\n handler(std::move(result));\n },\n [](Result &)\n {\n SILICIUM_UNREACHABLE();\n });\n }\n };\n }\n\n namespace detail\n {\n template \n struct apply_transform\n {\n template \n static void apply(Transformation &&transform, Input &&input,\n HandleResult &&handle_result)\n {\n std::forward(handle_result)(\n std::forward(transform)(std::forward(input)));\n }\n\n template \n static void apply(Transformation &&transform, HandleResult &&handle_result)\n {\n std::forward(handle_result)(\n std::forward(transform)());\n }\n };\n\n template <>\n struct apply_transform\n {\n template \n static void apply(Transformation &&transform, Input &&input,\n HandleResult &&handle_result)\n {\n std::forward(transform)(std::forward(input));\n std::forward(handle_result)();\n }\n\n template \n static void apply(Transformation &&transform, HandleResult &&handle_result)\n {\n std::forward(transform)();\n std::forward(handle_result)();\n }\n };\n }\n\n template \n struct future\n {\n explicit future(std::function)> wait)\n : _wait(std::move(wait))\n {\n }\n\n template \n auto async_wait(CompletionToken &&token)\n {\n assert(_wait);\n using handler_type =\n typename boost::asio::handler_type::type;\n handler_type handler(std::forward(token));\n boost::asio::async_result result(handler);\n _wait(std::move(handler));\n return result.get();\n }\n\n template \n auto then(Transformation &&transform)\n {\n using transformed_result = decltype(transform(std::declval()));\n auto wait = std::move(_wait);\n assert(!_wait);\n return future(\n [ wait = std::move(wait), transform = std::forward(transform) ](\n std::function on_result) mutable\n {\n wait([\n on_result = std::move(on_result),\n transform = std::forward(transform)\n ](Result intermediate) mutable\n {\n detail::apply_transform::apply(\n std::forward(transform),\n std::forward(intermediate), std::move(on_result));\n });\n });\n }\n\n private:\n std::function)> _wait;\n };\n\n template <>\n struct future\n {\n explicit future(std::function)> wait)\n : _wait(std::move(wait))\n {\n }\n\n template \n auto async_wait(CompletionToken &&token)\n {\n assert(_wait);\n using handler_type = typename boost::asio::handler_type::type;\n handler_type handler(std::forward(token));\n boost::asio::async_result result(handler);\n _wait(std::move(handler));\n return result.get();\n }\n\n template \n auto then(Transformation &&transform)\n {\n using transformed_result = decltype(transform());\n auto wait = std::move(_wait);\n assert(!_wait);\n return future(\n [ wait = std::move(wait), transform = std::forward(transform) ](\n std::function on_result) mutable\n {\n wait([\n on_result = std::move(on_result),\n transform = std::forward(transform)\n ]() mutable\n {\n detail::apply_transform::apply(\n std::forward(transform), std::move(on_result));\n });\n });\n }\n\n private:\n std::function)> _wait;\n };\n\n template \n auto when_all(Futures &&... futures)\n {\n return future(std::function)>(std::bind(\n [](auto &&on_result, auto &&... futures) mutable\n {\n static constexpr size_t future_count = sizeof...(futures);\n using expand_type = int[];\n auto callback = [ completed = std::make_shared(0), on_result ]()\n {\n ++*completed;\n if (*completed == future_count)\n {\n on_result();\n }\n };\n expand_type{(futures.async_wait(callback), 0)...};\n },\n std::placeholders::_1, std::forward(futures)...)));\n }\n}\n\nnamespace boost\n{\n namespace asio\n {\n template \n struct async_result>\n {\n using type = warpcoil::future;\n\n explicit async_result(warpcoil::detail::future_handler const &handler)\n : _handler(handler)\n {\n assert(_handler.state);\n }\n\n warpcoil::future get()\n {\n assert(_handler.state);\n return warpcoil::future([state = std::move(_handler.state)](\n std::function handle_result)\n {\n Si::visit(\n *state,\n [&state, &handle_result](Si::unit)\n {\n *state = std::move(handle_result);\n },\n [](std::function &)\n {\n SILICIUM_UNREACHABLE();\n },\n [&handle_result](Result &result)\n {\n handle_result(std::move(result));\n });\n });\n }\n\n private:\n warpcoil::detail::future_handler _handler;\n };\n\n template \n struct handler_type\n {\n using type = warpcoil::detail::future_handler;\n };\n }\n}\n<|endoftext|>"} {"text":"\/\/ -----------------------------------------------------------------------------\n\/\/ Copyright : (C) 2014 Andreas-C. Bernstein\n\/\/ License : MIT (see the file LICENSE)\n\/\/ Maintainer : Andreas-C. Bernstein \n\/\/ Stability : experimental\n\/\/\n\/\/ Renderer\n\/\/ -----------------------------------------------------------------------------\n\n#include \n#include \"renderer.hpp\"\n\n\/\/#include \"scene.hpp\"\n\nRenderer::Renderer()\n :\n scene_{},\n colorbuffer_(scene_.xres_*scene_.yres_, Color{}),\n ppm_(scene_.xres_, scene_.yres_, \"default.ppm\")\n {}\n\nRenderer::Renderer(Scene scene)\n : \/*width_{scene->xres_}\n , height_{scene->yres_}\n , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))\n , filename_(file)\n , ppm_(width_, height_)*\/\n scene_{scene},\n colorbuffer_(scene.xres_*scene.yres_, Color{}),\n ppm_(scene.xres_, scene.yres_, scene.filename)\n {}\n\n\n\n\/\/0.5 Alpha \/ 2 M_PI\nvoid Renderer::render()\n{\n\n float pic_ymax =2\/scene_.xres_*scene_.yres_;\n\n\/\/float pic_z =1\/(0.5*1.0\/*alpha*\/);\/\/alpha von der camera aus der scene \"angle\"\n\/\/glm::vec3 p1{-1.0,};\n\/\/ height_=(2\/scene.width_);\n\/\/prinzipieller aufbau\n \/*\nwhile (int x = 0; x < width; ++x)\n{\n for (int y = 0; y < height; ++y)\n {\n Pixel p(x,y,pic_z);\n }\n}*\/\n\n\n\n const std::size_t checkersize = 20;\n\n float distance=(((45\/360)*2*3.1415)*0.5)\/2*3.1415;\n glm::vec3 mittelp{0.0,0.0,-3.0};\n float rad = 1;\n Sphere kugel{mittelp, rad};\n glm::vec3 onedirection{0.0,0.0,-1.0};\n int height_= scene_.yres_;\n int width_= scene_.xres_;\n\n\n for (unsigned y = 0; y < height_; ++y) {\n \/\/std::cout << y << \"\\n\";\n int h = height_\/2;\n\n for (unsigned x = 0; x < width_; ++x) {\n int w = -(width_\/2);\n \/\/std::cout << \"x = \" << x << \"\\n\";\n \/\/\n \/\/ p.color = raytrace(ray, depth);\n glm::vec3 origin{w,h,0.0};\n Ray camray{origin, onedirection};\n Pixel p(x,y);\n Hit hitteter=kugel.intersect(camray);\n if (hitteter.hit_ == true){\n p.color = Color(1.0,1.0,1.0);\n } else{\n p.color = Color(0.0,0.0,0.0);\n }\n write(p);\n ++w;\n }\n --h;\n }\n ppm_.save(scene_.filename);\n std::cout << \"saved file in: \" << scene_.filename << \" amazing! \\n\";\n}\n\nvoid Renderer::write(Pixel const& p)\n{\n \/\/ flip pixels, because of opengl glDrawPixels\n size_t buf_pos = (scene_.xres_*p.y + p.x);\n if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) {\n std::cerr << \"Fatal Error Renderer::write(Pixel p) : \"\n << \"pixel out of ppm_ : \"\n << (int)p.x << \",\" << (int)p.y\n << std::endl;\n } else {\n colorbuffer_[buf_pos] = p.color;\n }\n \/\/std::cout << scene_.xres_ << \" \" << scene_.yres_ << \"\\n\";\n ppm_.write(p);\n}\nFirst picgit add .. !\/\/ -----------------------------------------------------------------------------\n\/\/ Copyright : (C) 2014 Andreas-C. Bernstein\n\/\/ License : MIT (see the file LICENSE)\n\/\/ Maintainer : Andreas-C. Bernstein \n\/\/ Stability : experimental\n\/\/\n\/\/ Renderer\n\/\/ -----------------------------------------------------------------------------\n\n#include \n#include \"renderer.hpp\"\n\n\/\/#include \"scene.hpp\"\n\nRenderer::Renderer()\n :\n scene_{},\n colorbuffer_(scene_.xres_*scene_.yres_, Color{}),\n ppm_(scene_.xres_, scene_.yres_, \"default.ppm\")\n {}\n\nRenderer::Renderer(Scene scene)\n : \/*width_{scene->xres_}\n , height_{scene->yres_}\n , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))\n , filename_(file)\n , ppm_(width_, height_)*\/\n scene_{scene},\n colorbuffer_(scene.xres_*scene.yres_, Color{}),\n ppm_(scene.xres_, scene.yres_, scene.filename)\n {}\n\n\n\n\/\/0.5 Alpha \/ 2 M_PI\nvoid Renderer::render()\n{\n\n float pic_ymax =2\/scene_.xres_*scene_.yres_;\n\n\/\/float pic_z =1\/(0.5*1.0\/*alpha*\/);\/\/alpha von der camera aus der scene \"angle\"\n\/\/glm::vec3 p1{-1.0,};\n\/\/ height_=(2\/scene.width_);\n\/\/prinzipieller aufbau\n \/*\nwhile (int x = 0; x < width; ++x)\n{\n for (int y = 0; y < height; ++y)\n {\n Pixel p(x,y,pic_z);\n }\n}*\/\n\n\n\n\/\/ const std::size_t checkersize = 20;\n\n float distance=(((45\/360)*2*3.1415)*0.5)\/2*3.1415;\n glm::vec3 mittelp{0.0,0.0,-3.0};\n float rad = 1;\n Sphere kugel{mittelp, rad};\n glm::vec3 onedirection{0.0,0.0,-1.0};\n int height_= scene_.yres_;\n int width_= scene_.xres_;\n\n float h = height_\/2;\n for (unsigned y = 0; y < height_; ++y) {\n \/\/std::cout << y << \"\\n\";\n\n\n float w = -width_\/2;\n for (unsigned x = 0; x < width_; ++x) {\n \/\/std::cout << \"x = \" << x << \"\\n\";\n \/\/\n \/\/ p.color = raytrace(ray, depth);\n glm::vec3 origin{w\/(width_\/2),h\/(height_\/2),0.0};\n std::cout <<\"origin vec \" << origin.x << \", \" << origin.y << \", \" << origin.z << \" \\n\";\n Ray camray{origin, onedirection};\n Pixel p(x,y);\n Hit hitteter=kugel.intersect(camray);\n if (hitteter.hit_ == true){\n p.color = Color(1.0,1.0,1.0);\n } else{\n p.color = Color(0.0,0.0,0.0);\n }\n write(p);\n ++w;\n }\n --h;\n }\n ppm_.save(scene_.filename);\n std::cout << \"saved file in: \" << scene_.filename << \" amazing! \\n\";\n}\n\nvoid Renderer::write(Pixel const& p)\n{\n \/\/ flip pixels, because of opengl glDrawPixels\n size_t buf_pos = (scene_.xres_*p.y + p.x);\n if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) {\n std::cerr << \"Fatal Error Renderer::write(Pixel p) : \"\n << \"pixel out of ppm_ : \"\n << (int)p.x << \",\" << (int)p.y\n << std::endl;\n } else {\n colorbuffer_[buf_pos] = p.color;\n }\n \/\/std::cout << scene_.xres_ << \" \" << scene_.yres_ << \"\\n\";\n ppm_.write(p);\n}\n<|endoftext|>"} {"text":"#include \"server\/http\/reply.hpp\"\n\n#include \n\nnamespace osrm\n{\nnamespace server\n{\nnamespace http\n{\n\nconst char ok_html[] = \"\";\nconst char bad_request_html[] = \"{\\\"status\\\": 400,\\\"status_message\\\":\\\"Bad Request\\\"}\";\nconst char internal_server_error_html[] =\n \"{\\\"status\\\": 500,\\\"status_message\\\":\\\"Internal Server Error\\\"}\";\nconst char seperators[] = {':', ' '};\nconst char crlf[] = {'\\r', '\\n'};\nconst std::string http_ok_string = \"HTTP\/1.0 200 OK\\r\\n\";\nconst std::string http_bad_request_string = \"HTTP\/1.0 400 Bad Request\\r\\n\";\nconst std::string http_internal_server_error_string = \"HTTP\/1.0 500 Internal Server Error\\r\\n\";\n\nvoid reply::set_size(const std::size_t size)\n{\n for (header &h : headers)\n {\n if (\"Content-Length\" == h.name)\n {\n h.value = std::to_string(size);\n }\n }\n}\n\nvoid reply::set_uncompressed_size() { set_size(content.size()); }\n\nstd::vector reply::to_buffers()\n{\n std::vector buffers;\n buffers.push_back(status_to_buffer(status));\n for (const header &h : headers)\n {\n buffers.push_back(boost::asio::buffer(h.name));\n buffers.push_back(boost::asio::buffer(seperators));\n buffers.push_back(boost::asio::buffer(h.value));\n buffers.push_back(boost::asio::buffer(crlf));\n }\n buffers.push_back(boost::asio::buffer(crlf));\n buffers.push_back(boost::asio::buffer(content));\n return buffers;\n}\n\nstd::vector reply::headers_to_buffers()\n{\n std::vector buffers;\n buffers.push_back(status_to_buffer(status));\n for (const header ¤t_header : headers)\n {\n buffers.push_back(boost::asio::buffer(current_header.name));\n buffers.push_back(boost::asio::buffer(seperators));\n buffers.push_back(boost::asio::buffer(current_header.value));\n buffers.push_back(boost::asio::buffer(crlf));\n }\n buffers.push_back(boost::asio::buffer(crlf));\n return buffers;\n}\n\nreply reply::stock_reply(const reply::status_type status)\n{\n reply reply;\n reply.status = status;\n reply.content.clear();\n\n const std::string status_string = reply.status_to_string(status);\n reply.content.insert(reply.content.end(), status_string.begin(), status_string.end());\n reply.headers.emplace_back(\"Access-Control-Allow-Origin\", \"*\");\n reply.headers.emplace_back(\"Content-Length\", std::to_string(reply.content.size()));\n reply.headers.emplace_back(\"Content-Type\", \"text\/html\");\n return reply;\n}\n\nstd::string reply::status_to_string(const reply::status_type status)\n{\n if (reply::ok == status)\n {\n return ok_html;\n }\n if (reply::bad_request == status)\n {\n return bad_request_html;\n }\n return internal_server_error_html;\n}\n\nboost::asio::const_buffer reply::status_to_buffer(const reply::status_type status)\n{\n if (reply::ok == status)\n {\n return boost::asio::buffer(http_ok_string);\n }\n if (reply::internal_server_error == status)\n {\n return boost::asio::buffer(http_internal_server_error_string);\n }\n return boost::asio::buffer(http_bad_request_string);\n}\n\nreply::reply() : status(ok) {}\n}\n}\n}\nSend the Connection: close response header#include \"server\/http\/reply.hpp\"\n\n#include \n\nnamespace osrm\n{\nnamespace server\n{\nnamespace http\n{\n\nconst char ok_html[] = \"\";\nconst char bad_request_html[] = \"{\\\"status\\\": 400,\\\"status_message\\\":\\\"Bad Request\\\"}\";\nconst char internal_server_error_html[] =\n \"{\\\"status\\\": 500,\\\"status_message\\\":\\\"Internal Server Error\\\"}\";\nconst char seperators[] = {':', ' '};\nconst char crlf[] = {'\\r', '\\n'};\nconst std::string http_ok_string = \"HTTP\/1.0 200 OK\\r\\n\";\nconst std::string http_bad_request_string = \"HTTP\/1.0 400 Bad Request\\r\\n\";\nconst std::string http_internal_server_error_string = \"HTTP\/1.0 500 Internal Server Error\\r\\n\";\n\nvoid reply::set_size(const std::size_t size)\n{\n for (header &h : headers)\n {\n if (\"Content-Length\" == h.name)\n {\n h.value = std::to_string(size);\n }\n }\n}\n\nvoid reply::set_uncompressed_size() { set_size(content.size()); }\n\nstd::vector reply::to_buffers()\n{\n std::vector buffers;\n buffers.push_back(status_to_buffer(status));\n for (const header &h : headers)\n {\n buffers.push_back(boost::asio::buffer(h.name));\n buffers.push_back(boost::asio::buffer(seperators));\n buffers.push_back(boost::asio::buffer(h.value));\n buffers.push_back(boost::asio::buffer(crlf));\n }\n buffers.push_back(boost::asio::buffer(crlf));\n buffers.push_back(boost::asio::buffer(content));\n return buffers;\n}\n\nstd::vector reply::headers_to_buffers()\n{\n std::vector buffers;\n buffers.push_back(status_to_buffer(status));\n for (const header ¤t_header : headers)\n {\n buffers.push_back(boost::asio::buffer(current_header.name));\n buffers.push_back(boost::asio::buffer(seperators));\n buffers.push_back(boost::asio::buffer(current_header.value));\n buffers.push_back(boost::asio::buffer(crlf));\n }\n buffers.push_back(boost::asio::buffer(crlf));\n return buffers;\n}\n\nreply reply::stock_reply(const reply::status_type status)\n{\n reply reply;\n reply.status = status;\n reply.content.clear();\n\n const std::string status_string = reply.status_to_string(status);\n reply.content.insert(reply.content.end(), status_string.begin(), status_string.end());\n reply.headers.emplace_back(\"Access-Control-Allow-Origin\", \"*\");\n reply.headers.emplace_back(\"Content-Length\", std::to_string(reply.content.size()));\n reply.headers.emplace_back(\"Content-Type\", \"text\/html\");\n return reply;\n}\n\nstd::string reply::status_to_string(const reply::status_type status)\n{\n if (reply::ok == status)\n {\n return ok_html;\n }\n if (reply::bad_request == status)\n {\n return bad_request_html;\n }\n return internal_server_error_html;\n}\n\nboost::asio::const_buffer reply::status_to_buffer(const reply::status_type status)\n{\n if (reply::ok == status)\n {\n return boost::asio::buffer(http_ok_string);\n }\n if (reply::internal_server_error == status)\n {\n return boost::asio::buffer(http_internal_server_error_string);\n }\n return boost::asio::buffer(http_bad_request_string);\n}\n\nreply::reply() : status(ok)\n{\n \/\/ We do not currently support keep alive. Always set 'Connection: close'.\n headers.emplace_back(\"Connection\", \"close\");\n}\n}\n}\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkChartParallelCoordinates.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkChartParallelCoordinates.h\"\n\n#include \"vtkContext2D.h\"\n#include \"vtkBrush.h\"\n#include \"vtkPen.h\"\n#include \"vtkContextScene.h\"\n#include \"vtkTextProperty.h\"\n#include \"vtkAxis.h\"\n#include \"vtkPlotParallelCoordinates.h\"\n#include \"vtkContextMapper2D.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTable.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkTransform2D.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkCommand.h\"\n#include \"vtkAnnotationLink.h\"\n#include \"vtkSelection.h\"\n#include \"vtkSelectionNode.h\"\n\n#include \"vtkstd\/vector\"\n#include \"vtkstd\/algorithm\"\n\n\/\/ Minimal storage class for STL containers etc.\nclass vtkChartParallelCoordinates::Private\n{\npublic:\n Private()\n {\n this->Plot = vtkSmartPointer::New();\n this->Transform = vtkSmartPointer::New();\n this->CurrentAxis = -1;\n }\n ~Private()\n {\n for (vtkstd::vector::iterator it = this->Axes.begin();\n it != this->Axes.end(); ++it)\n {\n (*it)->Delete();\n }\n }\n vtkSmartPointer Plot;\n vtkSmartPointer Transform;\n vtkstd::vector Axes;\n vtkstd::vector AxesSelections;\n int CurrentAxis;\n};\n\n\/\/-----------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------\nvtkStandardNewMacro(vtkChartParallelCoordinates);\n\n\/\/-----------------------------------------------------------------------------\nvtkChartParallelCoordinates::vtkChartParallelCoordinates()\n{\n this->Storage = new vtkChartParallelCoordinates::Private;\n this->Storage->Plot->SetParent(this);\n this->GeometryValid = false;\n this->Selection = vtkIdTypeArray::New();\n this->Storage->Plot->SetSelection(this->Selection);\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkChartParallelCoordinates::~vtkChartParallelCoordinates()\n{\n this->Storage->Plot->SetSelection(NULL);\n delete this->Storage;\n this->Selection->Delete();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::Update()\n{\n vtkTable* table = this->Storage->Plot->GetData()->GetInput();\n if (!table)\n {\n return;\n }\n\n if (table->GetMTime() < this->BuildTime)\n {\n return;\n }\n\n \/\/ Now we have a table, set up the axes accordingly, clear and build.\n if (static_cast(this->Storage->Axes.size()) != table->GetNumberOfColumns())\n {\n for (vtkstd::vector::iterator it = this->Storage->Axes.begin();\n it != this->Storage->Axes.end(); ++it)\n {\n (*it)->Delete();\n }\n this->Storage->Axes.clear();\n\n for (int i = 0; i < table->GetNumberOfColumns(); ++i)\n {\n vtkAxis* axis = vtkAxis::New();\n axis->SetPosition(vtkAxis::PARALLEL);\n this->Storage->Axes.push_back(axis);\n }\n }\n\n \/\/ Now set up their ranges and locations\n for (int i = 0; i < table->GetNumberOfColumns(); ++i)\n {\n double range[2];\n vtkDataArray* array = vtkDataArray::SafeDownCast(table->GetColumn(i));\n if (array)\n {\n array->GetRange(range);\n }\n vtkAxis* axis = this->Storage->Axes[i];\n axis->SetMinimum(range[0]);\n axis->SetMaximum(range[1]);\n axis->SetTitle(table->GetColumnName(i));\n }\n this->Storage->AxesSelections.clear();\n\n this->Storage->AxesSelections.resize(this->Storage->Axes.size());\n this->GeometryValid = false;\n this->BuildTime.Modified();\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::Paint(vtkContext2D *painter)\n{\n if (this->GetScene()->GetViewWidth() == 0 ||\n this->GetScene()->GetViewHeight() == 0 ||\n !this->Visible || !this->Storage->Plot->GetVisible())\n {\n \/\/ The geometry of the chart must be valid before anything can be drawn\n return false;\n }\n\n this->Update();\n this->UpdateGeometry();\n\n \/\/ Handle selections\n vtkIdTypeArray *idArray = 0;\n if (this->AnnotationLink)\n {\n vtkSelection *selection = this->AnnotationLink->GetCurrentSelection();\n if (selection->GetNumberOfNodes() &&\n this->AnnotationLink->GetMTime() > this->Storage->Plot->GetMTime())\n {\n vtkSelectionNode *node = selection->GetNode(0);\n idArray = vtkIdTypeArray::SafeDownCast(node->GetSelectionList());\n this->Storage->Plot->SetSelection(idArray);\n }\n }\n else\n {\n vtkDebugMacro(\"No annotation link set.\");\n }\n\n painter->PushMatrix();\n painter->SetTransform(this->Storage->Transform);\n this->Storage->Plot->Paint(painter);\n painter->PopMatrix();\n\n \/\/ Now we have a table, set up the axes accordingly, clear and build.\n for (vtkstd::vector::iterator it = this->Storage->Axes.begin();\n it != this->Storage->Axes.end(); ++it)\n {\n (*it)->Paint(painter);\n }\n\n \/\/ If there is a selected axis, draw the highlight\n if (this->Storage->CurrentAxis >= 0)\n {\n painter->GetBrush()->SetColor(200, 200, 200, 200);\n vtkAxis* axis = this->Storage->Axes[this->Storage->CurrentAxis];\n painter->DrawRect(axis->GetPoint1()[0]-10, this->Point1[1],\n 20, this->Point2[1]-this->Point1[1]);\n }\n\n \/\/ Now draw our active selections\n for (size_t i = 0; i < this->Storage->AxesSelections.size(); ++i)\n {\n vtkRectf &rect = this->Storage->AxesSelections[i];\n if (rect.Height() != 0.0f)\n {\n painter->GetBrush()->SetColor(200, 20, 20, 220);\n painter->DrawRect(rect.X(), rect.Y(), rect.Width(), rect.Height());\n }\n }\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkPlot * vtkChartParallelCoordinates::AddPlot(int)\n{\n return NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::RemovePlot(vtkIdType)\n{\n return false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::ClearPlots()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkPlot* vtkChartParallelCoordinates::GetPlot(vtkIdType)\n{\n return this->Storage->Plot;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdType vtkChartParallelCoordinates::GetNumberOfPlots()\n{\n return 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkAxis* vtkChartParallelCoordinates::GetAxis(int index)\n{\n if (index < this->GetNumberOfAxes())\n {\n return this->Storage->Axes[index];\n }\n else\n {\n return NULL;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdType vtkChartParallelCoordinates::GetNumberOfAxes()\n{\n return this->Storage->Axes.size();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::UpdateGeometry()\n{\n int geometry[] = { this->GetScene()->GetViewWidth(),\n this->GetScene()->GetViewHeight() };\n\n if (geometry[0] != this->Geometry[0] || geometry[1] != this->Geometry[1] ||\n !this->GeometryValid)\n {\n \/\/ Take up the entire window right now, this could be made configurable\n this->SetGeometry(geometry);\n this->SetBorders(60, 20, 20, 50);\n\n \/\/ Iterate through the axes and set them up to span the chart area.\n int xStep = (this->Point2[0] - this->Point1[0]) \/\n (static_cast(this->Storage->Axes.size())-1);\n int x = this->Point1[0];\n\n for (size_t i = 0; i < this->Storage->Axes.size(); ++i)\n {\n vtkAxis* axis = this->Storage->Axes[i];\n axis->SetPoint1(x, this->Point1[1]);\n axis->SetPoint2(x, this->Point2[1]);\n axis->AutoScale();\n axis->Update();\n x += xStep;\n }\n\n this->GeometryValid = true;\n \/\/ Cause the plot transform to be recalculated if necessary\n this->CalculatePlotTransform();\n this->Storage->Plot->Update();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::CalculatePlotTransform()\n{\n \/\/ In the case of parallel coordinates everything is plotted in a normalized\n \/\/ system, where the range is from 0.0 to 1.0 in the y axis, and in screen\n \/\/ coordinates along the x axis.\n if (!this->Storage->Axes.size())\n {\n return;\n }\n\n vtkAxis* axis = this->Storage->Axes[0];\n float *min = axis->GetPoint1();\n float *max = axis->GetPoint2();\n float yScale = 1.0f \/ (max[1] - min[1]);\n\n this->Storage->Transform->Identity();\n this->Storage->Transform->Translate(0, axis->GetPoint1()[1]);\n \/\/ Get the scale for the plot area from the x and y axes\n this->Storage->Transform->Scale(1.0, 1.0 \/ yScale);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::RecalculateBounds()\n{\n return;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::Hit(const vtkContextMouseEvent &mouse)\n{\n if (mouse.ScreenPos[0] > this->Point1[0]-10 &&\n mouse.ScreenPos[0] < this->Point2[0]+10 &&\n mouse.ScreenPos[1] > this->Point1[1] &&\n mouse.ScreenPos[1] < this->Point2[1])\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseEnterEvent(const vtkContextMouseEvent &)\n{\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseMoveEvent(const vtkContextMouseEvent &mouse)\n{\n if (mouse.Button == 0)\n {\n \/\/ If an axis is selected, then lets try to narrow down a selection...\n if (this->Storage->CurrentAxis >= 0)\n {\n vtkAxis* axis = this->Storage->Axes[this->Storage->CurrentAxis];\n vtkRectf &rect = this->Storage->AxesSelections[this->Storage->CurrentAxis];\n if (mouse.ScenePos[1] > axis->GetPoint2()[1])\n {\n rect.SetHeight(axis->GetPoint2()[1] - rect.Y());\n }\n else if (mouse.ScenePos[1] < axis->GetPoint1()[1])\n {\n rect.SetHeight(axis->GetPoint1()[1] - rect.Y());\n }\n else\n {\n rect.SetHeight(mouse.ScenePos[1] - rect.Y());\n }\n }\n this->Scene->SetDirty(true);\n\n }\n else if (mouse.Button == 2)\n {\n }\n else if (mouse.Button < 0)\n {\n\n }\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseLeaveEvent(const vtkContextMouseEvent &)\n{\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseButtonPressEvent(const vtkContextMouseEvent\n &mouse)\n{\n if (mouse.Button == 0)\n {\n \/\/ Select an axis if we are within range\n if (mouse.ScenePos[1] > this->Point1[1] &&\n mouse.ScenePos[1] < this->Point2[1])\n {\n \/\/ Iterate over the axes, see if we are within 10 pixels of an axis\n for (size_t i = 0; i < this->Storage->Axes.size(); ++i)\n {\n vtkAxis* axis = this->Storage->Axes[i];\n if (axis->GetPoint1()[0]-10 < mouse.ScenePos[0] &&\n axis->GetPoint1()[0]+10 > mouse.ScenePos[0])\n {\n this->Storage->CurrentAxis = static_cast(i);\n this->Scene->SetDirty(true);\n this->Storage->AxesSelections[i].Set(axis->GetPoint1()[0]-5,\n mouse.ScenePos[1],\n 10, 0);\n return true;\n }\n }\n }\n this->Storage->CurrentAxis = -1;\n this->Scene->SetDirty(true);\n return false;\n return true;\n }\n else if (mouse.Button == 2)\n {\n \/\/ Right mouse button - zoom box\n\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseButtonReleaseEvent(const vtkContextMouseEvent\n &mouse)\n{\n if (mouse.Button == 0)\n {\n if (this->Storage->CurrentAxis >= 0)\n {\n vtkAxis* axis = this->Storage->Axes[this->Storage->CurrentAxis];\n vtkRectf &rect = this->Storage->AxesSelections[this->Storage->CurrentAxis];\n\n \/\/ Set the final mouse position\n if (mouse.ScenePos[1] > axis->GetPoint2()[1])\n {\n rect.SetHeight(axis->GetPoint2()[1] - rect.Y());\n }\n else if (mouse.ScenePos[1] < axis->GetPoint1()[1])\n {\n rect.SetHeight(axis->GetPoint1()[1] - rect.Y());\n }\n else\n {\n rect.SetHeight(mouse.ScenePos[1] - rect.Y());\n }\n\n if (rect.Height() == 0.0f)\n {\n \/\/ Reset the axes.\n this->Storage->Plot->ResetSelectionRange();\n\n \/\/ Now set the remaining selections that were kept\n float low = 0.0;\n float high = 0.0;\n for (size_t i = 0; i < this->Storage->AxesSelections.size(); ++i)\n {\n vtkRectf &rect2 = this->Storage->AxesSelections[i];\n if (rect2.Height() != 0.0f)\n {\n if (rect2.Height() > 0.0f)\n {\n low = rect2.Y();\n high = rect2.Y() + rect2.Height();\n }\n else\n {\n low = rect2.Y() + rect2.Height();\n high = rect2.Y();\n }\n low -= this->Storage->Transform->GetMatrix()->GetElement(1, 2);\n low \/= this->Storage->Transform->GetMatrix()->GetElement(1, 1);\n high -= this->Storage->Transform->GetMatrix()->GetElement(1, 2);\n high \/= this->Storage->Transform->GetMatrix()->GetElement(1, 1);\n\n \/\/ Process the selected range and display this\n this->Storage->Plot->SetSelectionRange(static_cast(i),\n low, high);\n }\n }\n }\n else\n {\n float low = 0.0;\n float high = 0.0;\n if (rect.Height() > 0.0f)\n {\n low = rect.Y();\n high = rect.Y() + rect.Height();\n }\n else\n {\n low = rect.Y() + rect.Height();\n high = rect.Y();\n }\n low -= this->Storage->Transform->GetMatrix()->GetElement(1, 2);\n low \/= this->Storage->Transform->GetMatrix()->GetElement(1, 1);\n high -= this->Storage->Transform->GetMatrix()->GetElement(1, 2);\n high \/= this->Storage->Transform->GetMatrix()->GetElement(1, 1);\n \/\/ Process the selected range and display this\n this->Storage->Plot->SetSelectionRange(this->Storage->CurrentAxis,\n low, high);\n }\n\n this->Scene->SetDirty(true);\n }\n if (this->AnnotationLink)\n {\n vtkSelection* selection = vtkSelection::New();\n vtkSelectionNode* node = vtkSelectionNode::New();\n selection->AddNode(node);\n node->SetSelectionList(this->Storage->Plot->GetSelection());\n this->AnnotationLink->SetCurrentSelection(selection);\n selection->Delete();\n node->Delete();\n }\n this->InvokeEvent(vtkCommand::SelectionChangedEvent);\n }\n return false;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseWheelEvent(const vtkContextMouseEvent &,\n int)\n{\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::PrintSelf(ostream &os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\nBUG: Tightly couple the selections to the axes.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkChartParallelCoordinates.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\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 notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkChartParallelCoordinates.h\"\n\n#include \"vtkContext2D.h\"\n#include \"vtkBrush.h\"\n#include \"vtkPen.h\"\n#include \"vtkContextScene.h\"\n#include \"vtkTextProperty.h\"\n#include \"vtkAxis.h\"\n#include \"vtkPlotParallelCoordinates.h\"\n#include \"vtkContextMapper2D.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTable.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkTransform2D.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkCommand.h\"\n#include \"vtkAnnotationLink.h\"\n#include \"vtkSelection.h\"\n#include \"vtkSelectionNode.h\"\n\n#include \"vtkstd\/vector\"\n#include \"vtkstd\/algorithm\"\n\n\/\/ Minimal storage class for STL containers etc.\nclass vtkChartParallelCoordinates::Private\n{\npublic:\n Private()\n {\n this->Plot = vtkSmartPointer::New();\n this->Transform = vtkSmartPointer::New();\n this->CurrentAxis = -1;\n }\n ~Private()\n {\n for (vtkstd::vector::iterator it = this->Axes.begin();\n it != this->Axes.end(); ++it)\n {\n (*it)->Delete();\n }\n }\n vtkSmartPointer Plot;\n vtkSmartPointer Transform;\n vtkstd::vector Axes;\n vtkstd::vector > AxesSelections;\n int CurrentAxis;\n};\n\n\/\/-----------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------\nvtkStandardNewMacro(vtkChartParallelCoordinates);\n\n\/\/-----------------------------------------------------------------------------\nvtkChartParallelCoordinates::vtkChartParallelCoordinates()\n{\n this->Storage = new vtkChartParallelCoordinates::Private;\n this->Storage->Plot->SetParent(this);\n this->GeometryValid = false;\n this->Selection = vtkIdTypeArray::New();\n this->Storage->Plot->SetSelection(this->Selection);\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkChartParallelCoordinates::~vtkChartParallelCoordinates()\n{\n this->Storage->Plot->SetSelection(NULL);\n delete this->Storage;\n this->Selection->Delete();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::Update()\n{\n vtkTable* table = this->Storage->Plot->GetData()->GetInput();\n if (!table)\n {\n return;\n }\n\n if (table->GetMTime() < this->BuildTime)\n {\n return;\n }\n\n \/\/ Now we have a table, set up the axes accordingly, clear and build.\n if (static_cast(this->Storage->Axes.size()) != table->GetNumberOfColumns())\n {\n for (vtkstd::vector::iterator it = this->Storage->Axes.begin();\n it != this->Storage->Axes.end(); ++it)\n {\n (*it)->Delete();\n }\n this->Storage->Axes.clear();\n\n for (int i = 0; i < table->GetNumberOfColumns(); ++i)\n {\n vtkAxis* axis = vtkAxis::New();\n axis->SetPosition(vtkAxis::PARALLEL);\n this->Storage->Axes.push_back(axis);\n }\n }\n\n \/\/ Now set up their ranges and locations\n for (int i = 0; i < table->GetNumberOfColumns(); ++i)\n {\n double range[2];\n vtkDataArray* array = vtkDataArray::SafeDownCast(table->GetColumn(i));\n if (array)\n {\n array->GetRange(range);\n }\n vtkAxis* axis = this->Storage->Axes[i];\n axis->SetMinimum(range[0]);\n axis->SetMaximum(range[1]);\n axis->SetTitle(table->GetColumnName(i));\n }\n this->Storage->AxesSelections.clear();\n\n this->Storage->AxesSelections.resize(this->Storage->Axes.size());\n this->GeometryValid = false;\n this->BuildTime.Modified();\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::Paint(vtkContext2D *painter)\n{\n if (this->GetScene()->GetViewWidth() == 0 ||\n this->GetScene()->GetViewHeight() == 0 ||\n !this->Visible || !this->Storage->Plot->GetVisible())\n {\n \/\/ The geometry of the chart must be valid before anything can be drawn\n return false;\n }\n\n this->Update();\n this->UpdateGeometry();\n\n \/\/ Handle selections\n vtkIdTypeArray *idArray = 0;\n if (this->AnnotationLink)\n {\n vtkSelection *selection = this->AnnotationLink->GetCurrentSelection();\n if (selection->GetNumberOfNodes() &&\n this->AnnotationLink->GetMTime() > this->Storage->Plot->GetMTime())\n {\n vtkSelectionNode *node = selection->GetNode(0);\n idArray = vtkIdTypeArray::SafeDownCast(node->GetSelectionList());\n this->Storage->Plot->SetSelection(idArray);\n }\n }\n else\n {\n vtkDebugMacro(\"No annotation link set.\");\n }\n\n painter->PushMatrix();\n painter->SetTransform(this->Storage->Transform);\n this->Storage->Plot->Paint(painter);\n painter->PopMatrix();\n\n \/\/ Now we have a table, set up the axes accordingly, clear and build.\n for (vtkstd::vector::iterator it = this->Storage->Axes.begin();\n it != this->Storage->Axes.end(); ++it)\n {\n (*it)->Paint(painter);\n }\n\n \/\/ If there is a selected axis, draw the highlight\n if (this->Storage->CurrentAxis >= 0)\n {\n painter->GetBrush()->SetColor(200, 200, 200, 200);\n vtkAxis* axis = this->Storage->Axes[this->Storage->CurrentAxis];\n painter->DrawRect(axis->GetPoint1()[0]-10, this->Point1[1],\n 20, this->Point2[1]-this->Point1[1]);\n }\n\n \/\/ Now draw our active selections\n for (size_t i = 0; i < this->Storage->AxesSelections.size(); ++i)\n {\n vtkVector &range = this->Storage->AxesSelections[i];\n if (range[0] != range[1])\n {\n painter->GetBrush()->SetColor(200, 20, 20, 220);\n float x = this->Storage->Axes[i]->GetPoint1()[0] - 5;\n float y = range[0];\n y *= this->Storage->Transform->GetMatrix()->GetElement(1, 1);\n y += this->Storage->Transform->GetMatrix()->GetElement(1, 2);\n float height = range[1] - range[0];\n height *= this->Storage->Transform->GetMatrix()->GetElement(1, 1);\n\n painter->DrawRect(x, y, 10, height);\n }\n }\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkPlot * vtkChartParallelCoordinates::AddPlot(int)\n{\n return NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::RemovePlot(vtkIdType)\n{\n return false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::ClearPlots()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkPlot* vtkChartParallelCoordinates::GetPlot(vtkIdType)\n{\n return this->Storage->Plot;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdType vtkChartParallelCoordinates::GetNumberOfPlots()\n{\n return 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkAxis* vtkChartParallelCoordinates::GetAxis(int index)\n{\n if (index < this->GetNumberOfAxes())\n {\n return this->Storage->Axes[index];\n }\n else\n {\n return NULL;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdType vtkChartParallelCoordinates::GetNumberOfAxes()\n{\n return this->Storage->Axes.size();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::UpdateGeometry()\n{\n vtkVector2i geometry(this->GetScene()->GetViewWidth(),\n this->GetScene()->GetViewHeight());\n\n if (geometry.X() != this->Geometry[0] || geometry.Y() != this->Geometry[1] ||\n !this->GeometryValid)\n {\n \/\/ Take up the entire window right now, this could be made configurable\n this->SetGeometry(geometry.GetData());\n this->SetBorders(60, 20, 20, 50);\n\n \/\/ Iterate through the axes and set them up to span the chart area.\n int xStep = (this->Point2[0] - this->Point1[0]) \/\n (static_cast(this->Storage->Axes.size())-1);\n int x = this->Point1[0];\n\n for (size_t i = 0; i < this->Storage->Axes.size(); ++i)\n {\n vtkAxis* axis = this->Storage->Axes[i];\n axis->SetPoint1(x, this->Point1[1]);\n axis->SetPoint2(x, this->Point2[1]);\n axis->AutoScale();\n axis->Update();\n x += xStep;\n }\n\n this->GeometryValid = true;\n \/\/ Cause the plot transform to be recalculated if necessary\n this->CalculatePlotTransform();\n this->Storage->Plot->Update();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::CalculatePlotTransform()\n{\n \/\/ In the case of parallel coordinates everything is plotted in a normalized\n \/\/ system, where the range is from 0.0 to 1.0 in the y axis, and in screen\n \/\/ coordinates along the x axis.\n if (!this->Storage->Axes.size())\n {\n return;\n }\n\n vtkAxis* axis = this->Storage->Axes[0];\n float *min = axis->GetPoint1();\n float *max = axis->GetPoint2();\n float yScale = 1.0f \/ (max[1] - min[1]);\n\n this->Storage->Transform->Identity();\n this->Storage->Transform->Translate(0, axis->GetPoint1()[1]);\n \/\/ Get the scale for the plot area from the x and y axes\n this->Storage->Transform->Scale(1.0, 1.0 \/ yScale);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::RecalculateBounds()\n{\n return;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::Hit(const vtkContextMouseEvent &mouse)\n{\n if (mouse.ScreenPos[0] > this->Point1[0]-10 &&\n mouse.ScreenPos[0] < this->Point2[0]+10 &&\n mouse.ScreenPos[1] > this->Point1[1] &&\n mouse.ScreenPos[1] < this->Point2[1])\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseEnterEvent(const vtkContextMouseEvent &)\n{\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseMoveEvent(const vtkContextMouseEvent &mouse)\n{\n if (mouse.Button == vtkContextMouseEvent::LEFT_BUTTON)\n {\n \/\/ If an axis is selected, then lets try to narrow down a selection...\n if (this->Storage->CurrentAxis >= 0)\n {\n vtkVector &range =\n this->Storage->AxesSelections[this->Storage->CurrentAxis];\n\n \/\/ Normalize the coordinates\n float current = mouse.ScenePos.Y();\n current -= this->Storage->Transform->GetMatrix()->GetElement(1, 2);\n current \/= this->Storage->Transform->GetMatrix()->GetElement(1, 1);\n\n if (current > 1.0f)\n {\n range[1] = 1.0f;\n }\n else if (current < 0.0f)\n {\n range[1] = 0.0f;\n }\n else\n {\n range[1] = current;\n }\n }\n this->Scene->SetDirty(true);\n }\n else if (mouse.Button == 2)\n {\n }\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseLeaveEvent(const vtkContextMouseEvent &)\n{\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseButtonPressEvent(const vtkContextMouseEvent\n &mouse)\n{\n if (mouse.Button == vtkContextMouseEvent::LEFT_BUTTON)\n {\n \/\/ Select an axis if we are within range\n if (mouse.ScenePos[1] > this->Point1[1] &&\n mouse.ScenePos[1] < this->Point2[1])\n {\n \/\/ Iterate over the axes, see if we are within 10 pixels of an axis\n for (size_t i = 0; i < this->Storage->Axes.size(); ++i)\n {\n vtkAxis* axis = this->Storage->Axes[i];\n if (axis->GetPoint1()[0]-10 < mouse.ScenePos[0] &&\n axis->GetPoint1()[0]+10 > mouse.ScenePos[0])\n {\n this->Storage->CurrentAxis = static_cast(i);\n this->Scene->SetDirty(true);\n\n \/\/ Transform into normalized coordinates\n float low = mouse.ScenePos[1];\n low -= this->Storage->Transform->GetMatrix()->GetElement(1, 2);\n low \/= this->Storage->Transform->GetMatrix()->GetElement(1, 1);\n this->Storage->AxesSelections[i][0] = low;\n this->Storage->AxesSelections[i][1] = low;\n return true;\n }\n }\n }\n this->Storage->CurrentAxis = -1;\n this->Scene->SetDirty(true);\n return true;\n }\n else if (mouse.Button == 2)\n {\n \/\/ Right mouse button - zoom box\n\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseButtonReleaseEvent(const vtkContextMouseEvent\n &mouse)\n{\n if (mouse.Button == vtkContextMouseEvent::LEFT_BUTTON)\n {\n if (this->Storage->CurrentAxis >= 0)\n {\n vtkVector &range =\n this->Storage->AxesSelections[this->Storage->CurrentAxis];\n\n float final = mouse.ScenePos[1];\n final -= this->Storage->Transform->GetMatrix()->GetElement(1, 2);\n final \/= this->Storage->Transform->GetMatrix()->GetElement(1, 1);\n\n \/\/ Set the final mouse position\n if (final > 1.0)\n {\n range[1] = 1.0;\n }\n else if (final < 0.0)\n {\n range[1] = 0.0;\n }\n else\n {\n range[1] = final;\n }\n\n if (range[0] == range[1])\n {\n \/\/ Reset the axes.\n this->Storage->Plot->ResetSelectionRange();\n\n \/\/ Now set the remaining selections that were kept\n for (size_t i = 0; i < this->Storage->AxesSelections.size(); ++i)\n {\n vtkVector &range2 = this->Storage->AxesSelections[i];\n if (range2[0] != range2[1])\n {\n \/\/ Process the selected range and display this\n if (range[0] < range[1])\n {\n this->Storage->Plot->SetSelectionRange(static_cast(i),\n range2[0], range2[1]);\n }\n else\n {\n this->Storage->Plot->SetSelectionRange(static_cast(i),\n range2[1], range2[0]);\n }\n }\n }\n }\n else\n {\n \/\/ Add a new selection\n if (range[0] < range[1])\n {\n this->Storage->Plot->SetSelectionRange(this->Storage->CurrentAxis,\n range[0], range[1]);\n }\n else\n {\n this->Storage->Plot->SetSelectionRange(this->Storage->CurrentAxis,\n range[1], range[0]);\n }\n }\n\n if (this->AnnotationLink)\n {\n vtkSelection* selection = vtkSelection::New();\n vtkSelectionNode* node = vtkSelectionNode::New();\n selection->AddNode(node);\n node->SetSelectionList(this->Storage->Plot->GetSelection());\n this->AnnotationLink->SetCurrentSelection(selection);\n selection->Delete();\n node->Delete();\n }\n this->InvokeEvent(vtkCommand::SelectionChangedEvent);\n this->Scene->SetDirty(true);\n }\n }\n return false;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool vtkChartParallelCoordinates::MouseWheelEvent(const vtkContextMouseEvent &,\n int)\n{\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkChartParallelCoordinates::PrintSelf(ostream &os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\n<|endoftext|>"} {"text":"\/\/ -----------------------------------------------------------------------------\n\/\/ Copyright : (C) 2014 Andreas-C. Bernstein\n\/\/ License : MIT (see the file LICENSE)\n\/\/ Maintainer : Andreas-C. Bernstein \n\/\/ Stability : experimental\n\/\/\n\/\/ Renderer\n\/\/ -----------------------------------------------------------------------------\n#define _USE_MATH_DEFINES\n\n#include \"renderer.hpp\"\n#include \"SDFloader.hpp\"\n#include \"ray.hpp\"\n#include \n#include \n\nusing namespace std;\n\nRenderer::Renderer(unsigned w, unsigned h)\n : width_(w)\n , height_(h)\n , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))\n , scenefile_(\"scene.sdf\")\n , ppm_(width_, height_)\n ,finished_(false)\n{\n scene_ = SDFLoader::load(scenefile_);\n}\n\nRenderer::Renderer(unsigned w, unsigned h, string const& scenefile)\n : width_(w)\n , height_(h)\n , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))\n , scenefile_(scenefile)\n , ppm_(width_, height_)\n ,finished_(false)\n{\n scene_ = SDFLoader::load(scenefile);\n}\n\nvoid Renderer::render() {\n if (width_0){\/\/SSAA\n int samples = sqrt(scene_.antialiase);\n for (int xAA=1;xAA0)\n p.color \/=scene_.antialiase;\n else\n p.color +=getColor(ray);\n write(p);\n }\n }\n ppm_.save(scene_.outputFile);\n finished_ = true;\n } else {\n cout << \"no root found!\"<intersect(ray) );\n\n if (intersection.hit){\/\/if intersection happened\n clr +=scene_.amb*intersection.material.getKa();\/\/ambient light\n \n \/\/starting from the intersection go to every light source\n for(auto lightIt = scene_.lights.begin(); lightIt != scene_.lights.end(); lightIt++) {\n auto light = lightIt->second;\n \/\/a ray pointing to the current light source\n auto lightRay = Ray(\n intersection.ray.origin, \/\/start at intersection point\n glm::normalize(light.GetPos()-intersection.ray.origin)\/\/l=IL =L-I \n );\n lightRay.maxt = glm::length(light.GetPos()-lightRay.origin);\n \n \/\/shaddow\n auto lighintersect = scene_.renderObjects[\"root\"]->intersect(lightRay);\n if (!(lighintersect.hit)){\/\/check if intersec between p and light source\n \/\/diffuse light\n double fDiffuse = glm::dot(lightRay.direction, intersection.ray.direction);\/\/l*n\n fDiffuse = fDiffuse < 0 ? 0 : fDiffuse;\/\/allow no negative diffuse light\n\n clr += light.GetDiff()\/\/get light color\n * intersection.material.getKd()\/\/multiply by material, (l_p * k_d)\n * fDiffuse\n * intersection.material.getOpacity();\n \n \n auto r = glm::normalize(\n glm::reflect(\n lightRay.direction,\n intersection.ray.direction\n )\n );\n Color spec = light.GetDiff()\n * intersection.material.getKs()\n * glm::pow(\n glm::dot(r, glm::normalize(ray.direction)),\n intersection.material.getM()\n );\/\/(l*r)^m\n if (spec.r<0) spec.r=0;\n if (spec.g<0) spec.g=0;\n if (spec.b<0) spec.b=0;\n clr +=spec*intersection.material.getOpacity(); \n \n \/\/refraction\n if (intersection.material.getOpacity()<1.0f){\n auto refrdir = glm::refract(ray.direction, intersection.ray.direction, intersection.material.getRefraction());\n clr += getColor(\n Ray(\n intersection.ray.origin, \/\/start at intersection point\n refrdir\n )\n )*(1.0f-intersection.material.getOpacity());\n }\n\n }\n }\n }\n return clr;\n}\n\nvoid Renderer::write(Pixel const& p) {\n \/\/ flip pixels, because of opengl glDrawPixels\n size_t buf_pos = (width_*p.y + p.x);\n if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) {\n cerr << \"Fatal Error Renderer::write(Pixel p) : \"\n << \"pixel out of ppm_ : \"\n << (int)p.x << \",\" << (int)p.y\n << endl;\n } else {\n colorbuffer_[buf_pos] = p.color;\n }\n\n ppm_.write(p);\n}\nrefraction also in shadow\/\/ -----------------------------------------------------------------------------\n\/\/ Copyright : (C) 2014 Andreas-C. Bernstein\n\/\/ License : MIT (see the file LICENSE)\n\/\/ Maintainer : Andreas-C. Bernstein \n\/\/ Stability : experimental\n\/\/\n\/\/ Renderer\n\/\/ -----------------------------------------------------------------------------\n#define _USE_MATH_DEFINES\n\n#include \"renderer.hpp\"\n#include \"SDFloader.hpp\"\n#include \"ray.hpp\"\n#include \n#include \n\nusing namespace std;\n\nRenderer::Renderer(unsigned w, unsigned h)\n : width_(w)\n , height_(h)\n , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))\n , scenefile_(\"scene.sdf\")\n , ppm_(width_, height_)\n ,finished_(false)\n{\n scene_ = SDFLoader::load(scenefile_);\n}\n\nRenderer::Renderer(unsigned w, unsigned h, string const& scenefile)\n : width_(w)\n , height_(h)\n , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))\n , scenefile_(scenefile)\n , ppm_(width_, height_)\n ,finished_(false)\n{\n scene_ = SDFLoader::load(scenefile);\n}\n\nvoid Renderer::render() {\n if (width_0){\/\/SSAA\n int samples = sqrt(scene_.antialiase);\n for (int xAA=1;xAA0)\n p.color \/=scene_.antialiase;\n else\n p.color +=getColor(ray);\n write(p);\n }\n }\n ppm_.save(scene_.outputFile);\n finished_ = true;\n } else {\n cout << \"no root found!\"<intersect(ray) );\n\n if (intersection.hit){\/\/if intersection happened\n clr +=scene_.amb*intersection.material.getKa();\/\/ambient light\n \n \/\/starting from the intersection go to every light source\n for(auto lightIt = scene_.lights.begin(); lightIt != scene_.lights.end(); lightIt++) {\n auto light = lightIt->second;\n \/\/a ray pointing to the current light source\n auto lightRay = Ray(\n intersection.ray.origin, \/\/start at intersection point\n glm::normalize(light.GetPos()-intersection.ray.origin)\/\/l=IL =L-I \n );\n lightRay.maxt = glm::length(light.GetPos()-lightRay.origin);\n \n \/\/shaddow\n auto lighintersect = scene_.renderObjects[\"root\"]->intersect(lightRay);\n if (!(lighintersect.hit)){\/\/check if intersec between p and light source\n \/\/diffuse light\n double fDiffuse = glm::dot(lightRay.direction, intersection.ray.direction);\/\/l*n\n fDiffuse = fDiffuse < 0 ? 0 : fDiffuse;\/\/allow no negative diffuse light\n\n clr += light.GetDiff()\/\/get light color\n * intersection.material.getKd()\/\/multiply by material, (l_p * k_d)\n * fDiffuse\n * intersection.material.getOpacity();\n \n \n auto r = glm::normalize(\n glm::reflect(\n lightRay.direction,\n intersection.ray.direction\n )\n );\n Color spec = light.GetDiff()\n * intersection.material.getKs()\n * glm::pow(\n glm::dot(r, glm::normalize(ray.direction)),\n intersection.material.getM()\n );\/\/(l*r)^m\n if (spec.r<0) spec.r=0;\n if (spec.g<0) spec.g=0;\n if (spec.b<0) spec.b=0;\n clr +=spec*intersection.material.getOpacity(); \n }\n \/\/refraction\n if (intersection.material.getOpacity()<1.0f){\n auto refrdir = glm::refract(ray.direction, intersection.ray.direction, intersection.material.getRefraction());\n clr += getColor(\n Ray(\n intersection.ray.origin, \/\/start at intersection point\n refrdir\n )\n )*(1.0f-intersection.material.getOpacity());\n }\n }\n }\n return clr;\n}\n\nvoid Renderer::write(Pixel const& p) {\n \/\/ flip pixels, because of opengl glDrawPixels\n size_t buf_pos = (width_*p.y + p.x);\n if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) {\n cerr << \"Fatal Error Renderer::write(Pixel p) : \"\n << \"pixel out of ppm_ : \"\n << (int)p.x << \",\" << (int)p.y\n << endl;\n } else {\n colorbuffer_[buf_pos] = p.color;\n }\n\n ppm_.write(p);\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of OpenCV project.\n\/\/ It is subject to the license terms in the LICENSE file found in the top-level directory\n\/\/ of this distribution and at http:\/\/opencv.org\/license.html.\n\n#ifndef OPENCV_VERSION_HPP\n#define OPENCV_VERSION_HPP\n\n#define CV_VERSION_MAJOR 3\n#define CV_VERSION_MINOR 4\n#define CV_VERSION_REVISION 15\n#define CV_VERSION_STATUS \"-pre\"\n\n#define CVAUX_STR_EXP(__A) #__A\n#define CVAUX_STR(__A) CVAUX_STR_EXP(__A)\n\n#define CVAUX_STRW_EXP(__A) L ## #__A\n#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A)\n\n#define CV_VERSION CVAUX_STR(CV_VERSION_MAJOR) \".\" CVAUX_STR(CV_VERSION_MINOR) \".\" CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS\n\n\/* old style version constants*\/\n#define CV_MAJOR_VERSION CV_VERSION_MAJOR\n#define CV_MINOR_VERSION CV_VERSION_MINOR\n#define CV_SUBMINOR_VERSION CV_VERSION_REVISION\n\n#endif \/\/ OPENCV_VERSION_HPP\nrelease: OpenCV 3.4.15\/\/ This file is part of OpenCV project.\n\/\/ It is subject to the license terms in the LICENSE file found in the top-level directory\n\/\/ of this distribution and at http:\/\/opencv.org\/license.html.\n\n#ifndef OPENCV_VERSION_HPP\n#define OPENCV_VERSION_HPP\n\n#define CV_VERSION_MAJOR 3\n#define CV_VERSION_MINOR 4\n#define CV_VERSION_REVISION 15\n#define CV_VERSION_STATUS \"\"\n\n#define CVAUX_STR_EXP(__A) #__A\n#define CVAUX_STR(__A) CVAUX_STR_EXP(__A)\n\n#define CVAUX_STRW_EXP(__A) L ## #__A\n#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A)\n\n#define CV_VERSION CVAUX_STR(CV_VERSION_MAJOR) \".\" CVAUX_STR(CV_VERSION_MINOR) \".\" CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS\n\n\/* old style version constants*\/\n#define CV_MAJOR_VERSION CV_VERSION_MAJOR\n#define CV_MINOR_VERSION CV_VERSION_MINOR\n#define CV_SUBMINOR_VERSION CV_VERSION_REVISION\n\n#endif \/\/ OPENCV_VERSION_HPP\n<|endoftext|>"} {"text":"\/** \\file mysql_diff_schemas.cc\n * \\brief A tool for listing the differences between two schemas.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2020 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"FileUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nstd::string ExtractBackQuotedString(const std::string &s) {\n auto ch(s.cbegin());\n if (unlikely(*ch != '`'))\n LOG_ERROR(\"\\\"\" + s + \"\\\" does not start with a backtick!\");\n ++ch;\n\n std::string extracted_string;\n while (ch != s.cend() and *ch != '`')\n extracted_string += *ch++;\n if (unlikely(ch == s.cend()))\n LOG_ERROR(\"\\\"\" + s + \"\\\" does not end with a backtick!\");\n\n return extracted_string;\n}\n\n\ninline bool SchemaLineIsLessThan(const std::string &line1, const std::string &line2) {\n if ((*line1.c_str() == '`') != (*line2.c_str() == '`'))\n return *line1.c_str() == '`';\n\n return line1 < line2;\n}\n\n\nvoid LoadSchema(const std::string &filename, std::map> * const table_name_to_schema_map) {\n std::string current_table;\n std::vector current_schema;\n for (auto line : FileUtil::ReadLines(filename)) {\n StringUtil::Trim(&line);\n if (StringUtil::StartsWith(line, \"CREATE TABLE \")) {\n if (not current_table.empty()) {\n std::sort(current_schema.begin(), current_schema.end(), SchemaLineIsLessThan);\n (*table_name_to_schema_map)[current_table] = current_schema;\n }\n current_table = ExtractBackQuotedString(line.substr(__builtin_strlen(\"CREATE TABLE \")));\n current_schema.clear();\n } else {\n if (line[line.length() - 1] == ',')\n line = line.substr(0, line.length() - 1);\n current_schema.emplace_back(line);\n }\n }\n if (not current_schema.empty()) {\n std::sort(current_schema.begin(), current_schema.end(), SchemaLineIsLessThan);\n (*table_name_to_schema_map)[current_table] = current_schema;\n }\n}\n\n\nstd::set FindLinesStartingWithPrefix(const std::vector &lines, const std::string &prefix) {\n std::set matching_lines;\n for (const auto &line : lines) {\n if (StringUtil::StartsWith(line, prefix))\n matching_lines.emplace(line);\n }\n return matching_lines;\n}\n\n\n\/\/ Reports differences for lines that start w\/ \"prefix\" for tables w\/ the identical names.\nvoid CompareTables(const std::string &prefix, const std::map> &table_name_to_schema_map1,\n const std::map> &table_name_to_schema_map2)\n{\n for (const auto &table_name1_and_schema1 : table_name_to_schema_map1) {\n const auto &table_name1(table_name1_and_schema1.first);\n const auto table_name2_and_schema2(table_name_to_schema_map2.find(table_name1));\n if (table_name2_and_schema2 == table_name_to_schema_map2.cend())\n continue;\n const auto &schema2(table_name2_and_schema2->second);\n\n const std::set matching_lines_in_table1(FindLinesStartingWithPrefix(table_name1_and_schema1.second, prefix));\n for (const auto &matching_line_in_table1 : matching_lines_in_table1) {\n const auto matching_line_in_schema2(std::find(schema2.cbegin(), schema2.cend(), matching_line_in_table1));\n if (matching_line_in_schema2 == schema2.cend())\n std::cout << matching_line_in_table1 << \" is missing in 2nd schema for table \" << table_name1 << '\\n';\n }\n for (const auto &line_in_table2 : schema2) {\n if (StringUtil::StartsWith(line_in_table2, prefix)\n and matching_lines_in_table1.find(line_in_table2) == matching_lines_in_table1.cend())\n std::cout << line_in_table2 << \" is missing in 1st schema for table \" << table_name1 << '\\n';\n }\n }\n}\n\n\nclass StartsWith {\n std::string prefix_;\npublic:\n explicit StartsWith(const std::string &prefix): prefix_(prefix) { }\n bool operator ()(const std::string &line) const { return StringUtil::StartsWith(line, prefix_); }\n};\n\n\nclass StartsWithColumnName: public StartsWith {\npublic:\n explicit StartsWithColumnName(const std::string &reference_column_name): StartsWith(\"`\" + reference_column_name + \"`\") { }\n};\n\n\nvoid CompareTableOptions(const std::map> &table_name_to_schema_map1,\n const std::map> &table_name_to_schema_map2)\n{\n for (const auto &table_name1_and_schema1 : table_name_to_schema_map1) {\n const auto &table_name1(table_name1_and_schema1.first);\n const auto table_name2_and_schema2(table_name_to_schema_map2.find(table_name1));\n if (table_name2_and_schema2 == table_name_to_schema_map2.cend())\n continue;\n\n const auto &schema1(table_name1_and_schema1.second);\n const auto table_options1(std::find_if(schema1.cbegin(), schema1.cend(), StartsWith(\") \")));\n if (unlikely(table_options1 == schema1.cend()))\n LOG_ERROR(\"No table options line for table \\\"\" + table_name1 + \"\\\" found in 1st schema!\");\n\n const auto &schema2(table_name2_and_schema2->second);\n const auto table_options2(std::find_if(schema2.cbegin(), schema2.cend(), StartsWith(\") \")));\n if (unlikely(table_options2 == schema2.cend()))\n LOG_ERROR(\"No table options line for table \\\"\" + table_name1 + \"\\\" found in 2nd schema!\");\n\n static RegexMatcher * const auto_increment_matcher(RegexMatcher::RegexMatcherFactoryOrDie(\"\\\\s*AUTO_INCREMENT=\\\\d+\"));\n const std::string cleaned_table_options1(auto_increment_matcher->replaceAll(table_options1->substr(2), \"\"));\n const std::string cleaned_table_options2(auto_increment_matcher->replaceAll(table_options2->substr(2), \"\"));\n\n if (cleaned_table_options1 != cleaned_table_options2)\n std::cerr << \"Table options differ for \" << table_name1 << \": \" << cleaned_table_options1 << \" -> \"\n << cleaned_table_options2 << '\\n';\n }\n}\n\n\nvoid ReportUnknownLines(const std::string &schema, const std::map> &table_name_to_schema_map) {\n static const std::vector KNOWN_LINE_PREFIXES{ \"KEY\", \"PRIMARY KEY\", \"UNIQUE KEY\", \"CONSTRAINT\", \" )\" };\n\n for (const auto &table_name_and_schema : table_name_to_schema_map) {\n for (const auto &line : table_name_and_schema.second) {\n bool found_a_known_prefix(false);\n for (const auto &known_prefix : KNOWN_LINE_PREFIXES) {\n if (StringUtil::StartsWith(line, known_prefix)) {\n found_a_known_prefix = true;\n break;\n }\n }\n\n if (not found_a_known_prefix)\n LOG_ERROR(\"Unknown line type in \" + schema + \", table \" + table_name_and_schema.first + \": \" + line);\n }\n }\n}\n\n\nvoid DiffSchemas(const std::map> &table_name_to_schema_map1,\n const std::map> &table_name_to_schema_map2)\n{\n std::set already_processed_table_names;\n for (const auto &table_name1_and_schema1 : table_name_to_schema_map1) {\n const auto &table_name1(table_name1_and_schema1.first);\n already_processed_table_names.emplace(table_name1);\n const auto table_name2_and_schema2(table_name_to_schema_map2.find(table_name1));\n if (table_name2_and_schema2 == table_name_to_schema_map2.cend()) {\n std::cout << \"Table was deleted: \" << table_name1 << '\\n';\n continue;\n }\n\n const auto &schema1(table_name1_and_schema1.second);\n const auto &schema2(table_name2_and_schema2->second);\n\n \/\/ Compare column definitions first:\n const auto last_column_def1(std::find_if(schema1.crbegin(), schema1.crend(),\n [](const std::string &line){ return not line.empty() and line[0] == '`'; }));\n const auto last_column_def2(std::find_if(schema2.crbegin(), schema2.crend(),\n [](const std::string &line){ return not line.empty() and line[0] == '`'; }));\n\n std::set already_processed_column_names;\n for (auto column_def1(schema1.cbegin()); column_def1 != last_column_def1.base(); ++column_def1) {\n const auto column_name1(ExtractBackQuotedString(*column_def1));\n already_processed_column_names.emplace(column_name1);\n const auto column_def2(std::find_if(schema2.cbegin(), last_column_def2.base(), StartsWithColumnName(column_name1)));\n if (column_def2 == last_column_def2.base())\n std::cout << \"Column does not exist in 1st schema: \" << table_name1 << '.' << column_name1 << '\\n';\n else if (*column_def1 != *column_def2)\n std::cout << \"Column definition differs between the 1st and 2nd schemas (\" << table_name1 << \"): \" << *column_def1 << \" -> \" << *column_def2 << '\\n';\n }\n\n for (auto column_def2(schema2.cbegin()); column_def2 != last_column_def2.base(); ++column_def2) {\n const auto column_name2(ExtractBackQuotedString(*column_def2));\n if (already_processed_column_names.find(column_name2) == already_processed_column_names.cend())\n std::cout << \"Column exists only in 2nd schema: \" << table_name1 << '.' << column_name2 << '\\n';\n }\n }\n\n std::set schema2_tables;\n for (const auto &table_name2_and_schema2 : table_name_to_schema_map2) {\n const auto &table_name2(table_name2_and_schema2.first);\n schema2_tables.emplace(table_name2);\n if (already_processed_table_names.find(table_name2) == already_processed_table_names.cend())\n std::cout << \"Table exists only in 1st schema: \" << table_name2 << '\\n';\n }\n for (const auto &table_name1_and_schema1 : table_name_to_schema_map1) {\n const auto &table_name1(table_name1_and_schema1.first);\n if (schema2_tables.find(table_name1) == schema2_tables.cend())\n std::cout << \"Table exist only in 2st schema: \" << table_name1 << '\\n';\n }\n\n CompareTables(\"KEY\", table_name_to_schema_map1, table_name_to_schema_map2);\n CompareTables(\"PRIMARY KEY\", table_name_to_schema_map1, table_name_to_schema_map2);\n CompareTables(\"UNIQUE KEY\", table_name_to_schema_map1, table_name_to_schema_map2);\n CompareTables(\"CONSTRAINT\", table_name_to_schema_map1, table_name_to_schema_map2);\n CompareTableOptions(table_name_to_schema_map1, table_name_to_schema_map2);\n\n ReportUnknownLines(\"schema1\", table_name_to_schema_map1);\n ReportUnknownLines(\"schema2\", table_name_to_schema_map1);\n}\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 3)\n ::Usage(\"schema1 schema2\\n\"\n \"Please note that this tool may not work particularly well if you do not use output from mysql_list_tables\");\n\n std::map> table_name_to_schema_map1;\n LoadSchema(argv[1], &table_name_to_schema_map1);\n\n std::map> table_name_to_schema_map2;\n LoadSchema(argv[2], &table_name_to_schema_map2);\n\n DiffSchemas(table_name_to_schema_map1, table_name_to_schema_map2);\n\n return EXIT_SUCCESS;\n}\nmysql_schema_diff: fix for ReportUnknownLines (ignore regular columns + table ends)\/** \\file mysql_diff_schemas.cc\n * \\brief A tool for listing the differences between two schemas.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2020 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"FileUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nstd::string ExtractBackQuotedString(const std::string &s) {\n auto ch(s.cbegin());\n if (unlikely(*ch != '`'))\n LOG_ERROR(\"\\\"\" + s + \"\\\" does not start with a backtick!\");\n ++ch;\n\n std::string extracted_string;\n while (ch != s.cend() and *ch != '`')\n extracted_string += *ch++;\n if (unlikely(ch == s.cend()))\n LOG_ERROR(\"\\\"\" + s + \"\\\" does not end with a backtick!\");\n\n return extracted_string;\n}\n\n\ninline bool SchemaLineIsLessThan(const std::string &line1, const std::string &line2) {\n if ((*line1.c_str() == '`') != (*line2.c_str() == '`'))\n return *line1.c_str() == '`';\n\n return line1 < line2;\n}\n\n\nvoid LoadSchema(const std::string &filename, std::map> * const table_name_to_schema_map) {\n std::string current_table;\n std::vector current_schema;\n for (auto line : FileUtil::ReadLines(filename)) {\n StringUtil::Trim(&line);\n if (StringUtil::StartsWith(line, \"CREATE TABLE \")) {\n if (not current_table.empty()) {\n std::sort(current_schema.begin(), current_schema.end(), SchemaLineIsLessThan);\n (*table_name_to_schema_map)[current_table] = current_schema;\n }\n current_table = ExtractBackQuotedString(line.substr(__builtin_strlen(\"CREATE TABLE \")));\n current_schema.clear();\n } else {\n if (line[line.length() - 1] == ',')\n line = line.substr(0, line.length() - 1);\n current_schema.emplace_back(line);\n }\n }\n if (not current_schema.empty()) {\n std::sort(current_schema.begin(), current_schema.end(), SchemaLineIsLessThan);\n (*table_name_to_schema_map)[current_table] = current_schema;\n }\n}\n\n\nstd::vector FindLinesStartingWithPrefix(const std::vector &lines, const std::string &prefix) {\n std::vector matching_lines;\n for (const auto &line : lines) {\n if (StringUtil::StartsWith(line, prefix))\n matching_lines.emplace_back(line);\n }\n return matching_lines;\n}\n\n\n\/\/ Reports differences for lines that start w\/ \"prefix\" for tables w\/ the identical names.\nvoid CompareTables(const std::string &prefix, const std::map> &table_name_to_schema_map1,\n const std::map> &table_name_to_schema_map2)\n{\n for (const auto &table_name1_and_schema1 : table_name_to_schema_map1) {\n const auto &table_name1(table_name1_and_schema1.first);\n const auto table_name2_and_schema2(table_name_to_schema_map2.find(table_name1));\n if (table_name2_and_schema2 == table_name_to_schema_map2.cend())\n continue;\n const auto &schema2(table_name2_and_schema2->second);\n\n const auto matching_lines_in_table1(FindLinesStartingWithPrefix(table_name1_and_schema1.second, prefix));\n for (const auto &matching_line_in_table1 : matching_lines_in_table1) {\n const auto matching_line_in_schema2(std::find(schema2.cbegin(), schema2.cend(), matching_line_in_table1));\n if (matching_line_in_schema2 == schema2.cend())\n std::cout << matching_line_in_table1 << \" is missing in 2nd schema for table \" << table_name1 << '\\n';\n }\n for (const auto &line_in_table2 : schema2) {\n if (StringUtil::StartsWith(line_in_table2, prefix)\n and std::find(matching_lines_in_table1.cbegin(), matching_lines_in_table1.cend(), line_in_table2) == matching_lines_in_table1.cend())\n std::cout << line_in_table2 << \" is missing in 1st schema for table \" << table_name1 << '\\n';\n }\n }\n}\n\n\nclass StartsWith {\n std::string prefix_;\npublic:\n explicit StartsWith(const std::string &prefix): prefix_(prefix) { }\n bool operator ()(const std::string &line) const { return StringUtil::StartsWith(line, prefix_); }\n};\n\n\nclass StartsWithColumnName: public StartsWith {\npublic:\n explicit StartsWithColumnName(const std::string &reference_column_name): StartsWith(\"`\" + reference_column_name + \"`\") { }\n};\n\n\nvoid CompareTableOptions(const std::map> &table_name_to_schema_map1,\n const std::map> &table_name_to_schema_map2)\n{\n for (const auto &table_name1_and_schema1 : table_name_to_schema_map1) {\n const auto &table_name1(table_name1_and_schema1.first);\n const auto table_name2_and_schema2(table_name_to_schema_map2.find(table_name1));\n if (table_name2_and_schema2 == table_name_to_schema_map2.cend())\n continue;\n\n const auto &schema1(table_name1_and_schema1.second);\n const auto table_options1(std::find_if(schema1.cbegin(), schema1.cend(), StartsWith(\") \")));\n if (unlikely(table_options1 == schema1.cend()))\n LOG_ERROR(\"No table options line for table \\\"\" + table_name1 + \"\\\" found in 1st schema!\");\n\n const auto &schema2(table_name2_and_schema2->second);\n const auto table_options2(std::find_if(schema2.cbegin(), schema2.cend(), StartsWith(\") \")));\n if (unlikely(table_options2 == schema2.cend()))\n LOG_ERROR(\"No table options line for table \\\"\" + table_name1 + \"\\\" found in 2nd schema!\");\n\n static RegexMatcher * const auto_increment_matcher(RegexMatcher::RegexMatcherFactoryOrDie(\"\\\\s*AUTO_INCREMENT=\\\\d+\"));\n const std::string cleaned_table_options1(auto_increment_matcher->replaceAll(table_options1->substr(2), \"\"));\n const std::string cleaned_table_options2(auto_increment_matcher->replaceAll(table_options2->substr(2), \"\"));\n\n if (cleaned_table_options1 != cleaned_table_options2)\n std::cerr << \"Table options differ for \" << table_name1 << \": \" << cleaned_table_options1 << \" -> \"\n << cleaned_table_options2 << '\\n';\n }\n}\n\n\nvoid ReportUnknownLines(const std::string &schema, const std::map> &table_name_to_schema_map) {\n static const std::vector KNOWN_LINE_PREFIXES{ \"KEY\", \"PRIMARY KEY\", \"UNIQUE KEY\", \"CONSTRAINT\", \") \", \"`\" };\n\n for (const auto &table_name_and_schema : table_name_to_schema_map) {\n for (const auto &line : table_name_and_schema.second) {\n bool found_a_known_prefix(false);\n for (const auto &known_prefix : KNOWN_LINE_PREFIXES) {\n if (StringUtil::StartsWith(line, known_prefix)) {\n found_a_known_prefix = true;\n break;\n }\n }\n\n if (not found_a_known_prefix)\n LOG_ERROR(\"Unknown line type in \" + schema + \", table \" + table_name_and_schema.first + \": \" + line);\n }\n }\n}\n\n\nvoid DiffSchemas(const std::map> &table_name_to_schema_map1,\n const std::map> &table_name_to_schema_map2)\n{\n std::set already_processed_table_names;\n for (const auto &table_name1_and_schema1 : table_name_to_schema_map1) {\n const auto &table_name1(table_name1_and_schema1.first);\n already_processed_table_names.emplace(table_name1);\n const auto table_name2_and_schema2(table_name_to_schema_map2.find(table_name1));\n if (table_name2_and_schema2 == table_name_to_schema_map2.cend()) {\n std::cout << \"Table was deleted: \" << table_name1 << '\\n';\n continue;\n }\n\n const auto &schema1(table_name1_and_schema1.second);\n const auto &schema2(table_name2_and_schema2->second);\n\n \/\/ Compare column definitions first:\n const auto last_column_def1(std::find_if(schema1.crbegin(), schema1.crend(),\n [](const std::string &line){ return not line.empty() and line[0] == '`'; }));\n const auto last_column_def2(std::find_if(schema2.crbegin(), schema2.crend(),\n [](const std::string &line){ return not line.empty() and line[0] == '`'; }));\n\n std::set already_processed_column_names;\n for (auto column_def1(schema1.cbegin()); column_def1 != last_column_def1.base(); ++column_def1) {\n const auto column_name1(ExtractBackQuotedString(*column_def1));\n already_processed_column_names.emplace(column_name1);\n const auto column_def2(std::find_if(schema2.cbegin(), last_column_def2.base(), StartsWithColumnName(column_name1)));\n if (column_def2 == last_column_def2.base())\n std::cout << \"Column does not exist in 1st schema: \" << table_name1 << '.' << column_name1 << '\\n';\n else if (*column_def1 != *column_def2)\n std::cout << \"Column definition differs between the 1st and 2nd schemas (\" << table_name1 << \"): \" << *column_def1 << \" -> \" << *column_def2 << '\\n';\n }\n\n for (auto column_def2(schema2.cbegin()); column_def2 != last_column_def2.base(); ++column_def2) {\n const auto column_name2(ExtractBackQuotedString(*column_def2));\n if (already_processed_column_names.find(column_name2) == already_processed_column_names.cend())\n std::cout << \"Column exists only in 2nd schema: \" << table_name1 << '.' << column_name2 << '\\n';\n }\n }\n\n std::set schema2_tables;\n for (const auto &table_name2_and_schema2 : table_name_to_schema_map2) {\n const auto &table_name2(table_name2_and_schema2.first);\n schema2_tables.emplace(table_name2);\n if (already_processed_table_names.find(table_name2) == already_processed_table_names.cend())\n std::cout << \"Table exists only in 1st schema: \" << table_name2 << '\\n';\n }\n for (const auto &table_name1_and_schema1 : table_name_to_schema_map1) {\n const auto &table_name1(table_name1_and_schema1.first);\n if (schema2_tables.find(table_name1) == schema2_tables.cend())\n std::cout << \"Table exist only in 2st schema: \" << table_name1 << '\\n';\n }\n\n CompareTables(\"KEY\", table_name_to_schema_map1, table_name_to_schema_map2);\n CompareTables(\"PRIMARY KEY\", table_name_to_schema_map1, table_name_to_schema_map2);\n CompareTables(\"UNIQUE KEY\", table_name_to_schema_map1, table_name_to_schema_map2);\n CompareTables(\"CONSTRAINT\", table_name_to_schema_map1, table_name_to_schema_map2);\n CompareTableOptions(table_name_to_schema_map1, table_name_to_schema_map2);\n\n ReportUnknownLines(\"schema1\", table_name_to_schema_map1);\n ReportUnknownLines(\"schema2\", table_name_to_schema_map2);\n}\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 3)\n ::Usage(\"schema1 schema2\\n\"\n \"Please note that this tool may not work particularly well if you do not use output from mysql_list_tables\");\n\n std::map> table_name_to_schema_map1;\n LoadSchema(argv[1], &table_name_to_schema_map1);\n\n std::map> table_name_to_schema_map2;\n LoadSchema(argv[2], &table_name_to_schema_map2);\n\n DiffSchemas(table_name_to_schema_map1, table_name_to_schema_map2);\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"templates: add comments in TaskBase.* to explain some error messages<|endoftext|>"} {"text":"\/\/ run testOperations in loop mode from size 2x2 up to 30x30\n#define TEST_ALL_MATRIX_SIZES\n#define NITER 10\n#include \"testOperations.cxx\"\nkeep NITER=1 as default\/\/ run testOperations in loop mode from size 2x2 up to 30x30\n#define TEST_ALL_MATRIX_SIZES\n\/\/#define NITER 10\n#include \"testOperations.cxx\"\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nnamespace detail {\ntemplate struct MetatypeFunctionHelperImpl {\n static void Destruct(void *t) { static_cast(t)->~T(); }\n static void *Construct(void *where, const void *t) {\n if (t)\n return new (where) T(*static_cast(t));\n return new (where) T;\n }\n static void Save(QDataStream &ds, const void *t) { ds << *static_cast(t); }\n static void Load(QDataStream &stream, void *t) { ds >> *static_cast(t); }\n};\ntemplate struct BaseMetatypeFunctionhelper :\n MetatypeFunctionHelperImpl {};\n}\n\n#define DECLARE_CUSTOM_METATYPE(BASE_TYPE, TYPE) DECLARE_CUSTOM_METATYPE_IMPL(BASE_TYPE, TYPE)\n\n#define DECLARE_CUSTOM_METATYPE_IMPL(BASE_TYPE, TYPE) \\\n QT_BEGIN_NAMESPACE \\\n template <> \\\n struct QtMetaTypePrivate::QMetaTypeFunctionHelper : \\\n BaseMetatypeFunctionhelper {}; \\\n\n\nQ_GLOBAL_STATIC(QReadWriteLock, aa)\n\n template struct QGraphicsItemHelper {\n static void Destruct(void *t) { static_cast(t)->~T(); }\n static void *Construct(void *where, const void *t) {\n Q_ASSERT(!t);\n return new (where) T;\n }\n static void Save(QDataStream &ds, const void *t) { ds << *static_cast(t); }\n static void Load(QDataStream &ds, void *t) { ds >> *static_cast(t); }\n };\n\ntemplate bool checkTypeEnum() {\n auto const &en = QMetaEnum::fromType();\n for (int i = 0; i < en.keyCount(); i++)\n if (QMetaType::type(en.key(i)) == QMetaType::UnknownType)\n return false;\n return true;\n}\n\ntemplate int typeIdToEnum(int typeId) {\n auto const &en = QMetaEnum::fromType();\n return en.keyToValue(QMetaType::typeName(typeId));\n}\n\ntemplate int enumToTypeId(int enumVal) {\n auto const &en = QMetaEnum::fromType();\n auto *name = en.valueToKey(enumVal);\n return name ? QMetaType::type(name) : QMetaType::UnknownType;\n}\n\n#define DECLARE_GRAPHICS_METAITEM(TYPE) DECLARE_GRAPHICS_METAITEM_IMPL(TYPE)\n#define DECLARE_GRAPHICS_METAITEM_IMPL(TYPE) \\\n QT_BEGIN_NAMESPACE \\\n template <> \\\n struct QtMetaTypePrivate::QMetaTypeFunctionHelper : \\\n QGraphicsItemHelper {}; \\\n template <> \\\n struct QMetaTypeId \\\n{ \\\n enum { Defined = 1 }; \\\n static int qt_metatype_id() \\\n{ \\\n static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \\\n if (const int id = metatype_id.loadAcquire()) \\\n return id; \\\n const int newId = qRegisterMetaType< TYPE >(#TYPE, \\\n reinterpret_cast< TYPE *>(quintptr(-1))); \\\n metatype_id.storeRelease(newId); \\\n return newId; \\\n } \\\n }; \\\n QT_END_NAMESPACE\n\nDECLARE_GRAPHICS_METAITEM(QGraphicsEllipseItem)\n\nclass ItemStream {\n Q_GADGET\n QDataStream &ds;\n QGraphicsItem &item;\n public:\n enum Type {\n QGraphicsEllipseItem = QGraphicsEllipseItem::Type,\n QGraphicsPathItem = QGraphicsPathItem::Type,\n QGraphicsPolygonItem = QGraphicsPolygonItem::Type,\n QGraphicsRectItem = QGraphicsRectItem::Type,\n QGraphicsSimpleTextItem = QGraphicsSimpleTextItem::Type,\n QGraphicsLineItem = QGraphicsLineItem::Type,\n QGraphicsPixmapItem = QGraphicsPixmapItem::Type\n };\n Q_ENUM(Type)\n ItemStream(QDataStream &ds, class QGraphicsItem &item) : ds(ds), item(item) {}\n template ItemStream &operator>>(void (C::*set)(T)) {\n using decayed_type = typename std::decay::type;\n using value_type = typename std::conditional::value,\n std::underlying_type, std::decay>::type::type;\n value_type value;\n ds >> value;\n (static_cast(item).*set)(static_cast(value));\n return *this;\n }\n};\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsItem &g) {\n out << g.type()\n << g.pos()\n << g.scale()\n << g.rotation()\n << g.transform()\n \/\/<< g.transformations()\n << g.transformOriginPoint()\n << g.flags()\n << g.isEnabled()\n << g.isSelected()\n << g.zValue();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsItem &g) {\n using QGI = std::decay::type;\n int type;\n QTransform transform;\n in >> type;\n Q_ASSERT(g.type() == type);\n ItemStream iin(in, g);\n iin >> &QGI::setPos\n >> &QGI::setScale\n >> &QGI::setRotation;\n in >> transform;\n iin \/\/>> &QGI::setTransformations\n >> &QGI::setTransformOriginPoint\n >> &QGI::setFlags\n >> &QGI::setEnabled\n >> &QGI::setSelected\n >> &QGI::setZValue;\n g.setTransform(transform);\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QAbstractGraphicsShapeItem &g){\n out << static_cast(g);\n out << g.pen() << g.brush();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QAbstractGraphicsShapeItem &g){\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in,g) >> &QGI::setPen >> &QGI::setBrush;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsEllipseItem &g){\n out << dynamic_cast(g);\n out << g.rect() << g.startAngle() << g.spanAngle();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsEllipseItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setRect >> &QGI::setStartAngle >> &QGI::setSpanAngle;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsPathItem &g) {\n out << static_cast(g);\n out << g.path();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsPathItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setPath;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsPolygonItem &g) {\n out << static_cast(g);\n out << g.polygon()<< g.fillRule();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsPolygonItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setPolygon >> &QGI::setFillRule;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsRectItem &g) {\n out << static_cast(g);\n out << g.rect();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsRectItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in,g) >> &QGI::setRect;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsSimpleTextItem &g) {\n out << static_cast(g);\n out << g.text() << g.font();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsSimpleTextItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setText >> &QGI::setFont;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsLineItem &g) {\n out << static_cast(g);\n out << g.pen() << g.line();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsLineItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setPen >> &QGI::setLine;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsPixmapItem &g) {\n out << static_cast(g);\n out << g.pixmap() << g.offset() << g.transformationMode() << g.shapeMode();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsPixmapItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setPixmap >> &QGI::setOffset\n >> &QGI::setTransformationMode >> &QGI::setShapeMode;\n return in;\n}\n\n#if 0\nstatic void saveItems(QList items, QDataStream & out){\n for(QGraphicsItem *item : items){\n out << g.type();\n switch (g.type()) {\n case QGraphicsLineItem::Type:\n out << dynamic_cast(item);\n break;\n case QGraphicsSimpleTextItem::Type:\n out << dynamic_cast(item);\n break;\n case QGraphicsRectItem::Type:\n out << dynamic_cast(item);\n break;\n case QGraphicsPolygonItem::Type:\n out << dynamic_cast(item);\n break;\n case QGraphicsPathItem::Type:\n out << dynamic_cast(item);\n break;\n case QGraphicsPixmapItem::Type:\n out << dynamic_cast(item);\n break;\n }\n }\n}\n\nstatic QList readItems(QDataStream & in){\n QList items;\n int type;\n while (!in.atEnd()) {\n in >> type;\n switch (type) {\n case QGraphicsLineItem::Type: {\n QGraphicsLineItem *item = new QGraphicsLineItem;\n in >> item;\n items << item;\n break;\n }\n case QGraphicsSimpleTextItem::Type:{\n QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem;\n in >> item;\n items << item;\n break;\n }\n case QGraphicsRectItem::Type:{\n QGraphicsRectItem *item = new QGraphicsRectItem;\n in >> item;\n items << item;\n break;\n }\n case QGraphicsPolygonItem::Type:{\n QGraphicsPolygonItem *item = new QGraphicsPolygonItem;\n in >> item;\n items << item;\n break;\n }\n case QGraphicsPathItem::Type:{\n QGraphicsPathItem *item = new QGraphicsPathItem;\n in >> item;\n items << item;\n break;\n }\n case QGraphicsPixmapItem::Type:{\n QGraphicsPixmapItem *item = new QGraphicsPixmapItem;\n in >> item;\n items << item;\n break;\n }\n }\n }\n return items;\n}\n#endif\n\nint main(int argc, char *argv[])\n{\n QCoreApplication a(argc, argv);\n\n return a.exec();\n}\n#include \"main.moc\"\nWIP - some generic code can be reused for other projects#include \n#include \n#include \n#include \n\n#if 0\n\/* Common polymorphic type machinery *\/\n\nnamespace detail {\n\ntemplate struct CopyableFunctionHelperImpl {\n static void Destruct(void *t) { static_cast(t)->~T(); }\n static void *Construct(void *where, const void *t) {\n return t ? new (where) T(*static_cast(t)) : new (where) T;\n }\n static void Save(QDataStream &ds, const void *t) { ds << *static_cast(t); }\n static void Load(QDataStream &stream, void *t) { ds >> *static_cast(t); }\n};\n\ntemplate struct NonCopyableFunctionHelperImpl {\n static void Destruct(void *t) { static_cast(t)->~T(); }\n static void *Construct(void *where, const void *t) { return (!t) ? new (where) T : nullptr; }\n static void Save(QDataStream &ds, const void *t) { ds << *static_cast(t); }\n static void Load(QDataStream &stream, void *t) { ds >> *static_cast(t); }\n};\n\ntemplate struct PolymorphicTraits;\n\ntemplate struct PolymorphicTraits {\n \/\/ By default, discriminate types by their metatype Id\n using discriminator_type = int;\n template static discriminator_type type() { return qMetaTypeId(); }\n template static void *create(void *copy) { return QMetaType::create(type(), copy); }\n template static discriminator_type registerDiscriminator() { return type(); }\n};\n\n}\n\n#define DECLARE_POLYMORPHIC_METATYPE(BASE_TYPE, TYPE) DECLARE_POLYMORPHIC_METATYPE_IMPL(BASE_TYPE, TYPE)\n#define DECLARE_POLYMORPHIC_METATYPE_IMPL(BASE_TYPE, TYPE) \\\n QT_BEGIN_NAMESPACE \\\n template <> struct QtMetaTypePrivate::QMetaTypeFunctionHelper \\\n ::value, TYPE>::type, true> : \\\n detail::CopyableFunctionHelperImpl {}; \\\n template <> struct QtMetaTypePrivate::QMetaTypeFunctionHelper \\\n ::value, TYPE>::type, true> : \\\n detail::NonCopyableFunctionHelperImpl {}; \\\n template <> \\\n int qRegisterMetaType(const char *typeName, TYPE *dummy, \\\n typename QtPrivate::MetaTypeDefinedHelper::Defined && !QMetaTypeId2::IsBuiltIn>::DefinedType defined) \\\n{ \\\n QT_PREPEND_NAMESPACE(QByteArray) normalizedTypeName = QMetaObject::normalizedType(typeName); \\\n detail::PolymorphicTraits::registerDiscriminator(); \\\n return qRegisterNormalizedMetaType(normalizedTypeName, dummy, defined); \\\n } \\\n template <> struct QMetaTypeId { \\ \\\n enum { Defined = 1 }; \\\n static int qt_metatype_id() { \\\n static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \\\n if (const int id = metatype_id.loadAcquire()) \\\n return id; \\\n const int newId = qRegisterMetaType(#TYPE, \\\n reinterpret_cast(quintptr(-1))); \\\n metatype_id.storeRelease(newId); \\\n return newId; \\\n } \\\n }; \\\n QT_END_NAMESPACE\n\n\n\n#define DEFINE_POLYMORPHIC_METATYPE(TYPE) DEFINE_POLYMORPHIC_METATYPE_IMPL(TYPE)\n#define DEFINE_POLYMORPHIC_METATYPE_IMPL(TYPE) \\\n static\n\nQ_GLOBAL_STATIC(QReadWriteLock, aa)\n\n\ntemplate bool checkTypeEnum() {\n auto const &en = QMetaEnum::fromType();\n for (int i = 0; i < en.keyCount(); i++)\n if (QMetaType::type(en.key(i)) == QMetaType::UnknownType)\n return false;\n return true;\n}\n\ntemplate int typeIdToEnum(int typeId) {\n auto const &en = QMetaEnum::fromType();\n return en.keyToValue(QMetaType::typeName(typeId));\n}\n\ntemplate int enumToTypeId(int enumVal) {\n auto const &en = QMetaEnum::fromType();\n auto *name = en.valueToKey(enumVal);\n return name ? QMetaType::type(name) : QMetaType::UnknownType;\n}\n\n#define DECLARE_GRAPHICS_METAITEM(TYPE) DECLARE_GRAPHICS_METAITEM_IMPL(TYPE)\n#define DECLARE_GRAPHICS_METAITEM_IMPL(TYPE) \\\n QT_BEGIN_NAMESPACE \\\n template <> \\\n struct QtMetaTypePrivate::QMetaTypeFunctionHelper : \\\n QGraphicsItemHelper {}; \\\n template <> \\\n struct QMetaTypeId \\\n{ \\\n enum { Defined = 1 }; \\\n\n\nDECLARE_GRAPHICS_METAITEM(QGraphicsEllipseItem)\n#endif\n\n\ntemplate struct NonCopyableFunctionHelper {\n using base_type = B;\n static void Destruct(void *t) { static_cast(t)->~T(); }\n static void *Construct(void *where, const void *t) { return (!t) ? new (where) T : nullptr; }\n static void Save(QDataStream &ds, const void *t) { ds << *static_cast(t); }\n static void Load(QDataStream &ds, void *t) { ds >> *static_cast(t); }\n};\n\n#define DECLARE_POLYMORPHIC_METATYPE(BASE_TYPE, TYPE) DECLARE_POLYMORPHIC_METATYPE_IMPL(BASE_TYPE, TYPE)\n#define DECLARE_POLYMORPHIC_METATYPE_IMPL(BASE_TYPE, TYPE) \\\n QT_BEGIN_NAMESPACE \\\n template <> struct QtMetaTypePrivate::QMetaTypeFunctionHelper \\\n ::value, TYPE>::type, true> : \\\n detail::NonCopyableFunctionHelperImpl {}; \\\n QT_END_NAMESPACE \\\n Q_DECLARE_METATYPE_IMPL(TYPE)\n\n\/\/DECLARE_POLYMORPHIC_METATYPE(QGraphicsItem, QGraphicsEllipseItem)\n\n\n\/*Interface*\/\ntemplate <> struct QtMetaTypePrivate::QMetaTypeFunctionHelper\n ::value, QGraphicsEllipseItem>::type, true> :\n NonCopyableFunctionHelper {};\nQ_DECLARE_METATYPE(QGraphicsEllipseItem)\n\ntemplate struct BaseTraits;\n\ntemplate <> struct BaseTraits {\n using base_type = QGraphicsItem;\n struct pair_type { int itemType; int typeId; };\n template \n static typename std::enable_if::value>::type registerType() {\n qRegisterMetaTypeStreamOperators();\n registerMapping(qMetaTypeId(), T::type());\n }\n static pair_type registerMapping(int typeId, int d);\n};\n\nQDataStream &operator<<(QDataStream &, QGraphicsItem *g);\nQDataStream &operator>>(QDataStream &, QGraphicsItem *&g);\n\n\/*Implementation*\/\n\nQDataStream &operator<<(QDataStream &ds, const QGraphicsItem *g) {\n auto mapping = BaseTraits::registerMapping(QMetaType::UnknownType, g->type());\n QMetaType::save(ds, mapping.typeId, g);\n return ds;\n}\n\nQDataStream &operator>>(QDataStream &, QGraphicsItem *&g) {\n int type = 0;\n auto read = ds.device()->peek(reinterpret_cast(&type), sizeof(type));\n if (read != sizeof(type)) {\n ds.setStatus(QDataStream::ReadPastEnd);\n return ds;\n }\n auto mapping = BaseTraits::registerMapping(type, 0);\n const QMetaType mt(mapping.typeId);\n g = mt.create();\n if (g) mt.load()\n QMetaClassIn\n}\n\n\nclass ItemStream {\n Q_GADGET\n QDataStream &ds;\n QGraphicsItem &item;\npublic:\n enum Type {\n QGraphicsEllipseItem = QGraphicsEllipseItem::Type,\n QGraphicsPathItem = QGraphicsPathItem::Type,\n QGraphicsPolygonItem = QGraphicsPolygonItem::Type,\n QGraphicsRectItem = QGraphicsRectItem::Type,\n QGraphicsSimpleTextItem = QGraphicsSimpleTextItem::Type,\n QGraphicsLineItem = QGraphicsLineItem::Type,\n QGraphicsPixmapItem = QGraphicsPixmapItem::Type\n };\n Q_ENUM(Type)\n ItemStream(QDataStream &ds, class QGraphicsItem &item) : ds(ds), item(item) {}\n template ItemStream &operator>>(void (C::*set)(T)) {\n using decayed_type = typename std::decay::type;\n using value_type = typename std::conditional::value,\n std::underlying_type, std::decay>::type::type;\n value_type value;\n ds >> value;\n (static_cast(item).*set)(static_cast(value));\n return *this;\n }\n};\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsItem &g) {\n out << g.type()\n << g.pos()\n << g.scale()\n << g.rotation()\n << g.transform()\n \/\/<< g.transformations()\n << g.transformOriginPoint()\n << g.flags()\n << g.isEnabled()\n << g.isSelected()\n << g.zValue();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsItem &g) {\n using QGI = std::decay::type;\n int type;\n QTransform transform;\n in >> type;\n Q_ASSERT(g.type() == type);\n ItemStream iin(in, g);\n iin >> &QGI::setPos\n >> &QGI::setScale\n >> &QGI::setRotation;\n in >> transform;\n iin \/\/>> &QGI::setTransformations\n >> &QGI::setTransformOriginPoint\n >> &QGI::setFlags\n >> &QGI::setEnabled\n >> &QGI::setSelected\n >> &QGI::setZValue;\n g.setTransform(transform);\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QAbstractGraphicsShapeItem &g){\n out << static_cast(g);\n out << g.pen() << g.brush();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QAbstractGraphicsShapeItem &g){\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in,g) >> &QGI::setPen >> &QGI::setBrush;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsEllipseItem &g){\n out << dynamic_cast(g);\n out << g.rect() << g.startAngle() << g.spanAngle();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsEllipseItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setRect >> &QGI::setStartAngle >> &QGI::setSpanAngle;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsPathItem &g) {\n out << static_cast(g);\n out << g.path();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsPathItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setPath;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsPolygonItem &g) {\n out << static_cast(g);\n out << g.polygon()<< g.fillRule();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsPolygonItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setPolygon >> &QGI::setFillRule;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsRectItem &g) {\n out << static_cast(g);\n out << g.rect();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsRectItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in,g) >> &QGI::setRect;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsSimpleTextItem &g) {\n out << static_cast(g);\n out << g.text() << g.font();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsSimpleTextItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setText >> &QGI::setFont;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsLineItem &g) {\n out << static_cast(g);\n out << g.pen() << g.line();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsLineItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setPen >> &QGI::setLine;\n return in;\n}\n\nQDataStream &operator<<(QDataStream &out, const QGraphicsPixmapItem &g) {\n out << static_cast(g);\n out << g.pixmap() << g.offset() << g.transformationMode() << g.shapeMode();\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, QGraphicsPixmapItem &g) {\n using QGI = std::decay::type;\n in >> static_cast(g);\n ItemStream(in, g) >> &QGI::setPixmap >> &QGI::setOffset\n >> &QGI::setTransformationMode >> &QGI::setShapeMode;\n return in;\n}\n\n#if 0\nstatic void saveItems(QList items, QDataStream & out){\n for(QGraphicsItem *item : items){\n out << g.type();\n switch (g.type()) {\n case QGraphicsLineItem::Type:\n out << dynamic_cast(item);\n break;\n case QGraphicsSimpleTextItem::Type:\n out << dynamic_cast(item);\n break;\n case QGraphicsRectItem::Type:\n out << dynamic_cast(item);\n break;\n case QGraphicsPolygonItem::Type:\n out << dynamic_cast(item);\n break;\n case QGraphicsPathItem::Type:\n out << dynamic_cast(item);\n break;\n case QGraphicsPixmapItem::Type:\n out << dynamic_cast(item);\n break;\n }\n }\n}\n\nstatic QList readItems(QDataStream & in){\n QList items;\n int type;\n while (!in.atEnd()) {\n in >> type;\n switch (type) {\n case QGraphicsLineItem::Type: {\n QGraphicsLineItem *item = new QGraphicsLineItem;\n in >> item;\n items << item;\n break;\n }\n case QGraphicsSimpleTextItem::Type:{\n QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem;\n in >> item;\n items << item;\n break;\n }\n case QGraphicsRectItem::Type:{\n QGraphicsRectItem *item = new QGraphicsRectItem;\n in >> item;\n items << item;\n break;\n }\n case QGraphicsPolygonItem::Type:{\n QGraphicsPolygonItem *item = new QGraphicsPolygonItem;\n in >> item;\n items << item;\n break;\n }\n case QGraphicsPathItem::Type:{\n QGraphicsPathItem *item = new QGraphicsPathItem;\n in >> item;\n items << item;\n break;\n }\n case QGraphicsPixmapItem::Type:{\n QGraphicsPixmapItem *item = new QGraphicsPixmapItem;\n in >> item;\n items << item;\n break;\n }\n }\n }\n return items;\n}\n#endif\n\nint main(int argc, char *argv[])\n{\n QCoreApplication a(argc, argv);\n\n return a.exec();\n}\n#include \"main.moc\"\n<|endoftext|>"} {"text":"\/**\n * @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file JPetTaskLooper.cpp\n *\/\n\n#include \"JPetTaskLooper.h\"\n#include \"JPetLoggerInclude.h\"\n#include \"JPetParams\/JPetParams.h\"\n#include \"JPetData\/JPetData.h\"\n\nJPetTaskLooper::JPetTaskLooper(const char* name, std::unique_ptr subtask, Predicate isCondition):\n JPetTask(name),\n fIsCondition(isCondition)\n{\n addSubTask(std::move(subtask));\n}\n\nbool JPetTaskLooper::init(const JPetParams& paramsI)\n{\n fParams = paramsI;\n return true;\n}\n\nbool JPetTaskLooper::run(const JPetDataInterface&)\n{\n JPetDataInterface nullDataObject;\n auto subTasks = getSubTasks();\n if (subTasks.empty()) {\n WARNING(\"No subtask defined in JPetTaskLooper\");\n }\n for (const auto& subTask : subTasks) {\n if (!subTask) {\n ERROR(\"some subTasks are nullptr\");\n return false;\n }\n }\n JPetParams inParams = fParams;\n JPetParams outParams;\n while (fIsCondition(inParams)) {\n for (const auto& subTask : subTasks) {\n subTask->init(inParams);\n subTask->run(nullDataObject);\n subTask->terminate(outParams);\n inParams = outParams;\n }\n }\n return true;\n}\n\nbool JPetTaskLooper::terminate(JPetParams& paramsO)\n{\n paramsO = fParams;\n return true;\n}\n\nvoid JPetTaskLooper::setConditionFunction(Predicate isCondition)\n{\n fIsCondition = isCondition;\n}\n\n\nPredicate JPetTaskLooper::getMaxIterationPredicate(int maxIteration)\n{\n assert(maxIteration >=0);\n int counter = 0;\n auto iterationFunction = [maxIteration, counter](const JPetParams&) mutable ->bool {\n if (counter < maxIteration) {\n counter++;\n return true;\n } else {\n return false;\n }\n };\n return iterationFunction;\n}\n\nPredicate JPetTaskLooper::getStopOnOptionPredicate(const std::string stopIterationOptName)\n{\n auto stopFunction = [stopIterationOptName](const JPetParams& params)->bool {\n using namespace jpet_options_tools;\n auto options = params.getOptions();\n bool continueIteration = isOptionSet(options, stopIterationOptName) && (!getOptionAsBool(options, stopIterationOptName));\n return continueIteration;\n };\n return stopFunction;\n}\nAdd some error handling for subtasks calls\/**\n * @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file JPetTaskLooper.cpp\n *\/\n\n#include \"JPetTaskLooper.h\"\n#include \"JPetLoggerInclude.h\"\n#include \"JPetParams\/JPetParams.h\"\n#include \"JPetData\/JPetData.h\"\n\nJPetTaskLooper::JPetTaskLooper(const char* name, std::unique_ptr subtask, Predicate isCondition):\n JPetTask(name),\n fIsCondition(isCondition)\n{\n addSubTask(std::move(subtask));\n}\n\nbool JPetTaskLooper::init(const JPetParams& paramsI)\n{\n fParams = paramsI;\n return true;\n}\n\nbool JPetTaskLooper::run(const JPetDataInterface&)\n{\n JPetDataInterface nullDataObject;\n auto subTasks = getSubTasks();\n if (subTasks.empty()) {\n WARNING(\"No subtask defined in JPetTaskLooper\");\n }\n for (const auto& subTask : subTasks) {\n if (!subTask) {\n ERROR(\"some subTasks are nullptr\");\n return false;\n }\n }\n JPetParams inParams = fParams;\n JPetParams outParams;\n while (fIsCondition(inParams)) {\n for (const auto& subTask : subTasks) {\n auto isOk = subTask->init(inParams);\n if (!isOk) {\n ERROR(\"Errors in subtask init(). run() and terminate() calls will be skipped. \");\n continue;\n }\n subTask->run(nullDataObject);\n isOk = subTask->terminate(outParams);\n if (!isOk) {\n ERROR(\"Errors in subtask terminate(). \");\n }\n inParams = outParams;\n }\n }\n return true;\n}\n\nbool JPetTaskLooper::terminate(JPetParams& paramsO)\n{\n paramsO = fParams;\n return true;\n}\n\nvoid JPetTaskLooper::setConditionFunction(Predicate isCondition)\n{\n fIsCondition = isCondition;\n}\n\n\nPredicate JPetTaskLooper::getMaxIterationPredicate(int maxIteration)\n{\n assert(maxIteration >= 0);\n int counter = 0;\n auto iterationFunction = [maxIteration, counter](const JPetParams&) mutable ->bool {\n if (counter < maxIteration)\n {\n counter++;\n return true;\n } else {\n return false;\n }\n };\n return iterationFunction;\n}\n\nPredicate JPetTaskLooper::getStopOnOptionPredicate(const std::string stopIterationOptName)\n{\n auto stopFunction = [stopIterationOptName](const JPetParams & params)->bool {\n using namespace jpet_options_tools;\n auto options = params.getOptions();\n bool continueIteration = isOptionSet(options, stopIterationOptName) && (!getOptionAsBool(options, stopIterationOptName));\n return continueIteration;\n };\n return stopFunction;\n}\n<|endoftext|>"} {"text":"ncsid: Guarantee MAC override<|endoftext|>"} {"text":"\n#include \"base\/not_null.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \"base\/macros.hpp\"\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\nusing testing::Eq;\n\nnamespace principia {\nnamespace base {\n\nclass NotNullTest : public testing::Test {\n protected:\n \/\/ A very convoluted wrapper for the x86 add...\n void Add(not_null const destination,\n not_null const source) {\n *destination += *source;\n }\n void Sub(not_null const destination,\n not_null const source) {\n *destination -= *source;\n }\n};\n\nusing NotNullDeathTest = NotNullTest;\n\nTEST_F(NotNullDeathTest, DeathByNullptr) {\n EXPECT_DEATH({\n int* const null_int_ptr = nullptr;\n check_not_null(null_int_ptr);\n }, \"Check failed: .* != nullptr\");\n EXPECT_DEATH({\n std::unique_ptr null_int_ptr;\n check_not_null(std::move(null_int_ptr));\n }, \"Check failed: .* != nullptr\");\n}\n\nTEST_F(NotNullTest, Move) {\n not_null> int_ptr1 = make_not_null_unique(3);\n#if !PRINCIPIA_COMPILER_MSVC || \\\n !(_MSC_FULL_VER == 190'023'506 || \\\n _MSC_FULL_VER == 190'023'918 || \\\n _MSC_FULL_VER == 190'024'210 || \\\n _MSC_FULL_VER == 190'024'213 || \\\n _MSC_FULL_VER == 190'024'215 || \\\n _MSC_FULL_VER == 191'326'215 || \\\n _MSC_FULL_VER == 191'426'316 || \\\n _MSC_FULL_VER == 191'426'412 || \\\n _MSC_FULL_VER == 191'426'428 || \\\n _MSC_FULL_VER == 191'426'429 || \\\n _MSC_FULL_VER == 191'526'608 || \\\n _MSC_FULL_VER == 191'526'731 || \\\n _MSC_FULL_VER == 191'627'024 || \\\n _MSC_FULL_VER == 191'627'025 || \\\n _MSC_FULL_VER == 191'627'027 || \\\n _MSC_FULL_VER == 192'027'508 || \\\n _MSC_FULL_VER == 192'227'706 || \\\n _MSC_FULL_VER == 192'227'724 || \\\n _MSC_FULL_VER == 192'227'905 || \\\n _MSC_FULL_VER == 192'328'106 || \\\n _MSC_FULL_VER == 192'428'314)\n EXPECT_THAT(*(std::unique_ptr const&)int_ptr1, Eq(3));\n#endif\n not_null> int_ptr2 = std::move(int_ptr1);\n EXPECT_THAT(*int_ptr2, Eq(3));\n not_null> int_ptr3(std::move(int_ptr2));\n EXPECT_THAT(*int_ptr3, Eq(3));\n int_ptr2 = make_not_null_unique(5);\n EXPECT_THAT(*int_ptr2, Eq(5));\n int_ptr2 = std::move(int_ptr3);\n EXPECT_THAT(*int_ptr2, Eq(3));\n}\n\nTEST_F(NotNullTest, Copy) {\n std::unique_ptr const owner_of_three = std::make_unique(3);\n std::unique_ptr const owner_of_five = std::make_unique(5);\n not_null const int_ptr1 = check_not_null(owner_of_three.get());\n not_null int_ptr2 = int_ptr1;\n not_null const int_ptr3(int_ptr2);\n EXPECT_THAT(int_ptr1, Eq(owner_of_three.get()));\n EXPECT_THAT(int_ptr2, Eq(owner_of_three.get()));\n EXPECT_THAT(int_ptr3, Eq(owner_of_three.get()));\n EXPECT_THAT(*int_ptr1, Eq(3));\n EXPECT_THAT(*int_ptr2, Eq(3));\n EXPECT_THAT(*int_ptr3, Eq(3));\n int_ptr2 = check_not_null(owner_of_five.get());\n EXPECT_THAT(*int_ptr2, Eq(5));\n int_ptr2 = int_ptr3;\n EXPECT_THAT(*int_ptr2, Eq(3));\n EXPECT_THAT(*int_ptr3, Eq(3));\n}\n\nTEST_F(NotNullTest, CheckNotNull) {\n#if 0\n std::unique_ptr owner_int = std::make_unique(3);\n int* const constant_access_int = owner_int.get();\n not_null const constant_not_null_access_int =\n check_not_null(constant_access_int);\n check_not_null(constant_not_null_access_int);\n not_null> not_null_owner_int =\n check_not_null(std::move(owner_int));\n check_not_null(std::move(not_null_owner_int));\n#endif\n}\n\nTEST_F(NotNullTest, Booleans) {\n not_null> const pointer = make_not_null_unique(3);\n EXPECT_TRUE(pointer);\n EXPECT_TRUE(pointer != nullptr);\n EXPECT_FALSE(pointer == nullptr);\n}\n\nTEST_F(NotNullTest, ImplicitConversions) {\n not_null> not_null_owner_int =\n make_not_null_unique(3);\n not_null const constant_not_null_access_int =\n not_null_owner_int.get();\n \/\/ Copy constructor.\n not_null not_null_access_constant_int =\n constant_not_null_access_int;\n \/\/ Copy assignment.\n not_null_access_constant_int = not_null_owner_int.get();\n \/\/ Move constructor.\n not_null> not_null_owner_constant_int =\n make_not_null_unique(5);\n \/\/ Move assignment.\n not_null_owner_constant_int = std::move(not_null_owner_int);\n}\n\nTEST_F(NotNullTest, Arrow) {\n not_null> not_null_owner_string =\n make_not_null_unique(\"-\");\n not_null_owner_string->append(\">\");\n EXPECT_THAT(*not_null_owner_string, Eq(\"->\"));\n not_null not_null_access_string = not_null_owner_string.get();\n not_null_access_string->insert(0, \"operator\");\n EXPECT_THAT(*not_null_access_string, Eq(\"operator->\"));\n}\n\nTEST_F(NotNullTest, NotNullNotNull) {\n not_null> owner = make_not_null_unique(42);\n not_null> x = owner.get();\n not_null y = x;\n *x = 6 * 9;\n EXPECT_THAT(*owner, Eq(6 * 9));\n EXPECT_THAT(*x, Eq(6 * 9));\n EXPECT_THAT(*y, Eq(6 * 9));\n}\n\nTEST_F(NotNullTest, CheckArguments) {\n not_null> accumulator = make_not_null_unique(21);\n std::unique_ptr twenty_one = std::make_unique(21);\n Add(accumulator.get(), check_not_null(twenty_one.get()));\n EXPECT_THAT(*twenty_one, Eq(21));\n EXPECT_THAT(*accumulator, Eq(42));\n#if 0\n Sub(check_not_null(accumulator.get()), check_not_null(twenty_one.get()));\n EXPECT_THAT(*accumulator, Eq(21));\n#endif\n}\n\nTEST_F(NotNullTest, DynamicCast) {\n class Base {\n public:\n virtual ~Base() = default;\n };\n class Derived : public Base {};\n {\n not_null b = new Derived;\n [[maybe_unused]] not_null d = dynamic_cast_not_null(b);\n delete b;\n }\n {\n not_null> b = make_not_null_unique();\n not_null> d =\n dynamic_cast_not_null>(std::move(b));\n }\n}\n\nTEST_F(NotNullTest, RValue) {\n std::unique_ptr owner_int = std::make_unique(1);\n not_null not_null_int = new int(2);\n EXPECT_NE(owner_int.get(), not_null_int);\n\n not_null> not_null_owner_int =\n make_not_null_unique(4);\n std::vector v1;\n \/\/ |v1.push_back| would be ambiguous here if |not_null| had an\n \/\/ |operator pointer const&() const&| instead of an\n \/\/ |operator pointer const&&() const&|.\n v1.push_back(not_null_owner_int.get());\n \/\/ |emplace_back| is fine no matter what.\n v1.emplace_back(not_null_owner_int.get());\n EXPECT_EQ(4, *v1[0]);\n EXPECT_EQ(4, *not_null_owner_int);\n\n std::vector v2;\n \/\/ NOTE(egg): The following fails using clang, I'm not sure where the bug is.\n \/\/ More generally, if functions |foo(int*&&)| and |foo(int* const&)| exist,\n \/\/ |foo(non_rvalue_not_null)| fails to compile with clang (\"no viable\n \/\/ conversion\"), but without the |foo(int*&&)| overload it compiles.\n \/\/ This is easily circumvented using a temporary (whereas the ambiguity that\n \/\/ would result from having an |operator pointer const&() const&| would\n \/\/ entirely prevent conversion of |not_null>| to\n \/\/ |unique_ptr|), so we ignore it.\n#if PRINCIPIA_COMPILER_MSVC\n v2.push_back(not_null_int);\n#else\n int* const temporary = not_null_int;\n v2.push_back(temporary);\n#endif\n EXPECT_EQ(2, *v2[0]);\n EXPECT_EQ(2, *not_null_int);\n\n \/\/ |std::unique_ptr::operator=| would be ambiguous here between the move\n \/\/ and copy assignments if |not_null| had an\n \/\/ |operator pointer const&() const&| instead of an\n \/\/ |operator pointer const&&() const&|.\n \/\/ Note that one of the overloads (the implicit copy assignment operator) is\n \/\/ deleted, but this does not matter for overload resolution; however MSVC\n \/\/ compiles this even when it is ambiguous, while clang correctly fails.\n owner_int = make_not_null_unique(1729);\n\n not_null not_null_access_int = owner_int.get();\n [[maybe_unused]] int const* access_const_int = not_null_access_int;\n\n not_null> not_null_shared_int = std::make_shared(3);\n \/\/ This exercises |operator OtherPointer() const&|. The conversion from\n \/\/ |not_null| to |int const*| does not; instead it goes through the\n \/\/ conversion |not_null| -> |int*| -> |int const*|, where the latter is\n \/\/ a qualification adjustment, part of a standard conversion sequence.\n std::shared_ptr shared_const_int = not_null_shared_int;\n\n \/\/ MSVC seems to be confused by templatized move-conversion operators.\n#if PRINCIPIA_COMPILER_MSVC\n \/\/ Uses |not_null(not_null&& other)| followed by\n \/\/ |operator pointer&&() &&|, so the first conversion has to be explicit.\n std::unique_ptr owner_const_int =\n static_cast>>(\n make_not_null_unique(5));\n#else\n \/\/ Uses |operator OtherPointer() &&|.\n std::unique_ptr owner_const_int = make_not_null_unique(5);\n#endif\n EXPECT_EQ(5, *owner_const_int);\n}\n\n} \/\/ namespace base\n} \/\/ namespace principia\nUpgrade to 1.4.4.\n#include \"base\/not_null.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \"base\/macros.hpp\"\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\nusing testing::Eq;\n\nnamespace principia {\nnamespace base {\n\nclass NotNullTest : public testing::Test {\n protected:\n \/\/ A very convoluted wrapper for the x86 add...\n void Add(not_null const destination,\n not_null const source) {\n *destination += *source;\n }\n void Sub(not_null const destination,\n not_null const source) {\n *destination -= *source;\n }\n};\n\nusing NotNullDeathTest = NotNullTest;\n\nTEST_F(NotNullDeathTest, DeathByNullptr) {\n EXPECT_DEATH({\n int* const null_int_ptr = nullptr;\n check_not_null(null_int_ptr);\n }, \"Check failed: .* != nullptr\");\n EXPECT_DEATH({\n std::unique_ptr null_int_ptr;\n check_not_null(std::move(null_int_ptr));\n }, \"Check failed: .* != nullptr\");\n}\n\nTEST_F(NotNullTest, Move) {\n not_null> int_ptr1 = make_not_null_unique(3);\n#if !PRINCIPIA_COMPILER_MSVC || \\\n !(_MSC_FULL_VER == 190'023'506 || \\\n _MSC_FULL_VER == 190'023'918 || \\\n _MSC_FULL_VER == 190'024'210 || \\\n _MSC_FULL_VER == 190'024'213 || \\\n _MSC_FULL_VER == 190'024'215 || \\\n _MSC_FULL_VER == 191'326'215 || \\\n _MSC_FULL_VER == 191'426'316 || \\\n _MSC_FULL_VER == 191'426'412 || \\\n _MSC_FULL_VER == 191'426'428 || \\\n _MSC_FULL_VER == 191'426'429 || \\\n _MSC_FULL_VER == 191'526'608 || \\\n _MSC_FULL_VER == 191'526'731 || \\\n _MSC_FULL_VER == 191'627'024 || \\\n _MSC_FULL_VER == 191'627'025 || \\\n _MSC_FULL_VER == 191'627'027 || \\\n _MSC_FULL_VER == 192'027'508 || \\\n _MSC_FULL_VER == 192'227'706 || \\\n _MSC_FULL_VER == 192'227'724 || \\\n _MSC_FULL_VER == 192'227'905 || \\\n _MSC_FULL_VER == 192'328'106 || \\\n _MSC_FULL_VER == 192'428'314 || \\\n _MSC_FULL_VER == 192'428'316)\n EXPECT_THAT(*(std::unique_ptr const&)int_ptr1, Eq(3));\n#endif\n not_null> int_ptr2 = std::move(int_ptr1);\n EXPECT_THAT(*int_ptr2, Eq(3));\n not_null> int_ptr3(std::move(int_ptr2));\n EXPECT_THAT(*int_ptr3, Eq(3));\n int_ptr2 = make_not_null_unique(5);\n EXPECT_THAT(*int_ptr2, Eq(5));\n int_ptr2 = std::move(int_ptr3);\n EXPECT_THAT(*int_ptr2, Eq(3));\n}\n\nTEST_F(NotNullTest, Copy) {\n std::unique_ptr const owner_of_three = std::make_unique(3);\n std::unique_ptr const owner_of_five = std::make_unique(5);\n not_null const int_ptr1 = check_not_null(owner_of_three.get());\n not_null int_ptr2 = int_ptr1;\n not_null const int_ptr3(int_ptr2);\n EXPECT_THAT(int_ptr1, Eq(owner_of_three.get()));\n EXPECT_THAT(int_ptr2, Eq(owner_of_three.get()));\n EXPECT_THAT(int_ptr3, Eq(owner_of_three.get()));\n EXPECT_THAT(*int_ptr1, Eq(3));\n EXPECT_THAT(*int_ptr2, Eq(3));\n EXPECT_THAT(*int_ptr3, Eq(3));\n int_ptr2 = check_not_null(owner_of_five.get());\n EXPECT_THAT(*int_ptr2, Eq(5));\n int_ptr2 = int_ptr3;\n EXPECT_THAT(*int_ptr2, Eq(3));\n EXPECT_THAT(*int_ptr3, Eq(3));\n}\n\nTEST_F(NotNullTest, CheckNotNull) {\n#if 0\n std::unique_ptr owner_int = std::make_unique(3);\n int* const constant_access_int = owner_int.get();\n not_null const constant_not_null_access_int =\n check_not_null(constant_access_int);\n check_not_null(constant_not_null_access_int);\n not_null> not_null_owner_int =\n check_not_null(std::move(owner_int));\n check_not_null(std::move(not_null_owner_int));\n#endif\n}\n\nTEST_F(NotNullTest, Booleans) {\n not_null> const pointer = make_not_null_unique(3);\n EXPECT_TRUE(pointer);\n EXPECT_TRUE(pointer != nullptr);\n EXPECT_FALSE(pointer == nullptr);\n}\n\nTEST_F(NotNullTest, ImplicitConversions) {\n not_null> not_null_owner_int =\n make_not_null_unique(3);\n not_null const constant_not_null_access_int =\n not_null_owner_int.get();\n \/\/ Copy constructor.\n not_null not_null_access_constant_int =\n constant_not_null_access_int;\n \/\/ Copy assignment.\n not_null_access_constant_int = not_null_owner_int.get();\n \/\/ Move constructor.\n not_null> not_null_owner_constant_int =\n make_not_null_unique(5);\n \/\/ Move assignment.\n not_null_owner_constant_int = std::move(not_null_owner_int);\n}\n\nTEST_F(NotNullTest, Arrow) {\n not_null> not_null_owner_string =\n make_not_null_unique(\"-\");\n not_null_owner_string->append(\">\");\n EXPECT_THAT(*not_null_owner_string, Eq(\"->\"));\n not_null not_null_access_string = not_null_owner_string.get();\n not_null_access_string->insert(0, \"operator\");\n EXPECT_THAT(*not_null_access_string, Eq(\"operator->\"));\n}\n\nTEST_F(NotNullTest, NotNullNotNull) {\n not_null> owner = make_not_null_unique(42);\n not_null> x = owner.get();\n not_null y = x;\n *x = 6 * 9;\n EXPECT_THAT(*owner, Eq(6 * 9));\n EXPECT_THAT(*x, Eq(6 * 9));\n EXPECT_THAT(*y, Eq(6 * 9));\n}\n\nTEST_F(NotNullTest, CheckArguments) {\n not_null> accumulator = make_not_null_unique(21);\n std::unique_ptr twenty_one = std::make_unique(21);\n Add(accumulator.get(), check_not_null(twenty_one.get()));\n EXPECT_THAT(*twenty_one, Eq(21));\n EXPECT_THAT(*accumulator, Eq(42));\n#if 0\n Sub(check_not_null(accumulator.get()), check_not_null(twenty_one.get()));\n EXPECT_THAT(*accumulator, Eq(21));\n#endif\n}\n\nTEST_F(NotNullTest, DynamicCast) {\n class Base {\n public:\n virtual ~Base() = default;\n };\n class Derived : public Base {};\n {\n not_null b = new Derived;\n [[maybe_unused]] not_null d = dynamic_cast_not_null(b);\n delete b;\n }\n {\n not_null> b = make_not_null_unique();\n not_null> d =\n dynamic_cast_not_null>(std::move(b));\n }\n}\n\nTEST_F(NotNullTest, RValue) {\n std::unique_ptr owner_int = std::make_unique(1);\n not_null not_null_int = new int(2);\n EXPECT_NE(owner_int.get(), not_null_int);\n\n not_null> not_null_owner_int =\n make_not_null_unique(4);\n std::vector v1;\n \/\/ |v1.push_back| would be ambiguous here if |not_null| had an\n \/\/ |operator pointer const&() const&| instead of an\n \/\/ |operator pointer const&&() const&|.\n v1.push_back(not_null_owner_int.get());\n \/\/ |emplace_back| is fine no matter what.\n v1.emplace_back(not_null_owner_int.get());\n EXPECT_EQ(4, *v1[0]);\n EXPECT_EQ(4, *not_null_owner_int);\n\n std::vector v2;\n \/\/ NOTE(egg): The following fails using clang, I'm not sure where the bug is.\n \/\/ More generally, if functions |foo(int*&&)| and |foo(int* const&)| exist,\n \/\/ |foo(non_rvalue_not_null)| fails to compile with clang (\"no viable\n \/\/ conversion\"), but without the |foo(int*&&)| overload it compiles.\n \/\/ This is easily circumvented using a temporary (whereas the ambiguity that\n \/\/ would result from having an |operator pointer const&() const&| would\n \/\/ entirely prevent conversion of |not_null>| to\n \/\/ |unique_ptr|), so we ignore it.\n#if PRINCIPIA_COMPILER_MSVC\n v2.push_back(not_null_int);\n#else\n int* const temporary = not_null_int;\n v2.push_back(temporary);\n#endif\n EXPECT_EQ(2, *v2[0]);\n EXPECT_EQ(2, *not_null_int);\n\n \/\/ |std::unique_ptr::operator=| would be ambiguous here between the move\n \/\/ and copy assignments if |not_null| had an\n \/\/ |operator pointer const&() const&| instead of an\n \/\/ |operator pointer const&&() const&|.\n \/\/ Note that one of the overloads (the implicit copy assignment operator) is\n \/\/ deleted, but this does not matter for overload resolution; however MSVC\n \/\/ compiles this even when it is ambiguous, while clang correctly fails.\n owner_int = make_not_null_unique(1729);\n\n not_null not_null_access_int = owner_int.get();\n [[maybe_unused]] int const* access_const_int = not_null_access_int;\n\n not_null> not_null_shared_int = std::make_shared(3);\n \/\/ This exercises |operator OtherPointer() const&|. The conversion from\n \/\/ |not_null| to |int const*| does not; instead it goes through the\n \/\/ conversion |not_null| -> |int*| -> |int const*|, where the latter is\n \/\/ a qualification adjustment, part of a standard conversion sequence.\n std::shared_ptr shared_const_int = not_null_shared_int;\n\n \/\/ MSVC seems to be confused by templatized move-conversion operators.\n#if PRINCIPIA_COMPILER_MSVC\n \/\/ Uses |not_null(not_null&& other)| followed by\n \/\/ |operator pointer&&() &&|, so the first conversion has to be explicit.\n std::unique_ptr owner_const_int =\n static_cast>>(\n make_not_null_unique(5));\n#else\n \/\/ Uses |operator OtherPointer() &&|.\n std::unique_ptr owner_const_int = make_not_null_unique(5);\n#endif\n EXPECT_EQ(5, *owner_const_int);\n}\n\n} \/\/ namespace base\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"extern \"C\" {\n#include \"ets_sys.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"ets_rom.h\"\n}\n\n#include \n#include \n#include \n\n#include \"os\/os.h\"\n#include \"utils\/blinker.h\"\n#include \"hardware.hxx\"\n#include \"freertos\/bootloader_hal.h\"\n\nnamespace nmranet {\nextern char CONFIG_FILENAME[];\n}\n\nextern \"C\" {\n\nextern void ets_delay_us(uint32_t us);\n\nvoid resetblink(uint32_t pattern)\n{\n if (pattern)\n {\n HW::BLINKER_RAW_Pin::set(!HW::blinker_invert);\n }\n else\n {\n HW::BLINKER_RAW_Pin::set(HW::blinker_invert);\n }\n}\n\nvoid setblink(uint32_t pattern)\n{\n resetblink(pattern);\n}\n\nvoid __attribute__((noreturn)) diewith(uint32_t pattern)\n{\n extern void ets_wdt_disable();\n ets_wdt_disable();\n uint32_t p = 0;\n while(true) {\n if (p & 1) {\n HW::BLINKER_RAW_Pin::set(!HW::blinker_invert);\n } else {\n HW::BLINKER_RAW_Pin::set(HW::blinker_invert);\n }\n p >>= 1;\n if (!p) p = pattern;\n ets_delay_us(125000);\n }\n \/*\n resetblink(pattern);\n while (1)\n ;*\/\n}\n\nvoid ICACHE_FLASH_ATTR abort() {\n diewith(BLINK_DIE_ABORT);\n}\n\nvoid ICACHE_FLASH_ATTR usleep(useconds_t sleep_usec)\n{\n ets_delay_us(sleep_usec);\n}\n\n\/\/static os_event_t appl_task_event[1];\n\nvoid ICACHE_FLASH_ATTR appl_task(os_event_t *e)\n{\n static int argc = 0;\n static char **argv = {0};\n appl_main(argc, argv);\n}\n\nstruct _reent* _impure_ptr = nullptr;\n\nchar noerror[] = \"strerror output\";\n\nchar* strerror(int) {\n return noerror;\n}\n\nextern void (*__init_array_start)(void);\nextern void (*__init_array_end)(void);\n\nstatic void do_global_ctors(void) {\n void (**p)(void);\n for(p = &__init_array_start; p != &__init_array_end; ++p)\n (*p)();\n}\n\nextern void spiffs_init();\n\nvoid init_done() {\n system_set_os_print(1);\n \/\/gdb_init();\n do_global_ctors();\n spiffs_init();\n \/\/ Try to open the config file\n int fd = ::open(nmranet::CONFIG_FILENAME, O_RDONLY);\n if (fd < 0) fd = ::open(nmranet::CONFIG_FILENAME, O_CREAT|O_TRUNC|O_RDWR);\n if (fd < 0) {\n printf(\"Formatting the SPIFFS fs.\");\n extern void esp_spiffs_deinit(uint8_t);\n esp_spiffs_deinit(1);\n spiffs_init();\n }\n\n appl_task(nullptr);\n}\n\nextern \"C\" void system_restart_local();\n\nvoid reboot_now() {\n system_restart_local();\n}\n\nvoid reboot() {\n system_restart_local();\n}\n\nvoid enter_bootloader() {\n extern uint32_t __bootloader_magic_ptr;\n __bootloader_magic_ptr = REQUEST_BOOTLOADER;\n \n system_restart_local();\n}\n\nvoid ICACHE_FLASH_ATTR user_init()\n{\n gpio_init();\n HW::BLINKER_RAW_Pin::hw_init();\n HW::BLINKER_RAW_Pin::hw_set_to_safe();\n HW::GpioBootloaderInit::hw_init();\n\n \/\/uart_div_modify(0, UART_CLK_FREQ \/ (74880));\n uart_div_modify(0, UART_CLK_FREQ \/ (115200));\n\n \/\/abort();\n\n \/\/uart_init(74880, 74880);\n\n os_printf(\"hello,world\\n\");\n \/\/ init gpio subsytem\n system_init_done_cb(&init_done);\n\n \/\/ static os_task_t appl_task_struct;\n \/\/ system_os_task(appl_task, USER_TASK_PRIO_0, appl_task_event, 1);\n\n}\n\n\n} \/\/ extern \"C\"\n\nvoid log_output(char* buf, int size) {\n if (size <= 0) return;\n printf(\"%s\\n\", buf);\n}\nAdds more debugging.extern \"C\" {\n#include \"ets_sys.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"ets_rom.h\"\n}\n\n#include \n#include \n#include \n\n#include \"os\/os.h\"\n#include \"utils\/blinker.h\"\n#include \"hardware.hxx\"\n#include \"freertos\/bootloader_hal.h\"\n\nnamespace nmranet {\nextern char CONFIG_FILENAME[];\n}\n\nextern \"C\" {\n\nextern void ets_delay_us(uint32_t us);\n\nvoid resetblink(uint32_t pattern)\n{\n if (pattern)\n {\n HW::BLINKER_RAW_Pin::set(!HW::blinker_invert);\n }\n else\n {\n HW::BLINKER_RAW_Pin::set(HW::blinker_invert);\n }\n}\n\nvoid setblink(uint32_t pattern)\n{\n resetblink(pattern);\n}\n\nvoid __attribute__((noreturn)) diewith(uint32_t pattern)\n{\n extern void ets_wdt_disable();\n ets_wdt_disable();\n uint32_t p = 0;\n while(true) {\n if (p & 1) {\n HW::BLINKER_RAW_Pin::set(!HW::blinker_invert);\n } else {\n HW::BLINKER_RAW_Pin::set(HW::blinker_invert);\n }\n p >>= 1;\n if (!p) p = pattern;\n ets_delay_us(125000);\n }\n \/*\n resetblink(pattern);\n while (1)\n ;*\/\n}\n\nvoid ICACHE_FLASH_ATTR abort() {\n diewith(BLINK_DIE_ABORT);\n}\n\nvoid ICACHE_FLASH_ATTR usleep(useconds_t sleep_usec)\n{\n ets_delay_us(sleep_usec);\n}\n\n\/\/static os_event_t appl_task_event[1];\n\nvoid ICACHE_FLASH_ATTR appl_task(os_event_t *e)\n{\n static int argc = 0;\n static char **argv = {0};\n appl_main(argc, argv);\n}\n\nstruct _reent* _impure_ptr = nullptr;\n\nchar noerror[] = \"strerror output\";\n\nchar* strerror(int) {\n return noerror;\n}\n\nextern void (*__init_array_start)(void);\nextern void (*__init_array_end)(void);\n\nstatic void do_global_ctors(void) {\n void (**p)(void);\n for(p = &__init_array_start; p != &__init_array_end; ++p)\n (*p)();\n}\n\nextern void spiffs_init();\n\nvoid init_done() {\n system_set_os_print(1);\n \/\/gdb_init();\n do_global_ctors();\n spiffs_init();\n \/\/ Try to open the config file\n int fd = ::open(nmranet::CONFIG_FILENAME, O_RDONLY);\n if (fd < 0) fd = ::open(nmranet::CONFIG_FILENAME, O_CREAT|O_TRUNC|O_RDWR);\n if (fd < 0) {\n printf(\"Formatting the SPIFFS fs.\");\n extern void esp_spiffs_deinit(uint8_t);\n esp_spiffs_deinit(1);\n spiffs_init();\n }\n\n printf(\"userinit pinout: B hi %d; B lo %d; A hi %d; A lo %d;\\n\",\n HW::MOT_B_HI_Pin::PIN, \n HW::MOT_B_LO_Pin::PIN, \n HW::MOT_A_HI_Pin::PIN, \n HW::MOT_A_LO_Pin::PIN);\n appl_task(nullptr);\n}\n\nextern \"C\" void system_restart_local();\n\nvoid reboot_now() {\n system_restart_local();\n}\n\nvoid reboot() {\n system_restart_local();\n}\n\nvoid enter_bootloader() {\n extern uint32_t __bootloader_magic_ptr;\n __bootloader_magic_ptr = REQUEST_BOOTLOADER;\n \n system_restart_local();\n}\n\nvoid ICACHE_FLASH_ATTR user_init()\n{\n gpio_init();\n HW::BLINKER_RAW_Pin::hw_init();\n HW::BLINKER_RAW_Pin::hw_set_to_safe();\n HW::GpioBootloaderInit::hw_init();\n\n \/\/uart_div_modify(0, UART_CLK_FREQ \/ (74880));\n uart_div_modify(0, UART_CLK_FREQ \/ (115200));\n\n \/\/abort();\n\n \/\/uart_init(74880, 74880);\n\n os_printf(\"hello,world\\n\");\n \/\/ init gpio subsytem\n system_init_done_cb(&init_done);\n\n \/\/ static os_task_t appl_task_struct;\n \/\/ system_os_task(appl_task, USER_TASK_PRIO_0, appl_task_event, 1);\n\n}\n\n\n} \/\/ extern \"C\"\n\nvoid log_output(char* buf, int size) {\n if (size <= 0) return;\n printf(\"%s\\n\", buf);\n}\n<|endoftext|>"} {"text":"#pragma once\r\n#include \r\n#include \r\n#include \r\n\r\n#include \"maths\/maths.hpp\"\r\n\r\ntemplate\r\nclass Rational {\r\npublic:\r\n\tstatic_assert(std::is_integral::value, \"Base type of Rational must be an integral.\");\r\n\r\n\tconstexpr Rational() : Rational(0) {}\r\n\tconstexpr Rational(const T a) : a_(a), b_(1) {}\r\n\tRational(const T a, const T b) : a_(a), b_(b) {\r\n\t\tnormalize();\r\n\t}\r\n\r\n\tvoid swap(Rational& rhs) {\r\n\t\tstd::swap(a_, rhs.a_);\r\n\t\tstd::swap(b_, rhs.b_);\r\n\t}\r\n\r\n\tconstexpr operator bool() const {\r\n\t\treturn a_ != 0;\r\n\t}\r\n\r\n\tconstexpr operator T() const {\r\n\t\treturn to_int();\r\n\t}\r\n\r\n\tconstexpr operator long double() const {\r\n\t\treturn to_double();\r\n\t}\r\n\r\n\tstd::string to_string() const {\r\n\t\treturn std::to_string(a_) + \"\/\" + std::to_string(b_);\r\n\t}\r\n\r\n\tconstexpr bool operator !() const {\r\n\t\treturn a_ == 0;\r\n\t}\r\n\r\n\tconstexpr Rational operator -() const {\r\n\t\treturn negate();\r\n\t}\r\n\r\n\tconstexpr Rational operator +() const {\r\n\t\treturn{ a_, b_ };\r\n\t}\r\n\r\n\tRational& operator ++() {\r\n\t\ta_ += b_;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRational operator ++(int) {\r\n\t\ta_ += b_;\r\n\t\treturn {a_ - b_, b_};\r\n\t}\r\n\r\n\tRational& operator --() {\r\n\t\ta_ -= b_;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRational operator --(int) {\r\n\t\ta_ -= b_;\r\n\t\treturn{ a_ + b_, b_ };\r\n\t}\r\n\r\n\tconstexpr Rational add(const Rational& rhs) const {\r\n\t\treturn{ a_ * rhs.b_ + rhs.a_ * b_, b_ * rhs.b_ };\r\n\t}\r\n\r\n\tconstexpr Rational subtract(const Rational& rhs) const {\r\n\t\treturn add(rhs.negate());\r\n\t}\r\n\r\n\tconstexpr Rational multiply(const Rational& rhs) const {\r\n\t\treturn{ a_ * rhs.a_, b_ * rhs.b_ };\r\n\t}\r\n\r\n\tconstexpr Rational divide(const Rational& rhs) const {\r\n\t\treturn{ a_ * rhs.b_, b_ * rhs.a_ };\r\n\t}\r\n\r\n\tconstexpr Rational operator +(const Rational& rhs) const {\r\n\t\treturn add(rhs);\r\n\t}\r\n\r\n\tconstexpr Rational operator -(const Rational& rhs) const {\r\n\t\treturn subtract(rhs);\r\n\t}\r\n\r\n\tconstexpr Rational operator *(const Rational& rhs) const {\r\n\t\treturn multiply(rhs);\r\n\t}\r\n\r\n\tconstexpr Rational operator \/(const Rational& rhs) const {\r\n\t\treturn divide(rhs);\r\n\t}\r\n\r\n\tRational& operator +=(const Rational& rhs) {\r\n\t\tRational res = add(rhs);\r\n\t\tswap(res);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRational& operator -=(const Rational& rhs) {\r\n\t\tRational res = subtract(rhs);\r\n\t\tswap(res);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRational& operator *=(const Rational& rhs) {\r\n\t\tRational res = multiply(rhs);\r\n\t\tswap(res);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRational& operator \/=(const Rational& x) {\r\n\t\tRational res = divide(rhs);\r\n\t\tswap(res);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tconstexpr friend bool operator ==(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn lhs.a_ == rhs.a_ && lhs.b_ == rhs.b_;\r\n\t}\r\n\r\n\tconstexpr friend bool operator !=(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn !(lhs == rhs);\r\n\t}\r\n\r\n\tconstexpr friend bool operator <(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn lhs.a_ * rhs.b_ < lhs.a_ * rhs.b_;\r\n\t}\r\n\r\n\tconstexpr friend bool operator >(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn rhs < lhs;\r\n\t}\r\n\r\n\tconstexpr friend bool operator <=(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn lhs.a_ * rhs.b_ <= lhs.a_ * rhs.b_;\r\n\t}\r\n\r\n\tconstexpr friend bool operator >=(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn rhs <= lhs;\r\n\t}\r\n\r\n\tfriend std::ostream& operator << (std::ostream& out, const Rational& rational) {\r\n\t\treturn out << rational.a_ << \" \" << rational.b_;\r\n\t}\r\n\r\n\tfriend std::istream& operator >> (std::istream& in, Rational& rational) {\r\n\t\tin >> rational .a_ >> rational.b_;\r\n\t\trational.normalize();\r\n\t\treturn in;\r\n\t}\r\n\r\n\tvoid normalize() {\r\n\t\tconst T g = gcd(a_, b_);\r\n\t\ta_ \/= g;\r\n\t\tb_ \/= g;\r\n\t\tif (b_ < 0) {\r\n\t\t\ta_ = -a_;\r\n\t\t\tb_ = -b_;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid read_slash(std::istream& in) {\r\n\t\tchar ch;\r\n\t\tin >> a_ >> ch >> b_;\r\n\t\tnormalize();\r\n\t}\r\n\r\n\tvoid print_slash(std::ostream& out) const {\r\n\t\tout << a_ << \"\/\" << b_;\r\n\t}\r\n\r\n\tconstexpr Rational negate() const {\r\n\t\treturn{ -a_, b_ };\r\n\t}\r\n\r\n\tconstexpr Rational abs() const {\r\n\t\treturn a_ < 0 ? Rational(-a_, b_) : Rational(a_, b_);\r\n\t}\r\n\r\n\tconstexpr Rational inverse() const {\r\n\t\treturn{ b_, a_ };\r\n\t}\r\n\r\n\tconstexpr int sign() const {\r\n\t\treturn a_ < 0 ? -1 : static_cast(a_ > 0);\r\n\t}\r\n\r\n\tconstexpr long double to_double() const {\r\n\t\treturn static_cast(a_) \/ b_;\r\n\t}\r\n\r\n\tconstexpr T to_int() const {\r\n\t\treturn a_ \/ b_;\r\n\t}\r\n\r\n\tconstexpr T floor() const {\r\n\t\treturn to_int();\r\n\t}\r\n\r\n\tconstexpr T ceil() const {\r\n\t\treturn static_cast(ceil(to_double() - EPS));\r\n\t}\r\n\r\n\tconstexpr T round() const {\r\n\t\tconst long double cur = to_double();\r\n\t\treturn static_cast(cur < 0 ? ceil(cur - 0.5 - EPS) : floor(cur + 0.5 + EPS));\r\n\t}\r\n\r\n\tconstexpr long double frac() const {\r\n\t\treturn to_double() - to_int();\r\n\t}\r\n\r\n\tconstexpr Rational pow(const ll n) const {\r\n\t\treturn{ binpow(a_, n), binpow(b_, n) };\r\n\t}\r\n\r\nprivate:\r\n\tT a_;\r\n\tT b_;\r\n\r\n};\r\n\r\nnamespace std {\r\n\r\ntemplate\r\nstd::string to_string(const Rational& arg) {\r\n\treturn arg.to_string();\r\n}\r\n\r\ntemplate\r\nstruct hash> {\r\n\tsize_t operator()(const Rational& arg) const {\r\n\t\treturn hash>({ arg.a, arg.b });\r\n\t}\r\n};\r\n\r\ntemplate\r\nvoid swap(Rational& lhs, Rational& rhs) {\r\n\tlhs.swap(rhs);\r\n}\r\n\r\n}\r\nUpdated Rational class.#pragma once\r\n#include \r\n#include \r\n#include \r\n\r\n#include \"maths\/maths.hpp\"\r\n\r\ntemplate\r\nclass Rational {\r\npublic:\r\n\tstatic_assert(std::is_integral::value, \"Base type of Rational must be an integral.\");\r\n\r\n\tconstexpr Rational() : Rational(0) {}\r\n\tconstexpr Rational(const T a) : a_(a), b_(1) {}\r\n\tRational(const T a, const T b) : a_(a), b_(b) {\r\n\t\tnormalize();\r\n\t}\r\n\r\n\tvoid swap(Rational& rhs) {\r\n\t\tstd::swap(a_, rhs.a_);\r\n\t\tstd::swap(b_, rhs.b_);\r\n\t}\r\n\r\n\tconstexpr operator bool() const {\r\n\t\treturn a_ != 0;\r\n\t}\r\n\r\n\tconstexpr operator T() const {\r\n\t\treturn to_int();\r\n\t}\r\n\r\n\tconstexpr operator long double() const {\r\n\t\treturn to_double();\r\n\t}\r\n\r\n\tstd::string to_string() const {\r\n\t\treturn std::to_string(a_) + \"\/\" + std::to_string(b_);\r\n\t}\r\n\r\n\tconstexpr bool operator !() const {\r\n\t\treturn a_ == 0;\r\n\t}\r\n\r\n\tconstexpr Rational operator -() const {\r\n\t\treturn negate();\r\n\t}\r\n\r\n\tconstexpr Rational operator +() const {\r\n\t\treturn{ a_, b_ };\r\n\t}\r\n\r\n\tRational& operator ++() {\r\n\t\ta_ += b_;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRational operator ++(int) {\r\n\t\ta_ += b_;\r\n\t\treturn {a_ - b_, b_};\r\n\t}\r\n\r\n\tRational& operator --() {\r\n\t\ta_ -= b_;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRational operator --(int) {\r\n\t\ta_ -= b_;\r\n\t\treturn{ a_ + b_, b_ };\r\n\t}\r\n\r\n\tconstexpr Rational add(const Rational& rhs) const {\r\n\t\treturn{ a_ * rhs.b_ + rhs.a_ * b_, b_ * rhs.b_ };\r\n\t}\r\n\r\n\tconstexpr Rational subtract(const Rational& rhs) const {\r\n\t\treturn add(rhs.negate());\r\n\t}\r\n\r\n\tconstexpr Rational multiply(const Rational& rhs) const {\r\n\t\treturn{ a_ * rhs.a_, b_ * rhs.b_ };\r\n\t}\r\n\r\n\tconstexpr Rational divide(const Rational& rhs) const {\r\n\t\treturn{ a_ * rhs.b_, b_ * rhs.a_ };\r\n\t}\r\n\r\n\tconstexpr Rational operator +(const Rational& rhs) const {\r\n\t\treturn add(rhs);\r\n\t}\r\n\r\n\tconstexpr Rational operator -(const Rational& rhs) const {\r\n\t\treturn subtract(rhs);\r\n\t}\r\n\r\n\tconstexpr Rational operator *(const Rational& rhs) const {\r\n\t\treturn multiply(rhs);\r\n\t}\r\n\r\n\tconstexpr Rational operator \/(const Rational& rhs) const {\r\n\t\treturn divide(rhs);\r\n\t}\r\n\r\n\tconstexpr T a() const {\r\n\t\treturn a_;\r\n\t}\r\n\r\n\tconstexpr T b() const {\r\n\t\treturn b_;\r\n\t}\r\n\r\n\tRational& operator +=(const Rational& rhs) {\r\n\t\tRational res = add(rhs);\r\n\t\tswap(res);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRational& operator -=(const Rational& rhs) {\r\n\t\tRational res = subtract(rhs);\r\n\t\tswap(res);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRational& operator *=(const Rational& rhs) {\r\n\t\tRational res = multiply(rhs);\r\n\t\tswap(res);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRational& operator \/=(const Rational& x) {\r\n\t\tRational res = divide(rhs);\r\n\t\tswap(res);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tconstexpr friend bool operator ==(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn lhs.a_ == rhs.a_ && lhs.b_ == rhs.b_;\r\n\t}\r\n\r\n\tconstexpr friend bool operator !=(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn !(lhs == rhs);\r\n\t}\r\n\r\n\tconstexpr friend bool operator <(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn lhs.a_ * rhs.b_ < rhs.a_ * lhs.b_;\r\n\t}\r\n\r\n\tconstexpr friend bool operator >(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn rhs < lhs;\r\n\t}\r\n\r\n\tconstexpr friend bool operator <=(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn lhs.a_ * rhs.b_ <= rhs.a_ * lhs.b_;\r\n\t}\r\n\r\n\tconstexpr friend bool operator >=(const Rational& lhs, const Rational& rhs) {\r\n\t\treturn rhs <= lhs;\r\n\t}\r\n\r\n\tfriend std::ostream& operator << (std::ostream& out, const Rational& rational) {\r\n\t\treturn out << rational.a_ << \" \" << rational.b_;\r\n\t}\r\n\r\n\tfriend std::istream& operator >> (std::istream& in, Rational& rational) {\r\n\t\tin >> rational .a_ >> rational.b_;\r\n\t\trational.normalize();\r\n\t\treturn in;\r\n\t}\r\n\r\n\tvoid normalize() {\r\n\t\tconst T g = gcd(a_, b_);\r\n\t\ta_ \/= g;\r\n\t\tb_ \/= g;\r\n\t\tif (b_ < 0) {\r\n\t\t\ta_ = -a_;\r\n\t\t\tb_ = -b_;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid read_slash(std::istream& in) {\r\n\t\tchar ch;\r\n\t\tin >> a_ >> ch >> b_;\r\n\t\tnormalize();\r\n\t}\r\n\r\n\tvoid print_slash(std::ostream& out) const {\r\n\t\tout << a_ << \"\/\" << b_;\r\n\t}\r\n\r\n\tconstexpr Rational negate() const {\r\n\t\treturn{ -a_, b_ };\r\n\t}\r\n\r\n\tconstexpr Rational abs() const {\r\n\t\treturn a_ < 0 ? Rational(-a_, b_) : Rational(a_, b_);\r\n\t}\r\n\r\n\tconstexpr Rational inverse() const {\r\n\t\treturn{ b_, a_ };\r\n\t}\r\n\r\n\tconstexpr int sign() const {\r\n\t\treturn a_ < 0 ? -1 : static_cast(a_ > 0);\r\n\t}\r\n\r\n\tconstexpr long double to_double() const {\r\n\t\treturn static_cast(a_) \/ b_;\r\n\t}\r\n\r\n\tconstexpr T to_int() const {\r\n\t\treturn a_ \/ b_;\r\n\t}\r\n\r\n\tconstexpr T floor() const {\r\n\t\treturn to_int();\r\n\t}\r\n\r\n\tconstexpr T ceil() const {\r\n\t\treturn static_cast(ceil(to_double() - EPS));\r\n\t}\r\n\r\n\tconstexpr T round() const {\r\n\t\tconst long double cur = to_double();\r\n\t\treturn static_cast(cur < 0 ? ceil(cur - 0.5 - EPS) : floor(cur + 0.5 + EPS));\r\n\t}\r\n\r\n\tconstexpr long double frac() const {\r\n\t\treturn to_double() - to_int();\r\n\t}\r\n\r\n\tconstexpr Rational pow(const ll n) const {\r\n\t\treturn{ binpow(a_, n), binpow(b_, n) };\r\n\t}\r\n\r\nprivate:\r\n\tT a_;\r\n\tT b_;\r\n\r\n};\r\n\r\nnamespace std {\r\n\r\ntemplate\r\nstd::string to_string(const Rational& arg) {\r\n\treturn arg.to_string();\r\n}\r\n\r\ntemplate\r\nstruct hash> {\r\n\tsize_t operator()(const Rational& arg) const {\r\n\t\treturn hash>({ arg.a, arg.b });\r\n\t}\r\n};\r\n\r\ntemplate\r\nvoid swap(Rational& lhs, Rational& rhs) {\r\n\tlhs.swap(rhs);\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * extensions_manager.cpp: Extensions manager for Qt\n ****************************************************************************\n * Copyright (C) 2009-2010 VideoLAN and authors\n * $Id$\n *\n * Authors: Jean-Philippe André < jpeg # videolan.org >\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"extensions_manager.hpp\"\n#include \"input_manager.hpp\"\n#include \"dialogs\/extensions.hpp\"\n\n#include \"assert.h\"\n\n#include \n#include \n#include \n#include \n\n#define MENU_MAP(a,e) ((uint32_t)( (((uint16_t)a) << 16) | ((uint16_t)e) ))\n#define MENU_GET_ACTION(a) ( (uint16_t)( ((uint32_t)a) >> 16 ) )\n#define MENU_GET_EXTENSION(a) ( (uint16_t)( ((uint32_t)a) & 0xFFFF ) )\n\nExtensionsManager* ExtensionsManager::instance = NULL;\n\nExtensionsManager::ExtensionsManager( intf_thread_t *_p_intf, QObject *parent )\n : QObject( parent ), p_intf( _p_intf ), p_extensions_manager( NULL )\n , p_edp( NULL )\n{\n assert( ExtensionsManager::instance == NULL );\n instance = this;\n\n menuMapper = new QSignalMapper( this );\n CONNECT( menuMapper, mapped( int ), this, triggerMenu( int ) );\n CONNECT( THEMIM->getIM(), statusChanged( int ), this, playingChanged( int ) );\n DCONNECT( THEMIM, inputChanged( input_thread_t* ),\n this, inputChanged( input_thread_t* ) );\n b_unloading = false;\n b_failed = false;\n}\n\nExtensionsManager::~ExtensionsManager()\n{\n msg_Dbg( p_intf, \"Killing extension dialog provider\" );\n ExtensionsDialogProvider::killInstance();\n if( p_extensions_manager )\n {\n module_unneed( p_extensions_manager, p_extensions_manager->p_module );\n vlc_object_release( p_extensions_manager );\n }\n}\n\nbool ExtensionsManager::loadExtensions()\n{\n if( !p_extensions_manager )\n {\n p_extensions_manager = ( extensions_manager_t* )\n vlc_object_create( p_intf, sizeof( extensions_manager_t ) );\n if( !p_extensions_manager )\n {\n b_failed = true;\n emit extensionsUpdated();\n return false;\n }\n vlc_object_attach( p_extensions_manager, p_intf );\n\n p_extensions_manager->p_module =\n module_need( p_extensions_manager, \"extension\", NULL, false );\n\n if( !p_extensions_manager->p_module )\n {\n msg_Err( p_intf, \"Unable to load extensions module\" );\n vlc_object_release( p_extensions_manager );\n p_extensions_manager = NULL;\n b_failed = true;\n emit extensionsUpdated();\n return false;\n }\n\n \/* Initialize dialog provider *\/\n p_edp = ExtensionsDialogProvider::getInstance( p_intf,\n p_extensions_manager );\n if( !p_edp )\n {\n msg_Err( p_intf, \"Unable to create dialogs provider for extensions\" );\n module_unneed( p_extensions_manager,\n p_extensions_manager->p_module );\n vlc_object_release( p_extensions_manager );\n p_extensions_manager = NULL;\n b_failed = true;\n emit extensionsUpdated();\n return false;\n }\n b_unloading = false;\n }\n b_failed = false;\n emit extensionsUpdated();\n return true;\n}\n\nvoid ExtensionsManager::unloadExtensions()\n{\n if( !p_extensions_manager )\n return;\n b_unloading = true;\n module_unneed( p_extensions_manager, p_extensions_manager->p_module );\n vlc_object_release( p_extensions_manager );\n p_extensions_manager = NULL;\n emit extensionsUpdated();\n ExtensionsDialogProvider::killInstance();\n}\n\nvoid ExtensionsManager::reloadExtensions()\n{\n unloadExtensions();\n loadExtensions();\n emit extensionsUpdated();\n}\n\nvoid ExtensionsManager::menu( QMenu *current )\n{\n assert( current != NULL );\n if( !isLoaded() )\n {\n \/\/ This case can happen: do nothing\n return;\n }\n\n vlc_mutex_lock( &p_extensions_manager->lock );\n\n QAction *action;\n extension_t *p_ext = NULL;\n int i_ext = 0;\n FOREACH_ARRAY( p_ext, p_extensions_manager->extensions )\n {\n bool b_Active = extension_IsActivated( p_extensions_manager, p_ext );\n\n if( b_Active && extension_HasMenu( p_extensions_manager, p_ext ) )\n {\n QMenu *submenu = new QMenu( qfu( p_ext->psz_title ) );\n char **ppsz_titles = NULL;\n uint16_t *pi_ids = NULL;\n size_t i_num = 0;\n action = current->addMenu( submenu );\n\n action->setCheckable( true );\n action->setChecked( true );\n\n if( extension_GetMenu( p_extensions_manager, p_ext,\n &ppsz_titles, &pi_ids ) == VLC_SUCCESS )\n {\n for( int i = 0; ppsz_titles[i] != NULL; ++i )\n {\n ++i_num;\n action = submenu->addAction( qfu( ppsz_titles[i] ) );\n menuMapper->setMapping( action,\n MENU_MAP( pi_ids[i], i_ext ) );\n CONNECT( action, triggered(), menuMapper, map() );\n }\n if( !i_num )\n {\n action = submenu->addAction( qtr( \"Empty\" ) );\n action->setEnabled( false );\n }\n }\n else\n {\n msg_Warn( p_intf, \"Could not get menu for extension '%s'\",\n p_ext->psz_title );\n action = submenu->addAction( qtr( \"Empty\" ) );\n action->setEnabled( false );\n }\n\n submenu->addSeparator();\n action = submenu->addAction( QIcon( \":\/menu\/quit\" ),\n qtr( \"Deactivate\" ) );\n menuMapper->setMapping( action, MENU_MAP( 0, i_ext ) );\n CONNECT( action, triggered(), menuMapper, map() );\n }\n else\n {\n action = current->addAction( qfu( p_ext->psz_title ) );\n menuMapper->setMapping( action, MENU_MAP( 0, i_ext ) );\n CONNECT( action, triggered(), menuMapper, map() );\n\n if( !extension_TriggerOnly( p_extensions_manager, p_ext ) )\n {\n action->setCheckable( true );\n action->setChecked( b_Active );\n }\n }\n i_ext++;\n }\n FOREACH_END()\n\n vlc_mutex_unlock( &p_extensions_manager->lock );\n}\n\nvoid ExtensionsManager::triggerMenu( int id )\n{\n uint16_t i_ext = MENU_GET_EXTENSION( id );\n uint16_t i_action = MENU_GET_ACTION( id );\n\n vlc_mutex_lock( &p_extensions_manager->lock );\n\n if( (int) i_ext > p_extensions_manager->extensions.i_size )\n {\n msg_Dbg( p_intf, \"can't trigger extension with wrong id %d\",\n (int) i_ext );\n return;\n }\n\n extension_t *p_ext = ARRAY_VAL( p_extensions_manager->extensions, i_ext );\n assert( p_ext != NULL);\n\n vlc_mutex_unlock( &p_extensions_manager->lock );\n\n if( i_action == 0 )\n {\n msg_Dbg( p_intf, \"activating or triggering extension '%s'\",\n p_ext->psz_title );\n\n if( extension_TriggerOnly( p_extensions_manager, p_ext ) )\n {\n extension_Trigger( p_extensions_manager, p_ext );\n }\n else\n {\n if( !extension_IsActivated( p_extensions_manager, p_ext ) )\n extension_Activate( p_extensions_manager, p_ext );\n else\n extension_Deactivate( p_extensions_manager, p_ext );\n }\n }\n else\n {\n msg_Dbg( p_intf, \"triggering extension '%s', on menu with id = 0x%x\",\n p_ext->psz_title, i_action );\n\n extension_TriggerMenu( p_extensions_manager, p_ext, i_action );\n }\n}\n\nvoid ExtensionsManager::inputChanged( input_thread_t* p_input )\n{\n \/\/This is unlikely, but can happen if no extension modules can be loaded.\n if ( p_extensions_manager == NULL )\n return ;\n vlc_mutex_lock( &p_extensions_manager->lock );\n\n extension_t *p_ext;\n FOREACH_ARRAY( p_ext, p_extensions_manager->extensions )\n {\n if( extension_IsActivated( p_extensions_manager, p_ext ) )\n {\n extension_SetInput( p_extensions_manager, p_ext, p_input );\n }\n }\n FOREACH_END()\n\n vlc_mutex_unlock( &p_extensions_manager->lock );\n}\n\nvoid ExtensionsManager::playingChanged( int state )\n{\n \/\/This is unlikely, but can happen if no extension modules can be loaded.\n if ( p_extensions_manager == NULL )\n return ;\n vlc_mutex_lock( &p_extensions_manager->lock );\n\n extension_t *p_ext;\n FOREACH_ARRAY( p_ext, p_extensions_manager->extensions )\n {\n if( extension_IsActivated( p_extensions_manager, p_ext ) )\n {\n extension_PlayingChanged( p_extensions_manager, p_ext, state );\n }\n }\n FOREACH_END()\n\n vlc_mutex_unlock( &p_extensions_manager->lock );\n}\nqt4: fix another QMenu without parent\/*****************************************************************************\n * extensions_manager.cpp: Extensions manager for Qt\n ****************************************************************************\n * Copyright (C) 2009-2010 VideoLAN and authors\n * $Id$\n *\n * Authors: Jean-Philippe André < jpeg # videolan.org >\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"extensions_manager.hpp\"\n#include \"input_manager.hpp\"\n#include \"dialogs\/extensions.hpp\"\n\n#include \"assert.h\"\n\n#include \n#include \n#include \n#include \n\n#define MENU_MAP(a,e) ((uint32_t)( (((uint16_t)a) << 16) | ((uint16_t)e) ))\n#define MENU_GET_ACTION(a) ( (uint16_t)( ((uint32_t)a) >> 16 ) )\n#define MENU_GET_EXTENSION(a) ( (uint16_t)( ((uint32_t)a) & 0xFFFF ) )\n\nExtensionsManager* ExtensionsManager::instance = NULL;\n\nExtensionsManager::ExtensionsManager( intf_thread_t *_p_intf, QObject *parent )\n : QObject( parent ), p_intf( _p_intf ), p_extensions_manager( NULL )\n , p_edp( NULL )\n{\n assert( ExtensionsManager::instance == NULL );\n instance = this;\n\n menuMapper = new QSignalMapper( this );\n CONNECT( menuMapper, mapped( int ), this, triggerMenu( int ) );\n CONNECT( THEMIM->getIM(), statusChanged( int ), this, playingChanged( int ) );\n DCONNECT( THEMIM, inputChanged( input_thread_t* ),\n this, inputChanged( input_thread_t* ) );\n b_unloading = false;\n b_failed = false;\n}\n\nExtensionsManager::~ExtensionsManager()\n{\n msg_Dbg( p_intf, \"Killing extension dialog provider\" );\n ExtensionsDialogProvider::killInstance();\n if( p_extensions_manager )\n {\n module_unneed( p_extensions_manager, p_extensions_manager->p_module );\n vlc_object_release( p_extensions_manager );\n }\n}\n\nbool ExtensionsManager::loadExtensions()\n{\n if( !p_extensions_manager )\n {\n p_extensions_manager = ( extensions_manager_t* )\n vlc_object_create( p_intf, sizeof( extensions_manager_t ) );\n if( !p_extensions_manager )\n {\n b_failed = true;\n emit extensionsUpdated();\n return false;\n }\n vlc_object_attach( p_extensions_manager, p_intf );\n\n p_extensions_manager->p_module =\n module_need( p_extensions_manager, \"extension\", NULL, false );\n\n if( !p_extensions_manager->p_module )\n {\n msg_Err( p_intf, \"Unable to load extensions module\" );\n vlc_object_release( p_extensions_manager );\n p_extensions_manager = NULL;\n b_failed = true;\n emit extensionsUpdated();\n return false;\n }\n\n \/* Initialize dialog provider *\/\n p_edp = ExtensionsDialogProvider::getInstance( p_intf,\n p_extensions_manager );\n if( !p_edp )\n {\n msg_Err( p_intf, \"Unable to create dialogs provider for extensions\" );\n module_unneed( p_extensions_manager,\n p_extensions_manager->p_module );\n vlc_object_release( p_extensions_manager );\n p_extensions_manager = NULL;\n b_failed = true;\n emit extensionsUpdated();\n return false;\n }\n b_unloading = false;\n }\n b_failed = false;\n emit extensionsUpdated();\n return true;\n}\n\nvoid ExtensionsManager::unloadExtensions()\n{\n if( !p_extensions_manager )\n return;\n b_unloading = true;\n module_unneed( p_extensions_manager, p_extensions_manager->p_module );\n vlc_object_release( p_extensions_manager );\n p_extensions_manager = NULL;\n emit extensionsUpdated();\n ExtensionsDialogProvider::killInstance();\n}\n\nvoid ExtensionsManager::reloadExtensions()\n{\n unloadExtensions();\n loadExtensions();\n emit extensionsUpdated();\n}\n\nvoid ExtensionsManager::menu( QMenu *current )\n{\n assert( current != NULL );\n if( !isLoaded() )\n {\n \/\/ This case can happen: do nothing\n return;\n }\n\n vlc_mutex_lock( &p_extensions_manager->lock );\n\n QAction *action;\n extension_t *p_ext = NULL;\n int i_ext = 0;\n FOREACH_ARRAY( p_ext, p_extensions_manager->extensions )\n {\n bool b_Active = extension_IsActivated( p_extensions_manager, p_ext );\n\n if( b_Active && extension_HasMenu( p_extensions_manager, p_ext ) )\n {\n QMenu *submenu = new QMenu( qfu( p_ext->psz_title ), current );\n char **ppsz_titles = NULL;\n uint16_t *pi_ids = NULL;\n size_t i_num = 0;\n action = current->addMenu( submenu );\n\n action->setCheckable( true );\n action->setChecked( true );\n\n if( extension_GetMenu( p_extensions_manager, p_ext,\n &ppsz_titles, &pi_ids ) == VLC_SUCCESS )\n {\n for( int i = 0; ppsz_titles[i] != NULL; ++i )\n {\n ++i_num;\n action = submenu->addAction( qfu( ppsz_titles[i] ) );\n menuMapper->setMapping( action,\n MENU_MAP( pi_ids[i], i_ext ) );\n CONNECT( action, triggered(), menuMapper, map() );\n }\n if( !i_num )\n {\n action = submenu->addAction( qtr( \"Empty\" ) );\n action->setEnabled( false );\n }\n }\n else\n {\n msg_Warn( p_intf, \"Could not get menu for extension '%s'\",\n p_ext->psz_title );\n action = submenu->addAction( qtr( \"Empty\" ) );\n action->setEnabled( false );\n }\n\n submenu->addSeparator();\n action = submenu->addAction( QIcon( \":\/menu\/quit\" ),\n qtr( \"Deactivate\" ) );\n menuMapper->setMapping( action, MENU_MAP( 0, i_ext ) );\n CONNECT( action, triggered(), menuMapper, map() );\n }\n else\n {\n action = current->addAction( qfu( p_ext->psz_title ) );\n menuMapper->setMapping( action, MENU_MAP( 0, i_ext ) );\n CONNECT( action, triggered(), menuMapper, map() );\n\n if( !extension_TriggerOnly( p_extensions_manager, p_ext ) )\n {\n action->setCheckable( true );\n action->setChecked( b_Active );\n }\n }\n i_ext++;\n }\n FOREACH_END()\n\n vlc_mutex_unlock( &p_extensions_manager->lock );\n}\n\nvoid ExtensionsManager::triggerMenu( int id )\n{\n uint16_t i_ext = MENU_GET_EXTENSION( id );\n uint16_t i_action = MENU_GET_ACTION( id );\n\n vlc_mutex_lock( &p_extensions_manager->lock );\n\n if( (int) i_ext > p_extensions_manager->extensions.i_size )\n {\n msg_Dbg( p_intf, \"can't trigger extension with wrong id %d\",\n (int) i_ext );\n return;\n }\n\n extension_t *p_ext = ARRAY_VAL( p_extensions_manager->extensions, i_ext );\n assert( p_ext != NULL);\n\n vlc_mutex_unlock( &p_extensions_manager->lock );\n\n if( i_action == 0 )\n {\n msg_Dbg( p_intf, \"activating or triggering extension '%s'\",\n p_ext->psz_title );\n\n if( extension_TriggerOnly( p_extensions_manager, p_ext ) )\n {\n extension_Trigger( p_extensions_manager, p_ext );\n }\n else\n {\n if( !extension_IsActivated( p_extensions_manager, p_ext ) )\n extension_Activate( p_extensions_manager, p_ext );\n else\n extension_Deactivate( p_extensions_manager, p_ext );\n }\n }\n else\n {\n msg_Dbg( p_intf, \"triggering extension '%s', on menu with id = 0x%x\",\n p_ext->psz_title, i_action );\n\n extension_TriggerMenu( p_extensions_manager, p_ext, i_action );\n }\n}\n\nvoid ExtensionsManager::inputChanged( input_thread_t* p_input )\n{\n \/\/This is unlikely, but can happen if no extension modules can be loaded.\n if ( p_extensions_manager == NULL )\n return ;\n vlc_mutex_lock( &p_extensions_manager->lock );\n\n extension_t *p_ext;\n FOREACH_ARRAY( p_ext, p_extensions_manager->extensions )\n {\n if( extension_IsActivated( p_extensions_manager, p_ext ) )\n {\n extension_SetInput( p_extensions_manager, p_ext, p_input );\n }\n }\n FOREACH_END()\n\n vlc_mutex_unlock( &p_extensions_manager->lock );\n}\n\nvoid ExtensionsManager::playingChanged( int state )\n{\n \/\/This is unlikely, but can happen if no extension modules can be loaded.\n if ( p_extensions_manager == NULL )\n return ;\n vlc_mutex_lock( &p_extensions_manager->lock );\n\n extension_t *p_ext;\n FOREACH_ARRAY( p_ext, p_extensions_manager->extensions )\n {\n if( extension_IsActivated( p_extensions_manager, p_ext ) )\n {\n extension_PlayingChanged( p_extensions_manager, p_ext, state );\n }\n }\n FOREACH_END()\n\n vlc_mutex_unlock( &p_extensions_manager->lock );\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2018 The Brave 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 \"brave\/utility\/tor\/tor_launcher_impl.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/process\/kill.h\"\n#include \"base\/process\/launch.h\"\n#include \"base\/single_thread_task_runner.h\"\n#include \"base\/task_scheduler\/post_task.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/threading\/thread_task_runner_handle.h\"\n\n#if defined(OS_POSIX)\nint pipehack[2];\n\nstatic void SIGCHLDHandler(int signo) {\n int error = errno;\n char ch = 0;\n write(pipehack[1], &ch, 1);\n errno = error;\n}\n\nstatic void SetupPipeHack() {\n if (pipe(pipehack) == -1)\n LOG(ERROR) << \"pipehack\";\n\n int flags;\n for (size_t i = 0; i < 2; ++i) {\n if ((flags = fcntl(pipehack[i], F_GETFL)) == -1)\n LOG(ERROR) << \"get flags\";\n \/\/ Nonblock write end on SIGCHLD handler which will notify monitor thread\n \/\/ by sending one byte to pipe whose read end is blocked and wait for\n \/\/ SIGCHLD to arrives to avoid busy reading\n if (i == 1)\n flags |= O_NONBLOCK;\n if (fcntl(pipehack[i], F_SETFL, flags) == -1)\n LOG(ERROR) << \"set flags\";\n if ((flags = fcntl(pipehack[i], F_GETFD)) == -1)\n LOG(ERROR) << \"get fd flags\";\n flags |= FD_CLOEXEC;\n if (fcntl(pipehack[i], F_SETFD, flags) == -1)\n LOG(ERROR) << \"set fd flags\";\n }\n\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = SIGCHLDHandler;\n sigaction(SIGCHLD, &action, NULL);\n}\n\nstatic void TearDownPipeHack() {\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = SIG_DFL;\n sigaction(SIGCHLD, &action, NULL);\n for (size_t i = 0; i < 2; ++i)\n close(pipehack[i]);\n}\n#endif\n\nnamespace brave {\n\n#if defined(OS_POSIX)\nclass TorLauncherDelegate : public base::LaunchOptions::PreExecDelegate {\n public:\n TorLauncherDelegate() {}\n ~TorLauncherDelegate() override {}\n\n void RunAsyncSafe() override {\n \/\/ Makes tor process a new leader of process group so that it won't get\n \/\/ affected by ctrl+c (SIGINT) in current terminal\n setsid();\n }\n private:\n DISALLOW_COPY_AND_ASSIGN(TorLauncherDelegate);\n};\n#endif\n\nTorLauncherImpl::TorLauncherImpl(\n std::unique_ptr service_ref)\n : service_ref_(std::move(service_ref)) {\n#if defined(OS_POSIX)\n SetupPipeHack();\n#endif\n}\n\nTorLauncherImpl::~TorLauncherImpl() {\n if (tor_process_.IsValid()) {\n tor_process_.Terminate(0, false);\n#if defined(OS_POSIX)\n TearDownPipeHack();\n#endif\n#if defined(OS_MACOSX)\n base::PostTaskWithTraits(\n FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},\n base::BindOnce(&base::EnsureProcessTerminated, Passed(&tor_process_)));\n#else\n base::EnsureProcessTerminated(std::move(tor_process_));\n#endif\n }\n}\n\nvoid TorLauncherImpl::Launch(const base::FilePath& tor_bin,\n const std::string& tor_host,\n const std::string& tor_port,\n const base::FilePath& tor_data_dir,\n LaunchCallback callback) {\n base::CommandLine args(tor_bin);\n args.AppendArg(\"--ignore-missing-torrc\");\n args.AppendArg(\"-f\");\n args.AppendArg(\"\/nonexistent\");\n args.AppendArg(\"--defaults-torrc\");\n args.AppendArg(\"\/nonexistent\");\n args.AppendArg(\"--SocksPort\");\n args.AppendArg(tor_host + \":\" + tor_port);\n if (!tor_data_dir.empty()) {\n args.AppendArg(\"--DataDirectory\");\n args.AppendArgPath(tor_data_dir);\n }\n\n base::LaunchOptions launchopts;\n#if defined(OS_POSIX)\n TorLauncherDelegate tor_launcher_delegate;\n launchopts.pre_exec_delegate = &tor_launcher_delegate;\n#endif\n#if defined(OS_LINUX)\n launchopts.kill_on_parent_death = true;\n#endif\n tor_process_ = base::LaunchProcess(args, launchopts);\n\n bool result;\n \/\/ TODO(darkdh): return success when tor connected to tor network\n if (tor_process_.IsValid())\n result = true;\n else\n result = false;\n\n if (callback)\n std::move(callback).Run(result);\n\n if (!child_monitor_thread_.get()) {\n child_monitor_thread_.reset(new base::Thread(\"child_monitor_thread\"));\n if (!child_monitor_thread_->Start()) {\n NOTREACHED();\n }\n\n child_monitor_thread_->task_runner()->PostTask(\n FROM_HERE,\n base::BindOnce(&TorLauncherImpl::MonitorChild, base::Unretained(this)));\n }\n}\n\nvoid TorLauncherImpl::SetCrashHandler(SetCrashHandlerCallback callback) {\n crash_handler_callback_ = std::move(callback);\n}\n\nvoid TorLauncherImpl::MonitorChild() {\n#if defined(OS_POSIX)\n char buf[PIPE_BUF];\n\n while (1) {\n if (read(pipehack[0], buf, sizeof(buf)) > 0) {\n pid_t pid;\n int status;\n\n if ((pid = waitpid(-1, &status, WNOHANG)) != -1) {\n if (WIFSIGNALED(status)) {\n LOG(ERROR) << \"tor got terminated by signal \" << WTERMSIG(status);\n } else if (WCOREDUMP(status)) {\n LOG(ERROR) << \"tor coredumped\";\n } else if (WIFEXITED(status)) {\n LOG(ERROR) << \"tor exit (\" << WEXITSTATUS(status) << \")\";\n }\n if (crash_handler_callback_)\n std::move(crash_handler_callback_).Run(pid);\n }\n } else {\n \/\/ pipes closed\n break;\n }\n }\n#elif defined(OS_WIN)\n WaitForSingleObject(tor_process_.Handle(), INFINITE);\n if (crash_handler_callback_)\n std::move(crash_handler_callback_).\n Run(base::GetProcId(tor_process_.Handle()));\n#else\n#error unsupported platforms\n#endif\n}\n\n} \/\/ namespace brave\nlinux header fix (Mac and Windows have build\/precompile.h)\/\/ Copyright (c) 2018 The Brave 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 \"brave\/utility\/tor\/tor_launcher_impl.h\"\n\n\n#if defined(OS_LINUX)\n#include \n#include \n#include \n#include \n#include \n#endif\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/process\/kill.h\"\n#include \"base\/process\/launch.h\"\n#include \"base\/single_thread_task_runner.h\"\n#include \"base\/task_scheduler\/post_task.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/threading\/thread_task_runner_handle.h\"\n\n#if defined(OS_POSIX)\nint pipehack[2];\n\nstatic void SIGCHLDHandler(int signo) {\n int error = errno;\n char ch = 0;\n write(pipehack[1], &ch, 1);\n errno = error;\n}\n\nstatic void SetupPipeHack() {\n if (pipe(pipehack) == -1)\n LOG(ERROR) << \"pipehack\";\n\n int flags;\n for (size_t i = 0; i < 2; ++i) {\n if ((flags = fcntl(pipehack[i], F_GETFL)) == -1)\n LOG(ERROR) << \"get flags\";\n \/\/ Nonblock write end on SIGCHLD handler which will notify monitor thread\n \/\/ by sending one byte to pipe whose read end is blocked and wait for\n \/\/ SIGCHLD to arrives to avoid busy reading\n if (i == 1)\n flags |= O_NONBLOCK;\n if (fcntl(pipehack[i], F_SETFL, flags) == -1)\n LOG(ERROR) << \"set flags\";\n if ((flags = fcntl(pipehack[i], F_GETFD)) == -1)\n LOG(ERROR) << \"get fd flags\";\n flags |= FD_CLOEXEC;\n if (fcntl(pipehack[i], F_SETFD, flags) == -1)\n LOG(ERROR) << \"set fd flags\";\n }\n\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = SIGCHLDHandler;\n sigaction(SIGCHLD, &action, NULL);\n}\n\nstatic void TearDownPipeHack() {\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = SIG_DFL;\n sigaction(SIGCHLD, &action, NULL);\n for (size_t i = 0; i < 2; ++i)\n close(pipehack[i]);\n}\n#endif\n\nnamespace brave {\n\n#if defined(OS_POSIX)\nclass TorLauncherDelegate : public base::LaunchOptions::PreExecDelegate {\n public:\n TorLauncherDelegate() {}\n ~TorLauncherDelegate() override {}\n\n void RunAsyncSafe() override {\n \/\/ Makes tor process a new leader of process group so that it won't get\n \/\/ affected by ctrl+c (SIGINT) in current terminal\n setsid();\n }\n private:\n DISALLOW_COPY_AND_ASSIGN(TorLauncherDelegate);\n};\n#endif\n\nTorLauncherImpl::TorLauncherImpl(\n std::unique_ptr service_ref)\n : service_ref_(std::move(service_ref)) {\n#if defined(OS_POSIX)\n SetupPipeHack();\n#endif\n}\n\nTorLauncherImpl::~TorLauncherImpl() {\n if (tor_process_.IsValid()) {\n tor_process_.Terminate(0, false);\n#if defined(OS_POSIX)\n TearDownPipeHack();\n#endif\n#if defined(OS_MACOSX)\n base::PostTaskWithTraits(\n FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},\n base::BindOnce(&base::EnsureProcessTerminated, Passed(&tor_process_)));\n#else\n base::EnsureProcessTerminated(std::move(tor_process_));\n#endif\n }\n}\n\nvoid TorLauncherImpl::Launch(const base::FilePath& tor_bin,\n const std::string& tor_host,\n const std::string& tor_port,\n const base::FilePath& tor_data_dir,\n LaunchCallback callback) {\n base::CommandLine args(tor_bin);\n args.AppendArg(\"--ignore-missing-torrc\");\n args.AppendArg(\"-f\");\n args.AppendArg(\"\/nonexistent\");\n args.AppendArg(\"--defaults-torrc\");\n args.AppendArg(\"\/nonexistent\");\n args.AppendArg(\"--SocksPort\");\n args.AppendArg(tor_host + \":\" + tor_port);\n if (!tor_data_dir.empty()) {\n args.AppendArg(\"--DataDirectory\");\n args.AppendArgPath(tor_data_dir);\n }\n\n base::LaunchOptions launchopts;\n#if defined(OS_POSIX)\n TorLauncherDelegate tor_launcher_delegate;\n launchopts.pre_exec_delegate = &tor_launcher_delegate;\n#endif\n#if defined(OS_LINUX)\n launchopts.kill_on_parent_death = true;\n#endif\n tor_process_ = base::LaunchProcess(args, launchopts);\n\n bool result;\n \/\/ TODO(darkdh): return success when tor connected to tor network\n if (tor_process_.IsValid())\n result = true;\n else\n result = false;\n\n if (callback)\n std::move(callback).Run(result);\n\n if (!child_monitor_thread_.get()) {\n child_monitor_thread_.reset(new base::Thread(\"child_monitor_thread\"));\n if (!child_monitor_thread_->Start()) {\n NOTREACHED();\n }\n\n child_monitor_thread_->task_runner()->PostTask(\n FROM_HERE,\n base::BindOnce(&TorLauncherImpl::MonitorChild, base::Unretained(this)));\n }\n}\n\nvoid TorLauncherImpl::SetCrashHandler(SetCrashHandlerCallback callback) {\n crash_handler_callback_ = std::move(callback);\n}\n\nvoid TorLauncherImpl::MonitorChild() {\n#if defined(OS_POSIX)\n char buf[PIPE_BUF];\n\n while (1) {\n if (read(pipehack[0], buf, sizeof(buf)) > 0) {\n pid_t pid;\n int status;\n\n if ((pid = waitpid(-1, &status, WNOHANG)) != -1) {\n if (WIFSIGNALED(status)) {\n LOG(ERROR) << \"tor got terminated by signal \" << WTERMSIG(status);\n } else if (WCOREDUMP(status)) {\n LOG(ERROR) << \"tor coredumped\";\n } else if (WIFEXITED(status)) {\n LOG(ERROR) << \"tor exit (\" << WEXITSTATUS(status) << \")\";\n }\n if (crash_handler_callback_)\n std::move(crash_handler_callback_).Run(pid);\n }\n } else {\n \/\/ pipes closed\n break;\n }\n }\n#elif defined(OS_WIN)\n WaitForSingleObject(tor_process_.Handle(), INFINITE);\n if (crash_handler_callback_)\n std::move(crash_handler_callback_).\n Run(base::GetProcId(tor_process_.Handle()));\n#else\n#error unsupported platforms\n#endif\n}\n\n} \/\/ namespace brave\n<|endoftext|>"} {"text":"Add comments in formatclipboard.hxx<|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_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH\n#define DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n#if HAVE_DUNE_FEM\n#include \n#endif\n\n#if HAVE_DUNE_FEM_LOCALFUNCTIONS\n#include \n#include \n#include \n#include \n#endif \/\/ HAVE_DUNE_FEM_LOCALFUNCTIONS\n\n#include \n#include \n\n#include \"..\/..\/mapper\/fem.hh\"\n#include \"..\/..\/basefunctionset\/fem-localfunctions.hh\"\n#include \"..\/continuouslagrange.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace ContinuousLagrangeSpace {\n\n#if HAVE_DUNE_FEM_LOCALFUNCTIONS\n\n\n\/\/ forward, to be used in the traits and to allow for specialization\ntemplate \nclass FemLocalfunctionsWrapper\n{\n static_assert(Dune::AlwaysFalse::value, \"Untested for these dimensions!\");\n};\n\n\n\/**\n * \\brief Traits class for ContinuousLagrangeSpace::FemLocalfunctionsWrapper.\n *\/\ntemplate \nclass FemLocalfunctionsWrapperTraits\n{\npublic:\n typedef GridPartImp GridPartType;\n typedef typename GridPartType::GridViewType GridViewType;\n static const int polOrder = polynomialOrder;\n static_assert(polOrder >= 1, \"Wrong polOrder given!\");\n\nprivate:\n typedef typename GridPartType::ctype DomainFieldType;\n\npublic:\n static const unsigned int dimDomain = GridPartType::dimension;\n typedef RangeFieldImp RangeFieldType;\n static const unsigned int dimRange = rangeDim;\n static const unsigned int dimRangeCols = rangeDimCols;\n typedef FemLocalfunctionsWrapper derived_type;\n\nprivate:\n typedef FemLocalfunctionsWrapperTraits ThisType;\n\npublic:\n typedef Dune::LagrangeLocalFiniteElement\n FiniteElementType;\n\nprivate:\n typedef Dune::FemLocalFunctions::BaseFunctionSetMap BaseFunctionSetMapType;\n\npublic:\n typedef Dune::FemLocalFunctions::DiscreteFunctionSpace BackendType;\n typedef Mapper::FemDofWrapper MapperType;\n typedef BaseFunctionSet::FemLocalfunctionsWrapper BaseFunctionSetType;\n typedef typename BaseFunctionSetType::EntityType EntityType;\n static const bool needs_grid_view = false;\n\nprivate:\n template \n friend class FemLocalfunctionsWrapper;\n}; \/\/ class FemLocalfunctionsWrapperTraits\n\n\ntemplate \nclass FemLocalfunctionsWrapper\n : public ContinuousLagrangeSpaceBase,\n GridPartImp::dimension, RangeFieldImp, 1, 1>\n{\n typedef ContinuousLagrangeSpaceBase,\n GridPartImp::dimension, RangeFieldImp, 1, 1> BaseType;\n typedef FemLocalfunctionsWrapper ThisType;\n\npublic:\n typedef FemLocalfunctionsWrapperTraits Traits;\n\n typedef typename Traits::GridPartType GridPartType;\n typedef typename Traits::GridViewType GridViewType;\n static const int polOrder = Traits::polOrder;\n typedef typename GridPartType::ctype DomainFieldType;\n static const unsigned int dimDomain = GridPartType::dimension;\n typedef FieldVector DomainType;\n typedef typename Traits::RangeFieldType RangeFieldType;\n static const unsigned int dimRange = Traits::dimRange;\n static const unsigned int dimRangeCols = Traits::dimRangeCols;\n\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::MapperType MapperType;\n typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;\n typedef typename Traits::EntityType EntityType;\n\n typedef Dune::Stuff::LA::SparsityPatternDefault PatternType;\n\nprivate:\n typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType;\n\npublic:\n FemLocalfunctionsWrapper(std::shared_ptr gridP)\n : gridPart_(assertGridPart(gridP))\n , gridView_(std::make_shared(gridPart_->gridView()))\n , baseFunctionSetMap_(new BaseFunctionSetMapType(*gridPart_))\n , backend_(new BackendType(const_cast(*gridPart_), *baseFunctionSetMap_))\n , mapper_(new MapperType(backend_->mapper()))\n , tmp_global_indices_(mapper_->maxNumDofs())\n {\n }\n\n FemLocalfunctionsWrapper(const ThisType& other)\n : gridPart_(other.gridPart_)\n , gridView_(other.gridView_)\n , baseFunctionSetMap_(other.baseFunctionSetMap_)\n , backend_(other.backend_)\n , mapper_(other.mapper_)\n , tmp_global_indices_(mapper_->maxNumDofs())\n {\n }\n\n ThisType& operator=(const ThisType& other)\n {\n if (this != &other) {\n gridPart_ = other.gridPart_;\n gridView_ = other.gridView_;\n baseFunctionSetMap_ = other.baseFunctionSetMap_;\n backend_ = other.backend_;\n mapper_ = other.mapper_;\n tmp_global_indices_.resize(mapper_->maxNumDofs());\n }\n return *this;\n }\n\n std::shared_ptr grid_part() const\n {\n return gridPart_;\n }\n\n std::shared_ptr grid_view() const\n {\n return gridView_;\n }\n\n const BackendType& backend() const\n {\n return *backend_;\n }\n\n bool continuous() const\n {\n return true;\n }\n\n const MapperType& mapper() const\n {\n return *mapper_;\n }\n\n BaseFunctionSetType base_function_set(const EntityType& entity) const\n {\n return BaseFunctionSetType(*baseFunctionSetMap_, entity);\n }\n\nprivate:\n static std::shared_ptr assertGridPart(const std::shared_ptr gP)\n {\n \/\/ static checks\n typedef typename GridPartType::GridType GridType;\n static_assert((dimDomain == 1) || !std::is_same>::value,\n \"This space is only implemented for simplicial grids!\");\n static_assert((dimDomain == 1) || !std::is_same>::value,\n \"This space is only implemented for simplicial grids!\");\n \/\/ dynamic checks\n typedef typename Dune::Fem::AllGeomTypes\n AllGeometryTypes;\n const AllGeometryTypes allGeometryTypes(gP->indexSet());\n const std::vector& geometryTypes = allGeometryTypes.geomTypes(0);\n if (!(geometryTypes.size() == 1 && geometryTypes[0].isSimplex()))\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" this space is only implemented for simplicial grids!\");\n return gP;\n } \/\/ ... assertGridPart(...)\n\n std::shared_ptr gridPart_;\n std::shared_ptr gridView_;\n std::shared_ptr baseFunctionSetMap_;\n std::shared_ptr backend_;\n std::shared_ptr mapper_;\n mutable Dune::DynamicVector tmp_global_indices_;\n}; \/\/ class FemLocalfunctionsWrapper< ..., 1, 1 >\n\n\n#else \/\/ HAVE_DUNE_FEM_LOCALFUNCTIONS\n\n\ntemplate \nclass FemLocalfunctionsWrapper\n{\n static_assert(Dune::AlwaysFalse::value, \"You are missing dune-fem-localfunctions!\");\n};\n\n\n#endif \/\/ HAVE_DUNE_FEM_LOCALFUNCTIONS\n\n} \/\/ namespace ContinuousLagrangeSpace\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH\n[space.continuouslagrange.fem-localfunctions] use grid capabilities for static checks\/\/ 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_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH\n#define DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#if HAVE_DUNE_LOCALFUNCTIONS\n#include \n#include \n#endif \/\/ HAVE_DUNE_LOCALFUNCTIONS\n\n#if HAVE_DUNE_FEM_LOCALFUNCTIONS\n#include \n#include \n#include \n#include \n#endif \/\/ HAVE_DUNE_FEM_LOCALFUNCTIONS\n\n#include \"..\/..\/mapper\/fem.hh\"\n#include \"..\/..\/basefunctionset\/fem-localfunctions.hh\"\n#include \"..\/continuouslagrange.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace ContinuousLagrangeSpace {\n\n#if HAVE_DUNE_FEM_LOCALFUNCTIONS\n\n\n\/\/ forward, to be used in the traits and to allow for specialization\ntemplate \nclass FemLocalfunctionsWrapper\n{\n static_assert(Dune::AlwaysFalse::value, \"Untested for these dimensions!\");\n};\n\n\n\/**\n * \\brief Traits class for ContinuousLagrangeSpace::FemLocalfunctionsWrapper.\n *\/\ntemplate \nclass FemLocalfunctionsWrapperTraits\n{\npublic:\n typedef GridPartImp GridPartType;\n typedef typename GridPartType::GridViewType GridViewType;\n static const int polOrder = polynomialOrder;\n static_assert(polOrder >= 1, \"Wrong polOrder given!\");\n\nprivate:\n typedef typename GridPartType::ctype DomainFieldType;\n\npublic:\n static const unsigned int dimDomain = GridPartType::dimension;\n typedef RangeFieldImp RangeFieldType;\n static const unsigned int dimRange = rangeDim;\n static const unsigned int dimRangeCols = rangeDimCols;\n typedef FemLocalfunctionsWrapper derived_type;\n\nprivate:\n typedef typename GridPartType::GridType GridType;\n static_assert(dimDomain == 1 || Dune::Capabilities::hasSingleGeometryType::v,\n \"This space is only implemented for fully simplicial grids!\");\n static_assert(dimDomain == 1 || (Dune::Capabilities::hasSingleGeometryType::topologyId\n == GenericGeometry::SimplexTopology::type::id),\n \"This space is only implemented for fully simplicial grids!\");\n typedef FemLocalfunctionsWrapperTraits ThisType;\n\npublic:\n typedef Dune::LagrangeLocalFiniteElement\n FiniteElementType;\n\nprivate:\n typedef Dune::FemLocalFunctions::BaseFunctionSetMap BaseFunctionSetMapType;\n\npublic:\n typedef Dune::FemLocalFunctions::DiscreteFunctionSpace BackendType;\n typedef Mapper::FemDofWrapper MapperType;\n typedef BaseFunctionSet::FemLocalfunctionsWrapper BaseFunctionSetType;\n typedef typename BaseFunctionSetType::EntityType EntityType;\n static const bool needs_grid_view = false;\n\nprivate:\n template \n friend class FemLocalfunctionsWrapper;\n}; \/\/ class FemLocalfunctionsWrapperTraits\n\n\ntemplate \nclass FemLocalfunctionsWrapper\n : public ContinuousLagrangeSpaceBase,\n GridPartImp::dimension, RangeFieldImp, 1, 1>\n{\n typedef ContinuousLagrangeSpaceBase,\n GridPartImp::dimension, RangeFieldImp, 1, 1> BaseType;\n typedef FemLocalfunctionsWrapper ThisType;\n\npublic:\n typedef FemLocalfunctionsWrapperTraits Traits;\n\n typedef typename Traits::GridPartType GridPartType;\n typedef typename Traits::GridViewType GridViewType;\n static const int polOrder = Traits::polOrder;\n typedef typename GridPartType::ctype DomainFieldType;\n static const unsigned int dimDomain = GridPartType::dimension;\n typedef FieldVector DomainType;\n typedef typename Traits::RangeFieldType RangeFieldType;\n static const unsigned int dimRange = Traits::dimRange;\n static const unsigned int dimRangeCols = Traits::dimRangeCols;\n\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::MapperType MapperType;\n typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;\n typedef typename Traits::EntityType EntityType;\n\n typedef Dune::Stuff::LA::SparsityPatternDefault PatternType;\n\nprivate:\n typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType;\n\npublic:\n FemLocalfunctionsWrapper(std::shared_ptr gridP)\n : gridPart_(gridP)\n , gridView_(std::make_shared(gridPart_->gridView()))\n , baseFunctionSetMap_(new BaseFunctionSetMapType(*gridPart_))\n , backend_(new BackendType(const_cast(*gridPart_), *baseFunctionSetMap_))\n , mapper_(new MapperType(backend_->mapper()))\n , tmp_global_indices_(mapper_->maxNumDofs())\n {\n }\n\n FemLocalfunctionsWrapper(const ThisType& other)\n : gridPart_(other.gridPart_)\n , gridView_(other.gridView_)\n , baseFunctionSetMap_(other.baseFunctionSetMap_)\n , backend_(other.backend_)\n , mapper_(other.mapper_)\n , tmp_global_indices_(mapper_->maxNumDofs())\n {\n }\n\n ThisType& operator=(const ThisType& other)\n {\n if (this != &other) {\n gridPart_ = other.gridPart_;\n gridView_ = other.gridView_;\n baseFunctionSetMap_ = other.baseFunctionSetMap_;\n backend_ = other.backend_;\n mapper_ = other.mapper_;\n tmp_global_indices_.resize(mapper_->maxNumDofs());\n }\n return *this;\n }\n\n const std::shared_ptr& grid_part() const\n {\n return gridPart_;\n }\n\n const std::shared_ptr& grid_view() const\n {\n return gridView_;\n }\n\n const BackendType& backend() const\n {\n return *backend_;\n }\n\n bool continuous() const\n {\n return true;\n }\n\n const MapperType& mapper() const\n {\n return *mapper_;\n }\n\n BaseFunctionSetType base_function_set(const EntityType& entity) const\n {\n return BaseFunctionSetType(*baseFunctionSetMap_, entity);\n }\n\nprivate:\n std::shared_ptr gridPart_;\n std::shared_ptr gridView_;\n std::shared_ptr baseFunctionSetMap_;\n std::shared_ptr backend_;\n std::shared_ptr mapper_;\n mutable Dune::DynamicVector tmp_global_indices_;\n}; \/\/ class FemLocalfunctionsWrapper< ..., 1, 1 >\n\n\n#else \/\/ HAVE_DUNE_FEM_LOCALFUNCTIONS\n\n\ntemplate \nclass FemLocalfunctionsWrapper\n{\n static_assert(Dune::AlwaysFalse::value, \"You are missing dune-fem-localfunctions!\");\n};\n\n\n#endif \/\/ HAVE_DUNE_FEM_LOCALFUNCTIONS\n\n} \/\/ namespace ContinuousLagrangeSpace\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH\n<|endoftext|>"} {"text":"\/\/\n\/\/ AKTriangleOscillatorDSPKernel.hpp\n\/\/ AudioKit\n\/\/\n\/\/ Created by Aurelius Prochazka, revision history on Github.\n\/\/ Copyright (c) 2016 Aurelius Prochazka. All rights reserved.\n\/\/\n\n#ifndef AKTriangleOscillatorDSPKernel_hpp\n#define AKTriangleOscillatorDSPKernel_hpp\n\n#import \"AKDSPKernel.hpp\"\n#import \"AKParameterRamper.hpp\"\n\nextern \"C\" {\n#include \"soundpipe.h\"\n}\n\nenum {\n frequencyAddress = 0,\n amplitudeAddress = 1,\n detuningOffsetAddress = 2,\n detuningMultiplierAddress = 3\n};\n\nclass AKTriangleOscillatorDSPKernel : public AKDSPKernel {\npublic:\n \/\/ MARK: Member Functions\n\n AKTriangleOscillatorDSPKernel() {}\n\n void init(int channelCount, double inSampleRate) {\n channels = channelCount;\n\n sampleRate = float(inSampleRate);\n\n sp_create(&sp);\n sp_bltriangle_create(&bltriangle);\n sp_bltriangle_init(sp, bltriangle);\n *bltriangle->freq = 440;\n *bltriangle->amp = 0.5;\n }\n\n\n void start() {\n started = true;\n }\n\n void stop() {\n started = false;\n }\n\n void destroy() {\n sp_bltriangle_destroy(&bltriangle);\n sp_destroy(&sp);\n }\n\n void reset() {\n }\n\n void setFrequency(float freq) {\n frequency = freq;\n frequencyRamper.set(clamp(freq, (float)0.0, (float)20000.0));\n }\n\n void setAmplitude(float amp) {\n amplitude = amp;\n amplitudeRamper.set(clamp(amp, (float)0.0, (float)1.0));\n }\n\n void setDetuningoffset(float detuneOffset) {\n detuningOffset = detuneOffset;\n detuningOffsetRamper.set(clamp(detuneOffset, (float)-1000, (float)1000));\n }\n\n void setDetuningmultiplier(float detuneScale) {\n detuningMultiplier = detuneScale;\n detuningMultiplierRamper.set(clamp(detuneScale, (float)0.9, (float)1.11));\n }\n\n\n void setParameter(AUParameterAddress address, AUValue value) {\n switch (address) {\n case frequencyAddress:\n frequencyRamper.set(clamp(value, (float)0.0, (float)20000.0));\n break;\n\n case amplitudeAddress:\n amplitudeRamper.set(clamp(value, (float)0.0, (float)1.0));\n break;\n\n case detuningOffsetAddress:\n detuningOffsetRamper.set(clamp(value, (float)-1000, (float)1000));\n break;\n\n case detuningMultiplierAddress:\n detuningMultiplierRamper.set(clamp(value, (float)0.9, (float)1.11));\n break;\n\n }\n }\n\n AUValue getParameter(AUParameterAddress address) {\n switch (address) {\n case frequencyAddress:\n return frequencyRamper.goal();\n\n case amplitudeAddress:\n return amplitudeRamper.goal();\n\n case detuningOffsetAddress:\n return detuningOffsetRamper.goal();\n\n case detuningMultiplierAddress:\n return detuningMultiplierRamper.goal();\n\n default: return 0.0f;\n }\n }\n\n void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {\n switch (address) {\n case frequencyAddress:\n frequencyRamper.startRamp(clamp(value, (float)0.0, (float)20000.0), duration);\n break;\n\n case amplitudeAddress:\n amplitudeRamper.startRamp(clamp(value, (float)0.0, (float)1.0), duration);\n break;\n\n case detuningOffsetAddress:\n detuningOffsetRamper.startRamp(clamp(value, (float)-1000, (float)1000), duration);\n break;\n\n case detuningMultiplierAddress:\n detuningMultiplierRamper.startRamp(clamp(value, (float)0.9, (float)1.11), duration);\n break;\n\n }\n }\n\n void setBuffer(AudioBufferList *outBufferList) {\n outBufferListPtr = outBufferList;\n }\n\n void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {\n \/\/ For each sample.\n for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {\n int frameOffset = int(frameIndex + bufferOffset);\n\n frequency = double(frequencyRamper.getStep());\n amplitude = double(amplitudeRamper.getStep());\n detuningOffset = double(detuningOffsetRamper.getStep());\n detuningMultiplier = double(detuningMultiplierRamper.getStep());\n\n *bltriangle->freq = frequency;\n *bltriangle->amp = amplitude;\n\n float temp = 0;\n for (int channel = 0; channel < channels; ++channel) {\n float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;\n if (started) {\n if (channel == 0) {\n sp_bltriangle_compute(sp, bltriangle, nil, &temp);\n }\n *out = temp;\n } else {\n *out = 0.0;\n }\n }\n }\n }\n\n \/\/ MARK: Member Variables\n\nprivate:\n\n int channels = 2;\n float sampleRate = 44100.0;\n\n AudioBufferList *outBufferListPtr = nullptr;\n\n sp_data *sp;\n sp_bltriangle *bltriangle;\n\n\n float frequency = 440;\n float amplitude = 0.5;\n float detuningOffset = 0;\n float detuningMultiplier = 1;\n\npublic:\n bool started = false;\n AKParameterRamper frequencyRamper = 440;\n AKParameterRamper amplitudeRamper = 0.5;\n AKParameterRamper detuningOffsetRamper = 0;\n AKParameterRamper detuningMultiplierRamper = 1;\n};\n\n#endif \/* AKTriangleOscillatorDSPKernel_hpp *\/\nProperly used detune parameters\/\/\n\/\/ AKTriangleOscillatorDSPKernel.hpp\n\/\/ AudioKit\n\/\/\n\/\/ Created by Aurelius Prochazka, revision history on Github.\n\/\/ Copyright (c) 2016 Aurelius Prochazka. All rights reserved.\n\/\/\n\n#ifndef AKTriangleOscillatorDSPKernel_hpp\n#define AKTriangleOscillatorDSPKernel_hpp\n\n#import \"AKDSPKernel.hpp\"\n#import \"AKParameterRamper.hpp\"\n\nextern \"C\" {\n#include \"soundpipe.h\"\n}\n\nenum {\n frequencyAddress = 0,\n amplitudeAddress = 1,\n detuningOffsetAddress = 2,\n detuningMultiplierAddress = 3\n};\n\nclass AKTriangleOscillatorDSPKernel : public AKDSPKernel {\npublic:\n \/\/ MARK: Member Functions\n\n AKTriangleOscillatorDSPKernel() {}\n\n void init(int channelCount, double inSampleRate) {\n channels = channelCount;\n\n sampleRate = float(inSampleRate);\n\n sp_create(&sp);\n sp_bltriangle_create(&bltriangle);\n sp_bltriangle_init(sp, bltriangle);\n *bltriangle->freq = 440;\n *bltriangle->amp = 0.5;\n }\n\n\n void start() {\n started = true;\n }\n\n void stop() {\n started = false;\n }\n\n void destroy() {\n sp_bltriangle_destroy(&bltriangle);\n sp_destroy(&sp);\n }\n\n void reset() {\n }\n\n void setFrequency(float freq) {\n frequency = freq;\n frequencyRamper.set(clamp(freq, (float)0.0, (float)20000.0));\n }\n\n void setAmplitude(float amp) {\n amplitude = amp;\n amplitudeRamper.set(clamp(amp, (float)0.0, (float)1.0));\n }\n\n void setDetuningoffset(float detuneOffset) {\n detuningOffset = detuneOffset;\n detuningOffsetRamper.set(clamp(detuneOffset, (float)-1000, (float)1000));\n }\n\n void setDetuningmultiplier(float detuneScale) {\n detuningMultiplier = detuneScale;\n detuningMultiplierRamper.set(clamp(detuneScale, (float)0.9, (float)1.11));\n }\n\n\n void setParameter(AUParameterAddress address, AUValue value) {\n switch (address) {\n case frequencyAddress:\n frequencyRamper.set(clamp(value, (float)0.0, (float)20000.0));\n break;\n\n case amplitudeAddress:\n amplitudeRamper.set(clamp(value, (float)0.0, (float)1.0));\n break;\n\n case detuningOffsetAddress:\n detuningOffsetRamper.set(clamp(value, (float)-1000, (float)1000));\n break;\n\n case detuningMultiplierAddress:\n detuningMultiplierRamper.set(clamp(value, (float)0.9, (float)1.11));\n break;\n\n }\n }\n\n AUValue getParameter(AUParameterAddress address) {\n switch (address) {\n case frequencyAddress:\n return frequencyRamper.goal();\n\n case amplitudeAddress:\n return amplitudeRamper.goal();\n\n case detuningOffsetAddress:\n return detuningOffsetRamper.goal();\n\n case detuningMultiplierAddress:\n return detuningMultiplierRamper.goal();\n\n default: return 0.0f;\n }\n }\n\n void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {\n switch (address) {\n case frequencyAddress:\n frequencyRamper.startRamp(clamp(value, (float)0.0, (float)20000.0), duration);\n break;\n\n case amplitudeAddress:\n amplitudeRamper.startRamp(clamp(value, (float)0.0, (float)1.0), duration);\n break;\n\n case detuningOffsetAddress:\n detuningOffsetRamper.startRamp(clamp(value, (float)-1000, (float)1000), duration);\n break;\n\n case detuningMultiplierAddress:\n detuningMultiplierRamper.startRamp(clamp(value, (float)0.9, (float)1.11), duration);\n break;\n\n }\n }\n\n void setBuffer(AudioBufferList *outBufferList) {\n outBufferListPtr = outBufferList;\n }\n\n void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {\n \/\/ For each sample.\n for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {\n int frameOffset = int(frameIndex + bufferOffset);\n\n frequency = double(frequencyRamper.getStep());\n amplitude = double(amplitudeRamper.getStep());\n detuningOffset = double(detuningOffsetRamper.getStep());\n detuningMultiplier = double(detuningMultiplierRamper.getStep());\n\n *bltriangle->freq = frequency * detuningMultiplier + detuningOffset;\n *bltriangle->amp = amplitude;\n\n float temp = 0;\n for (int channel = 0; channel < channels; ++channel) {\n float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;\n if (started) {\n if (channel == 0) {\n sp_bltriangle_compute(sp, bltriangle, nil, &temp);\n }\n *out = temp;\n } else {\n *out = 0.0;\n }\n }\n }\n }\n\n \/\/ MARK: Member Variables\n\nprivate:\n\n int channels = 2;\n float sampleRate = 44100.0;\n\n AudioBufferList *outBufferListPtr = nullptr;\n\n sp_data *sp;\n sp_bltriangle *bltriangle;\n\n\n float frequency = 440;\n float amplitude = 0.5;\n float detuningOffset = 0;\n float detuningMultiplier = 1;\n\npublic:\n bool started = false;\n AKParameterRamper frequencyRamper = 440;\n AKParameterRamper amplitudeRamper = 0.5;\n AKParameterRamper detuningOffsetRamper = 0;\n AKParameterRamper detuningMultiplierRamper = 1;\n};\n\n#endif \/* AKTriangleOscillatorDSPKernel_hpp *\/\n<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright 2015 Cloudius Systems\n *\n * Modified by Cloudius Systems\n *\/\n\n#pragma once\n\n#include \"database.hh\"\n#include \"db\/api.hh\"\n\nnamespace validation {\n\nconstexpr size_t max_key_size = std::numeric_limits::max();\n\n\/**\n * Based on org.apache.cassandra.thrift.ThriftValidation#validate_key()\n *\/\nvoid validate_cql_key(schema_ptr schema, const api::partition_key& key) {\n if (key.empty()) {\n throw exceptions::invalid_request_exception(\"Key may not be empty\");\n }\n\n \/\/ check that key can be handled by FBUtilities.writeShortByteArray\n if (key.size() > max_key_size) {\n throw exceptions::invalid_request_exception(sprint(\"Key length of %s is longer than maximum of %d\", key.size(), max_key_size));\n }\n\n try {\n schema->partition_key_type->validate(key);\n } catch (const marshal_exception& e) {\n throw exceptions::invalid_request_exception(e.why());\n }\n}\n\n}\nvalidation: Fix incorrect format specifier\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright 2015 Cloudius Systems\n *\n * Modified by Cloudius Systems\n *\/\n\n#pragma once\n\n#include \"database.hh\"\n#include \"db\/api.hh\"\n\nnamespace validation {\n\nconstexpr size_t max_key_size = std::numeric_limits::max();\n\n\/**\n * Based on org.apache.cassandra.thrift.ThriftValidation#validate_key()\n *\/\nvoid validate_cql_key(schema_ptr schema, const api::partition_key& key) {\n if (key.empty()) {\n throw exceptions::invalid_request_exception(\"Key may not be empty\");\n }\n\n \/\/ check that key can be handled by FBUtilities.writeShortByteArray\n if (key.size() > max_key_size) {\n throw exceptions::invalid_request_exception(sprint(\"Key length of %d is longer than maximum of %d\", key.size(), max_key_size));\n }\n\n try {\n schema->partition_key_type->validate(key);\n } catch (const marshal_exception& e) {\n throw exceptions::invalid_request_exception(e.why());\n }\n}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \/\/ standard input \/ output functions\n#include \/\/ string function definitions\n#include \/\/ UNIX standard function definitions\n#include \/\/ File control definitions\n#include \/\/ Error number definitions\n#include \/\/ POSIX terminal control definitions\n#include \/\/ time calls\n#include \n#include \n\nusing namespace std;\n\n\/\/const int JoyLinearAxisPositive = 9;\n\/\/const int JoyLinearAxisNegative = 8;\nconst int JoyLinearAxisPositive = 3;\nconst int JoyLinearAxisNegative = 1;\nconst int JoyRotationAxis = 0;\nconst int JoyHeadRotationAxis = 2;\nconst int JoyIgnitionButton = 1;\nconst int JoyIgnitionResetButton = 6;\nconst float MaximumHeadAngle = 90.0f;\nconst float MaximumSteeringAngle = 30.0f;\n\/\/\/ \n\/\/\/ Maximum forward travel speed in meters per second.\n\/\/\/ <\/summary>\nconst float MaximumForwardSpeed = 1.0f;\n\/\/\/ \n\/\/\/ Maximum reverse travel speed in meters per second.\n\/\/\/ <\/summary>\nconst float MaximumReverseSpeed = -1.0f;\n\nclass RemoteControllerCls\n{\npublic:\n\tRemoteControllerCls();\n\nprivate:\n\tvoid robotStateCallback(const robot_state::robot_state::ConstPtr& state);\n\tvoid joyCallback(const sensor_msgs::Joy::ConstPtr& joy);\n\tvoid heartBeatStopCallback(const std_msgs::Bool::ConstPtr& stop);\n\tvoid joyDiagCallback(const diagnostic_msgs::DiagnosticArray::ConstPtr& diag);\n\tvoid ChangeState(int new_state);\n\tros::NodeHandle nh_;\n\n\tros::Publisher ignition_control_pub_;\n\tros::Publisher speed_steering_pub_;\n\tros::Subscriber heart_beat_stop_sub_;\n\tros::Subscriber joy_sub_;\n\tros::Subscriber joy_diag_sub_;\n\tros::Subscriber robot_state_sub_;\n\tros::Publisher robot_state_change_request_pub_;\n\tros::Publisher speech_pub_;\n\tbool force_next_ignition_;\n\tint robot_state;\n\tbool joy_ok;\n};\n\nRemoteControllerCls::RemoteControllerCls()\n{\n\tjoy_ok = false;\n\tforce_next_ignition_ = false;\n\t\/\/nh_.param(\"axis_linear\", linear_, linear_);\n\t\/\/nh_.param(\"axis_angular\", angular_, angular_);\n\t\/\/nh_.param(\"scale_angular\", a_scale_, a_scale_);\n\t\/\/nh_.param(\"scale_linear\", l_scale_, l_scale_);\n\tspeech_pub_ = nh_.advertise (\"speech_engine\/speech_request\", 1);\n\theart_beat_stop_sub_ = nh_.subscribe (\"heart_beat_stop\", 3, &RemoteControllerCls::heartBeatStopCallback, this);\n\tjoy_sub_ = nh_.subscribe < sensor_msgs::Joy> (\"joy\", 3, &RemoteControllerCls::joyCallback, this);\n\tjoy_diag_sub_ = nh_.subscribe < diagnostic_msgs::DiagnosticArray> (\"diagnostics\", 3, &RemoteControllerCls::joyDiagCallback, this);\n\tspeed_steering_pub_ = nh_.advertise < motor_controller::speed_steering\n\t\t\t> (\"motor_controller\/speed_steering_control\", 1);\n\tignition_control_pub_ = nh_.advertise < motor_controller::ignition_control\n\t\t\t> (\"motor_controller\/ignition_control\", 1);\n\trobot_state_sub_ = nh_.subscribe < robot_state::robot_state > (\"robot_state\/robot_state\", 10, &RemoteControllerCls::robotStateCallback, this);\n\trobot_state_change_request_pub_ = nh_.advertise < robot_state::robot_state> (\"robot_state\/robot_state_change_request\", 1, false);\n}\n\nvoid RemoteControllerCls::heartBeatStopCallback(const std_msgs::Bool::ConstPtr& stop)\n{\n\tif (robot_state != robot_state::robot_state_constants::RobotState_Stop)\n\t{\n\t\tif (stop->data == true)\n\t\t{\n\t\t\tROS_WARN(\"Heart beat not received.\");\n\t\t\trobot_state::robot_state stop_message;\n\t\t\tstop_message.state = robot_state::robot_state_constants::RobotState_Stop;\n\t\t\trobot_state_change_request_pub_.publish(stop_message);\n\n\t\t\tsleep(1);\n\t\t\t\/\/ Speak after state transition.\n\t\t\tspeech_engine::speech_request speech_message;\n\t\t\tstring speech_text = \"Connection lost!\";\n\t\t\tspeech_message.speech_request = speech_text;\n\t\t\tspeech_pub_.publish(speech_message);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tROS_WARN(\"No heart beat message received but value is false???.\");\n\t\t}\n\t}\n}\nvoid RemoteControllerCls::robotStateCallback(const robot_state::robot_state::ConstPtr& state)\n{\n\tChangeState((int)((int)state->state));\n}\n\n\nvoid RemoteControllerCls::ChangeState(int new_state)\n{\n\trobot_state = new_state;\n}\n\nvoid RemoteControllerCls::joyDiagCallback(const diagnostic_msgs::DiagnosticArray::ConstPtr& diag)\n{\n\tif (diag->status.size() > 0)\n\t{\n\t\tif (joy_ok && (diag->status[0].level != 0))\n\t\t{\n\t\t\tROS_WARN(\"Joystick disconnected\");\n\t\t\trobot_state::robot_state stop_message;\n\t\t\tstop_message.state = robot_state::robot_state_constants::RobotState_Stop;\n\t\t\trobot_state_change_request_pub_.publish(stop_message);\n\t\t}\n\t\tjoy_ok = (diag->status[0].level == 0);\n\t}\n\t\/\/ROS_INFO(\"Joy OK\");\n}\n\nvoid RemoteControllerCls::joyCallback(const sensor_msgs::Joy::ConstPtr& joy)\n{\n\t\/\/ROS_INFO(\"Joy callback OK: %d, Buttons: %d,%d,%d,%d\", joy_ok, joy->buttons[0],\n\t\/\/\t\t\t\t\t\tjoy->buttons[1], joy->buttons[2], joy->buttons[3], joy->buttons[4]);\n\tif (!joy_ok)\n\t{\n\n\t}\n\telse\n\t{\n\t\tif (robot_state == robot_state::robot_state_constants::RobotState_Remote)\n\t\t{\n\t\t\tif (joy->buttons[JoyIgnitionResetButton])\n\t\t\t{\n\t\t\t\tforce_next_ignition_ = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (joy->buttons[JoyIgnitionButton])\n\t\t\t\t{\n\t\t\t\t\tROS_INFO(\"Ignition button\");\n\t\t\t\t\tif (force_next_ignition_)\n\t\t\t\t\t{\n\t\t\t\t\t\tforce_next_ignition_ = false;\n\t\t\t\t\t\tmotor_controller::ignition_control ignition_message;\n\t\t\t\t\t\tignition_message.initiate_ignition = 1;\n\t\t\t\t\t\tignition_message.force = 1;\n\t\t\t\t\t\tignition_control_pub_.publish(ignition_message);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmotor_controller::ignition_control ignition_message;\n\t\t\t\t\t\tignition_message.initiate_ignition = 1;\n\t\t\t\t\t\tignition_message.force = 0;\n\t\t\t\t\t\tignition_control_pub_.publish(ignition_message);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (joy_ok)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat steering = joy->axes[JoyRotationAxis];\n\t\t\t\t\t\tfloat steering_degree = steering * MaximumSteeringAngle;\n\t\t\t\t\t\tfloat head = joy->axes[JoyHeadRotationAxis];\t\t\t\t\t\t\n\t\t\t\t\t\tfloat head_degree = steering * MaximumHeadAngle; \/\/ head * MaximumHeadAngle;\n\n\t\t\t\t\t\tfloat positive_speed = joy->axes[JoyLinearAxisPositive];\n\t\t\t\t\t\t\/\/ Map from [1,-1] to [0,1]\n\t\t\t\t\t\tpositive_speed = (1 - positive_speed) \/ 2.0f;\n\t\t\t\t\t\tfloat negative_speed = joy->axes[JoyLinearAxisNegative];\n\t\t\t\t\t\t\/\/ Map from [1,-1] to [0,1]\n\t\t\t\t\t\tnegative_speed = (1 - negative_speed) \/ 2.0f;\n\t\t\t\t\t\tfloat speed = positive_speed - negative_speed;\n\t\t\t\t\t\tfloat speed_mps = speed * MaximumForwardSpeed;\n\n\t\t\t\t\t\tmotor_controller::speed_steering speed_steering_message;\n\n\t\t\t\t\t\tspeed_steering_message.speed_mps.speed_mps = speed_mps;\n\t\t\t\t\t\tspeed_steering_message.steering_degree.degree = steering_degree;\n\t\t\t\t\t\tspeed_steering_message.head_degree.degree = head_degree;\n\n\t\t\t\t\t\tspeed_steering_pub_.publish(speed_steering_message);\n\t\t\t\t\t\tROS_INFO(\"Joy OK: %d, Speed: %f, Steering %f, Head %f\", joy_ok, speed_mps, steering_degree, head_degree);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(int argc, char** argv)\n{\n\tros::init(argc, argv, \"RemoteController\");\n\tRemoteControllerCls remote_controller;\n\tros::spin();\n}\n\nRemote control should send 0 speed when state changes#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 \/\/ standard input \/ output functions\n#include \/\/ string function definitions\n#include \/\/ UNIX standard function definitions\n#include \/\/ File control definitions\n#include \/\/ Error number definitions\n#include \/\/ POSIX terminal control definitions\n#include \/\/ time calls\n#include \n#include \n\nusing namespace std;\n\n\/\/const int JoyLinearAxisPositive = 9;\n\/\/const int JoyLinearAxisNegative = 8;\nconst int JoyLinearAxisPositive = 3;\nconst int JoyLinearAxisNegative = 1;\nconst int JoyRotationAxis = 0;\nconst int JoyHeadRotationAxis = 2;\nconst int JoyIgnitionButton = 1;\nconst int JoyIgnitionResetButton = 6;\nconst float MaximumHeadAngle = 90.0f;\nconst float MaximumSteeringAngle = 30.0f;\n\/\/\/ \n\/\/\/ Maximum forward travel speed in meters per second.\n\/\/\/ <\/summary>\nconst float MaximumForwardSpeed = 1.0f;\n\/\/\/ \n\/\/\/ Maximum reverse travel speed in meters per second.\n\/\/\/ <\/summary>\nconst float MaximumReverseSpeed = -1.0f;\n\nclass RemoteControllerCls\n{\npublic:\n\tRemoteControllerCls();\n\nprivate:\n\tvoid robotStateCallback(const robot_state::robot_state::ConstPtr& state);\n\tvoid joyCallback(const sensor_msgs::Joy::ConstPtr& joy);\n\tvoid heartBeatStopCallback(const std_msgs::Bool::ConstPtr& stop);\n\tvoid joyDiagCallback(const diagnostic_msgs::DiagnosticArray::ConstPtr& diag);\n\tvoid ChangeState(int new_state);\n\tvoid Stop();\n\tros::NodeHandle nh_;\n\n\tros::Publisher ignition_control_pub_;\n\tros::Publisher speed_steering_pub_;\n\tros::Subscriber heart_beat_stop_sub_;\n\tros::Subscriber joy_sub_;\n\tros::Subscriber joy_diag_sub_;\n\tros::Subscriber robot_state_sub_;\n\tros::Publisher robot_state_change_request_pub_;\n\tros::Publisher speech_pub_;\n\tbool force_next_ignition_;\n\tint robot_state;\n\tbool joy_ok;\n};\n\nvoid RemoteControllerCls::Stop() \n{\n\tmotor_controller::speed_steering speed_steering_message;\n\n\tspeed_steering_message.speed_mps.speed_mps = 0;\n\tspeed_steering_message.steering_degree.degree = 0;\n\tspeed_steering_message.head_degree.degree = 0;\n\n\tspeed_steering_pub_.publish(speed_steering_message);\n\tROS_INFO(\"Joy OK: %d, Speed: %f, Steering %f, Head %f\", joy_ok, 0, 0, 0);\n}\nRemoteControllerCls::RemoteControllerCls()\n{\n\tjoy_ok = false;\n\tforce_next_ignition_ = false;\n\t\/\/nh_.param(\"axis_linear\", linear_, linear_);\n\t\/\/nh_.param(\"axis_angular\", angular_, angular_);\n\t\/\/nh_.param(\"scale_angular\", a_scale_, a_scale_);\n\t\/\/nh_.param(\"scale_linear\", l_scale_, l_scale_);\n\tspeech_pub_ = nh_.advertise (\"speech_engine\/speech_request\", 1);\n\theart_beat_stop_sub_ = nh_.subscribe (\"heart_beat_stop\", 3, &RemoteControllerCls::heartBeatStopCallback, this);\n\tjoy_sub_ = nh_.subscribe < sensor_msgs::Joy> (\"joy\", 3, &RemoteControllerCls::joyCallback, this);\n\tjoy_diag_sub_ = nh_.subscribe < diagnostic_msgs::DiagnosticArray> (\"diagnostics\", 3, &RemoteControllerCls::joyDiagCallback, this);\n\tspeed_steering_pub_ = nh_.advertise < motor_controller::speed_steering\n\t\t\t> (\"motor_controller\/speed_steering_control\", 1);\n\tignition_control_pub_ = nh_.advertise < motor_controller::ignition_control\n\t\t\t> (\"motor_controller\/ignition_control\", 1);\n\trobot_state_sub_ = nh_.subscribe < robot_state::robot_state > (\"robot_state\/robot_state\", 10, &RemoteControllerCls::robotStateCallback, this);\n\trobot_state_change_request_pub_ = nh_.advertise < robot_state::robot_state> (\"robot_state\/robot_state_change_request\", 1, false);\n}\n\nvoid RemoteControllerCls::heartBeatStopCallback(const std_msgs::Bool::ConstPtr& stop)\n{\n\tif (robot_state != robot_state::robot_state_constants::RobotState_Stop)\n\t{\n\t\tif (stop->data == true)\n\t\t{\n\t\t\tROS_WARN(\"Heart beat not received.\");\n\t\t\trobot_state::robot_state stop_message;\n\t\t\tstop_message.state = robot_state::robot_state_constants::RobotState_Stop;\n\t\t\trobot_state_change_request_pub_.publish(stop_message);\n\n\t\t\tsleep(1);\n\t\t\t\/\/ Speak after state transition.\n\t\t\tspeech_engine::speech_request speech_message;\n\t\t\tstring speech_text = \"Connection lost!\";\n\t\t\tspeech_message.speech_request = speech_text;\n\t\t\tspeech_pub_.publish(speech_message);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tROS_WARN(\"No heart beat message received but value is false???.\");\n\t\t}\n\t}\n}\nvoid RemoteControllerCls::robotStateCallback(const robot_state::robot_state::ConstPtr& state)\n{\t\n\tChangeState((int)((int)state->state));\n\tStop();\n}\n\n\nvoid RemoteControllerCls::ChangeState(int new_state)\n{\n\trobot_state = new_state;\n}\n\nvoid RemoteControllerCls::joyDiagCallback(const diagnostic_msgs::DiagnosticArray::ConstPtr& diag)\n{\n\tif (diag->status.size() > 0)\n\t{\n\t\tif (joy_ok && (diag->status[0].level != 0))\n\t\t{\n\t\t\tROS_WARN(\"Joystick disconnected\");\n\t\t\trobot_state::robot_state stop_message;\n\t\t\tstop_message.state = robot_state::robot_state_constants::RobotState_Stop;\n\t\t\trobot_state_change_request_pub_.publish(stop_message);\n\t\t}\n\t\tjoy_ok = (diag->status[0].level == 0);\n\t}\n\t\/\/ROS_INFO(\"Joy OK\");\n}\n\nvoid RemoteControllerCls::joyCallback(const sensor_msgs::Joy::ConstPtr& joy)\n{\n\t\/\/ROS_INFO(\"Joy callback OK: %d, Buttons: %d,%d,%d,%d\", joy_ok, joy->buttons[0],\n\t\/\/\t\t\t\t\t\tjoy->buttons[1], joy->buttons[2], joy->buttons[3], joy->buttons[4]);\n\tif (!joy_ok)\n\t{\n\t\tStop();\n\t}\n\telse\n\t{\n\t\tif (robot_state == robot_state::robot_state_constants::RobotState_Remote)\n\t\t{\n\t\t\tif (joy->buttons[JoyIgnitionResetButton])\n\t\t\t{\n\t\t\t\tforce_next_ignition_ = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (joy->buttons[JoyIgnitionButton])\n\t\t\t\t{\n\t\t\t\t\tROS_INFO(\"Ignition button\");\n\t\t\t\t\tif (force_next_ignition_)\n\t\t\t\t\t{\n\t\t\t\t\t\tforce_next_ignition_ = false;\n\t\t\t\t\t\tmotor_controller::ignition_control ignition_message;\n\t\t\t\t\t\tignition_message.initiate_ignition = 1;\n\t\t\t\t\t\tignition_message.force = 1;\n\t\t\t\t\t\tignition_control_pub_.publish(ignition_message);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmotor_controller::ignition_control ignition_message;\n\t\t\t\t\t\tignition_message.initiate_ignition = 1;\n\t\t\t\t\t\tignition_message.force = 0;\n\t\t\t\t\t\tignition_control_pub_.publish(ignition_message);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (joy_ok)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat steering = joy->axes[JoyRotationAxis];\n\t\t\t\t\t\tfloat steering_degree = steering * MaximumSteeringAngle;\n\t\t\t\t\t\tfloat head = joy->axes[JoyHeadRotationAxis];\t\t\t\t\t\t\n\t\t\t\t\t\tfloat head_degree = steering * MaximumHeadAngle; \/\/ head * MaximumHeadAngle;\n\n\t\t\t\t\t\tfloat positive_speed = joy->axes[JoyLinearAxisPositive];\n\t\t\t\t\t\t\/\/ Map from [1,-1] to [0,1]\n\t\t\t\t\t\tpositive_speed = (1 - positive_speed) \/ 2.0f;\n\t\t\t\t\t\tfloat negative_speed = joy->axes[JoyLinearAxisNegative];\n\t\t\t\t\t\t\/\/ Map from [1,-1] to [0,1]\n\t\t\t\t\t\tnegative_speed = (1 - negative_speed) \/ 2.0f;\n\t\t\t\t\t\tfloat speed = positive_speed - negative_speed;\n\t\t\t\t\t\tfloat speed_mps = speed * MaximumForwardSpeed;\n\n\t\t\t\t\t\tmotor_controller::speed_steering speed_steering_message;\n\n\t\t\t\t\t\tspeed_steering_message.speed_mps.speed_mps = speed_mps;\n\t\t\t\t\t\tspeed_steering_message.steering_degree.degree = steering_degree;\n\t\t\t\t\t\tspeed_steering_message.head_degree.degree = head_degree;\n\n\t\t\t\t\t\tspeed_steering_pub_.publish(speed_steering_message);\n\t\t\t\t\t\tROS_INFO(\"Joy OK: %d, Speed: %f, Steering %f, Head %f\", joy_ok, speed_mps, steering_degree, head_degree);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(int argc, char** argv)\n{\n\tros::init(argc, argv, \"RemoteController\");\n\tRemoteControllerCls remote_controller;\n\tros::spin();\n}\n\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-gdt project:\n\/\/ https:\/\/github.com\/dune-community\/dune-gdt\n\/\/ Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.\n\/\/ License: Dual licensed as BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/ or GPL-2.0+ (http:\/\/opensource.org\/licenses\/gpl-license)\n\/\/ with \"runtime exception\" (http:\/\/www.dune-project.org\/license.html)\n\/\/ Authors:\n\/\/ Felix Schindler (2017)\n\n#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH\n#define DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"..\/problems\/base.hh\"\n#include \"base.hh\"\n#include \"ipdg.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace LinearElliptic {\n\n\n\/**\n * \\todo add pattern() to StationaryContainerBasedDefaultDiscretization, avoid computation of local_pattern below\n *\/\ntemplate \nclass BlockIpdgDiscretizer\n{\n typedef IpdgDiscretizer\n LocalDiscretizer;\n typedef typename LocalDiscretizer::DiscretizationType LocalDiscretizationType;\n typedef typename LocalDiscretizer::SpaceType LocalSpaceType;\n\npublic:\n typedef typename LocalDiscretizer::ProblemType ProblemType;\n typedef BlockSpace SpaceType;\n typedef typename LocalDiscretizer::MatrixType MatrixType;\n typedef typename LocalDiscretizer::VectorType VectorType;\n typedef StationaryContainerBasedDefaultDiscretization\n DiscretizationType;\n static const constexpr ChooseDiscretizer type = ChooseDiscretizer::block_ipdg;\n static const constexpr XT::LA::Backends la_backend = la;\n static const int polOrder = pol;\n\n static std::string static_id()\n {\n return std::string(\"gdt.linearelliptic.discretization.block-ipdg.order_\")\n + Dune::XT::Common::to_string(int(polOrder)); \/\/ int() needed, otherwise we get a linker error\n }\n\n static DiscretizationType\n discretize(XT::Grid::GridProvider>& grid_provider,\n const ProblemType& problem,\n const int \/*level*\/ = 0,\n const size_t inner_boundary_index = std::numeric_limits::max() - 42)\n {\n auto logger = XT::Common::TimedLogger().get(static_id());\n const auto& dd_grid = grid_provider.dd_grid();\n logger.info() << \"Creating \" << dd_grid.size() << \" local discretizations... \" << std::endl;\n XT::Common::Configuration local_boundary_cfg;\n local_boundary_cfg[\"type\"] = \"xt.grid.boundaryinfo.boundarysegmentindexbased\";\n local_boundary_cfg[\"default\"] = \"dirichlet\";\n local_boundary_cfg[\"neumann\"] =\n \"[\" + XT::Common::to_string(inner_boundary_index) + \" \" + XT::Common::to_string(inner_boundary_index + 1) + \"]\";\n LinearElliptic::ProblemBase::Entity,\n typename GridType::ctype,\n GridType::dimension,\n typename SpaceType::RangeFieldType,\n 1>\n local_problem(problem.diffusion_factor(),\n problem.diffusion_tensor(),\n problem.force(),\n problem.dirichlet(),\n problem.neumann(),\n XT::Common::Configuration(),\n local_boundary_cfg);\n std::vector local_discretizations;\n auto local_spaces_ptr = std::make_shared>();\n auto& local_spaces = *local_spaces_ptr;\n for (size_t ss = 0; ss < dd_grid.size(); ++ss) {\n local_discretizations.emplace_back(\n LocalDiscretizer::discretize(grid_provider, local_problem, boost::numeric_cast(ss)));\n local_spaces.emplace_back(local_discretizations.back().test_space());\n }\n logger.info() << \"Creating space... \" << std::endl;\n SpaceType space(dd_grid, local_spaces_ptr);\n\n logger.info() << \"Preparing container...\" << std::endl;\n std::vector local_patterns(dd_grid.size());\n std::vector> inside_outside_patterns(dd_grid.size());\n std::vector> outside_inside_patterns(dd_grid.size());\n std::map boundary_patterns;\n XT::LA::SparsityPatternDefault pattern(space.mapper().size());\n for (size_t ss = 0; ss < dd_grid.size(); ++ss) {\n local_patterns[ss] = local_spaces[ss].compute_face_and_volume_pattern(); \/\/ todo: from the local discretization\n copy_local_to_global(local_patterns[ss], space, ss, ss, pattern);\n if (dd_grid.boundary(ss)) {\n \/\/ in general, this can differ from the local one (think of CG)\n boundary_patterns[ss] = local_spaces[ss].compute_face_pattern(dd_grid.boundaryGridPart(ss));\n copy_local_to_global(boundary_patterns[ss], space, ss, ss, pattern);\n }\n for (auto&& nn : dd_grid.neighborsOf(ss)) {\n if (ss < nn) { \/\/ each coupling only once\n inside_outside_patterns[ss][nn] =\n local_spaces[ss].compute_face_pattern(dd_grid.couplingGridPart(ss, nn), local_spaces[nn]);\n copy_local_to_global(inside_outside_patterns[ss][nn], space, ss, nn, pattern);\n outside_inside_patterns[nn][ss] =\n local_spaces[nn].compute_face_pattern(dd_grid.couplingGridPart(nn, ss), local_spaces[ss]);\n copy_local_to_global(outside_inside_patterns[nn][ss], space, nn, ss, pattern);\n }\n }\n }\n pattern.sort();\n MatrixType system_matrix(space.mapper().size(), space.mapper().size(), pattern);\n VectorType rhs_vector(space.mapper().size());\n for (size_t ss = 0; ss < dd_grid.size(); ++ss) {\n copy_local_to_global(local_discretizations[ss].system_matrix(), local_patterns[ss], space, ss, ss, system_matrix);\n copy_local_to_global(local_discretizations[ss].rhs_vector(), space, ss, rhs_vector);\n }\n\n logger.info() << \"Assembling coupling contributions...\" << std::endl;\n for (size_t ss = 0; ss < dd_grid.size(); ++ss) {\n for (auto&& nn : dd_grid.neighborsOf(ss)) {\n if (ss < nn) { \/\/ each coupling only once\n MatrixType inside_inside_matrix(\n local_spaces[ss].mapper().size(), local_spaces[ss].mapper().size(), local_patterns[ss]);\n MatrixType outside_outside_matrix(\n local_spaces[nn].mapper().size(), local_spaces[nn].mapper().size(), local_patterns[nn]);\n MatrixType inside_outside_matrix(\n local_spaces[ss].mapper().size(), local_spaces[nn].mapper().size(), inside_outside_patterns[ss][nn]);\n MatrixType outside_inside_matrix(\n local_spaces[nn].mapper().size(), local_spaces[ss].mapper().size(), outside_inside_patterns[nn][ss]);\n auto coupling_grid_part = dd_grid.couplingGridPart(ss, nn);\n \/\/ put all of this into a coupling operator\n SystemAssembler coupling_assembler(\n coupling_grid_part, local_spaces[ss], local_spaces[ss], local_spaces[nn], local_spaces[nn]);\n typedef XT::Grid::extract_intersection_t IntersectionType;\n typedef LocalEllipticIpdgIntegrands::Inner\n CouplingIntegrandType;\n LocalCouplingIntegralOperator\n local_coupling_operator(problem.diffusion_factor(), problem.diffusion_tensor());\n LocalCouplingTwoFormAssembler local_coupling_assembler(\n local_coupling_operator);\n coupling_assembler.append(local_coupling_assembler,\n inside_inside_matrix,\n outside_outside_matrix,\n inside_outside_matrix,\n outside_inside_matrix);\n coupling_assembler.assemble();\n copy_local_to_global(inside_inside_matrix, local_patterns[ss], space, ss, ss, system_matrix);\n copy_local_to_global(outside_outside_matrix, local_patterns[nn], space, nn, nn, system_matrix);\n copy_local_to_global(inside_outside_matrix, inside_outside_patterns[ss][nn], space, ss, nn, system_matrix);\n copy_local_to_global(outside_inside_matrix, outside_inside_patterns[nn][ss], space, nn, ss, system_matrix);\n }\n }\n }\n\n logger.info() << \"Assembling boundary contributions...\" << std::endl;\n for (size_t ss = 0; ss < dd_grid.size(); ++ss) {\n if (dd_grid.boundary(ss)) {\n auto boundary_grid_part = dd_grid.boundaryGridPart(ss);\n auto boundary_pattern = local_spaces[ss].compute_face_and_volume_pattern(boundary_grid_part);\n MatrixType boundary_matrix(\n local_spaces[ss].mapper().size(), local_spaces[ss].mapper().size(), boundary_pattern);\n VectorType boundary_vector(local_spaces[ss].mapper().size());\n SystemAssembler boundary_assembler(local_spaces[ss],\n boundary_grid_part);\n typedef XT::Grid::extract_intersection_t IntersectionType;\n auto boundary_info = XT::Grid::BoundaryInfoFactory::create(problem.boundary_info_cfg());\n typedef LocalEllipticIpdgIntegrands::BoundaryLHS\n BoundaryLhsIntegrandType;\n LocalBoundaryIntegralOperator\n local_boundary_operator(problem.diffusion_factor(), problem.diffusion_tensor());\n LocalBoundaryTwoFormAssembler local_boundary_operator_assembler(\n local_boundary_operator);\n boundary_assembler.append(\n local_boundary_operator_assembler,\n boundary_matrix,\n new XT::Grid::ApplyOn::DirichletIntersections(*boundary_info));\n typedef LocalEllipticIpdgIntegrands::BoundaryRHS\n BoundaryRhsIntegrandType;\n LocalFaceIntegralFunctional\n local_boundary_functional(problem.dirichlet(), problem.diffusion_factor(), problem.diffusion_tensor());\n LocalFaceFunctionalAssembler local_boundary_functional_assembler(\n local_boundary_functional);\n boundary_assembler.append(\n local_boundary_functional_assembler,\n boundary_vector,\n new XT::Grid::ApplyOn::DirichletIntersections(*boundary_info));\n boundary_assembler.assemble();\n copy_local_to_global(boundary_matrix, boundary_pattern, space, ss, ss, system_matrix);\n copy_local_to_global(boundary_vector, space, ss, rhs_vector);\n }\n }\n\n \/\/ create the discretization (no copy of the containers done here, bc. of cow)\n return DiscretizationType(problem, space, system_matrix, rhs_vector);\n } \/\/ ... discretize(...)\n\nprivate:\n static void copy_local_to_global(const XT::LA::SparsityPatternDefault& local_pattern,\n const SpaceType& space,\n const size_t test_subdomain,\n const size_t ansatz_subdomain,\n XT::LA::SparsityPatternDefault& global_pattern)\n {\n const auto& mapper = space.mapper();\n for (size_t local_ii = 0; local_ii < local_pattern.size(); ++local_ii) {\n const size_t global_ii = mapper.mapToGlobal(test_subdomain, local_ii);\n const auto& local_rows = local_pattern.inner(local_ii);\n for (const auto& local_jj : local_rows) {\n const size_t global_jj = mapper.mapToGlobal(ansatz_subdomain, local_jj);\n global_pattern.insert(global_ii, global_jj);\n }\n }\n } \/\/ ... copy_local_to_global(...)\n\n static void copy_local_to_global(const MatrixType& local_matrix,\n const XT::LA::SparsityPatternDefault& local_pattern,\n const SpaceType& space,\n const size_t test_subdomain,\n const size_t ansatz_subdomain,\n MatrixType& global_matrix)\n {\n for (size_t local_ii = 0; local_ii < local_pattern.size(); ++local_ii) {\n const size_t global_ii = space.mapper().mapToGlobal(test_subdomain, local_ii);\n for (const size_t& local_jj : local_pattern.inner(local_ii)) {\n const size_t global_jj = space.mapper().mapToGlobal(ansatz_subdomain, local_jj);\n global_matrix.add_to_entry(global_ii, global_jj, local_matrix.get_entry(local_ii, local_jj));\n }\n }\n } \/\/ ... copy_local_to_global_matrix(...)\n\n static void copy_local_to_global(const VectorType& local_vector,\n const SpaceType& space,\n const size_t subdomain,\n VectorType& global_vector)\n {\n for (size_t local_ii = 0; local_ii < local_vector.size(); ++local_ii) {\n const size_t global_ii = space.mapper().mapToGlobal(subdomain, local_ii);\n global_vector.add_to_entry(global_ii, local_vector.get_entry(local_ii));\n }\n } \/\/ ... copy_local_to_global_matrix(...)\n}; \/\/ class BlockIpdgDiscretizer\n\n\n} \/\/ namespace LinearElliptic\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH\n[test.linearelliptic.block-ipdg] fix discretizer\/\/ This file is part of the dune-gdt project:\n\/\/ https:\/\/github.com\/dune-community\/dune-gdt\n\/\/ Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.\n\/\/ License: Dual licensed as BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/ or GPL-2.0+ (http:\/\/opensource.org\/licenses\/gpl-license)\n\/\/ with \"runtime exception\" (http:\/\/www.dune-project.org\/license.html)\n\/\/ Authors:\n\/\/ Felix Schindler (2017)\n\n#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH\n#define DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"..\/problems\/base.hh\"\n#include \"base.hh\"\n#include \"ipdg.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace LinearElliptic {\n\n\n\/**\n * \\todo add pattern() to StationaryContainerBasedDefaultDiscretization, avoid computation of local_pattern below\n *\/\ntemplate \nclass BlockIpdgDiscretizer\n{\n typedef IpdgDiscretizer\n LocalDiscretizer;\n typedef typename LocalDiscretizer::DiscretizationType LocalDiscretizationType;\n typedef typename LocalDiscretizer::SpaceType LocalSpaceType;\n\npublic:\n typedef typename LocalDiscretizer::ProblemType ProblemType;\n typedef BlockSpace SpaceType;\n typedef typename LocalDiscretizer::MatrixType MatrixType;\n typedef typename LocalDiscretizer::VectorType VectorType;\n typedef StationaryContainerBasedDefaultDiscretization\n DiscretizationType;\n static const constexpr ChooseDiscretizer type = ChooseDiscretizer::block_ipdg;\n static const constexpr XT::LA::Backends la_backend = la;\n static const int polOrder = pol;\n\n static std::string static_id()\n {\n return std::string(\"gdt.linearelliptic.discretization.block-ipdg.order_\")\n + Dune::XT::Common::to_string(int(polOrder)); \/\/ int() needed, otherwise we get a linker error\n }\n\n static DiscretizationType\n discretize(XT::Grid::GridProvider>& grid_provider,\n const ProblemType& problem,\n const int \/*level*\/ = 0)\n {\n auto logger = XT::Common::TimedLogger().get(static_id());\n const auto& dd_grid = grid_provider.dd_grid();\n logger.info() << \"Creating \" << dd_grid.size() << \" local discretizations... \" << std::endl;\n const LinearElliptic::ProblemBase::Entity,\n typename GridType::ctype,\n GridType::dimension,\n typename SpaceType::RangeFieldType,\n 1>\n local_problem(problem.diffusion_factor(),\n problem.diffusion_tensor(),\n problem.force(),\n problem.dirichlet(),\n problem.neumann(),\n XT::Common::Configuration(),\n XT::Grid::allneumann_boundaryinfo_default_config());\n std::vector local_discretizations;\n auto local_spaces_ptr = std::make_shared>();\n auto& local_spaces = *local_spaces_ptr;\n for (size_t ss = 0; ss < dd_grid.size(); ++ss)\n local_discretizations.emplace_back(\n LocalDiscretizer::discretize(grid_provider, local_problem, XT::Common::numeric_cast(ss)));\n\n logger.info() << \"Creating space... \" << std::endl;\n for (size_t ss = 0; ss < dd_grid.size(); ++ss)\n local_spaces.emplace_back(local_discretizations[ss].test_space());\n SpaceType space(dd_grid, local_spaces_ptr);\n\n logger.info() << \"Preparing container...\" << std::endl;\n std::vector local_patterns(dd_grid.size());\n std::map boundary_patterns;\n std::vector> coupling_patterns(dd_grid.size());\n XT::LA::SparsityPatternDefault pattern(space.mapper().size());\n for (size_t ss = 0; ss < dd_grid.size(); ++ss) {\n local_patterns[ss] = local_spaces[ss].compute_face_and_volume_pattern();\n copy_local_to_global(local_patterns[ss], space, ss, ss, pattern);\n if (dd_grid.boundary(ss)) {\n boundary_patterns[ss] = local_spaces[ss].compute_volume_pattern(dd_grid.boundaryGridPart(ss));\n copy_local_to_global(boundary_patterns[ss], space, ss, ss, pattern);\n }\n coupling_patterns[ss][ss] = local_spaces[ss].compute_volume_pattern(); \/\/ this is too much, but we are relazy here\n for (auto&& nn : dd_grid.neighborsOf(ss)) {\n if (ss < nn) { \/\/ each coupling only once\n coupling_patterns[ss][nn] =\n local_spaces[ss].compute_face_pattern(dd_grid.couplingGridPart(ss, nn), local_spaces[nn]);\n coupling_patterns[nn][ss] =\n local_spaces[nn].compute_face_pattern(dd_grid.couplingGridPart(nn, ss), local_spaces[ss]);\n copy_local_to_global(coupling_patterns[ss][ss], space, ss, ss, pattern);\n copy_local_to_global(coupling_patterns[ss][nn], space, ss, nn, pattern);\n copy_local_to_global(coupling_patterns[nn][ss], space, nn, ss, pattern);\n }\n }\n }\n pattern.sort();\n MatrixType system_matrix(space.mapper().size(), space.mapper().size(), pattern);\n VectorType rhs_vector(space.mapper().size());\n for (size_t ss = 0; ss < dd_grid.size(); ++ss) {\n copy_local_to_global(local_discretizations[ss].system_matrix(), local_patterns[ss], space, ss, ss, system_matrix);\n copy_local_to_global(local_discretizations[ss].rhs_vector(), space, ss, rhs_vector);\n }\n\n logger.info() << \"Assembling coupling contributions...\" << std::endl;\n for (size_t ss = 0; ss < dd_grid.size(); ++ss) {\n for (auto&& nn : dd_grid.neighborsOf(ss)) {\n if (ss < nn) { \/\/ each coupling only once\n MatrixType inside_inside_matrix(\n local_spaces[ss].mapper().size(), local_spaces[ss].mapper().size(), coupling_patterns[ss][ss]);\n MatrixType outside_outside_matrix(\n local_spaces[nn].mapper().size(), local_spaces[nn].mapper().size(), coupling_patterns[nn][nn]);\n MatrixType inside_outside_matrix(\n local_spaces[ss].mapper().size(), local_spaces[nn].mapper().size(), coupling_patterns[ss][nn]);\n MatrixType outside_inside_matrix(\n local_spaces[nn].mapper().size(), local_spaces[ss].mapper().size(), coupling_patterns[nn][ss]);\n auto coupling_grid_part = dd_grid.couplingGridPart(ss, nn);\n \/\/ put all of this into a coupling operator\n SystemAssembler coupling_assembler(\n coupling_grid_part, local_spaces[ss], local_spaces[ss], local_spaces[nn], local_spaces[nn]);\n typedef XT::Grid::extract_intersection_t IntersectionType;\n typedef LocalEllipticIpdgIntegrands::Inner\n CouplingIntegrandType;\n LocalCouplingIntegralOperator\n local_coupling_operator(problem.diffusion_factor(), problem.diffusion_tensor());\n coupling_assembler.append(local_coupling_operator,\n inside_inside_matrix,\n outside_outside_matrix,\n inside_outside_matrix,\n outside_inside_matrix);\n coupling_assembler.assemble();\n copy_local_to_global(inside_inside_matrix, coupling_patterns[ss][ss], space, ss, ss, system_matrix);\n copy_local_to_global(outside_outside_matrix, coupling_patterns[nn][nn], space, nn, nn, system_matrix);\n copy_local_to_global(inside_outside_matrix, coupling_patterns[ss][nn], space, ss, nn, system_matrix);\n copy_local_to_global(outside_inside_matrix, coupling_patterns[nn][ss], space, nn, ss, system_matrix);\n }\n }\n }\n\n logger.info() << \"Assembling boundary contributions...\" << std::endl;\n for (size_t ss = 0; ss < dd_grid.size(); ++ss) {\n if (dd_grid.boundary(ss)) {\n auto boundary_grid_part = dd_grid.boundaryGridPart(ss);\n MatrixType boundary_matrix(\n local_spaces[ss].mapper().size(), local_spaces[ss].mapper().size(), boundary_patterns[ss]);\n VectorType boundary_vector(local_spaces[ss].mapper().size());\n SystemAssembler boundary_assembler(local_spaces[ss],\n boundary_grid_part);\n typedef XT::Grid::extract_intersection_t IntersectionType;\n auto boundary_info = XT::Grid::BoundaryInfoFactory::create(problem.boundary_info_cfg());\n typedef LocalEllipticIpdgIntegrands::BoundaryLHS\n BoundaryLhsIntegrandType;\n LocalBoundaryIntegralOperator\n local_boundary_operator(problem.diffusion_factor(), problem.diffusion_tensor());\n boundary_assembler.append(\n local_boundary_operator,\n boundary_matrix,\n new XT::Grid::ApplyOn::DirichletIntersections(*boundary_info));\n typedef LocalEllipticIpdgIntegrands::BoundaryRHS\n BoundaryRhsIntegrandType;\n LocalFaceIntegralFunctional\n local_boundary_functional(problem.dirichlet(), problem.diffusion_factor(), problem.diffusion_tensor());\n LocalFaceFunctionalAssembler local_boundary_functional_assembler(\n local_boundary_functional);\n boundary_assembler.append(\n local_boundary_functional_assembler,\n boundary_vector,\n new XT::Grid::ApplyOn::DirichletIntersections(*boundary_info));\n boundary_assembler.assemble();\n copy_local_to_global(boundary_matrix, boundary_patterns[ss], space, ss, ss, system_matrix);\n copy_local_to_global(boundary_vector, space, ss, rhs_vector);\n }\n }\n\n \/\/ create the discretization (no copy of the containers done here, bc. of cow)\n return DiscretizationType(problem, space, system_matrix, rhs_vector);\n } \/\/ ... discretize(...)\n\nprivate:\n static void copy_local_to_global(const XT::LA::SparsityPatternDefault& local_pattern,\n const SpaceType& space,\n const size_t test_subdomain,\n const size_t ansatz_subdomain,\n XT::LA::SparsityPatternDefault& global_pattern)\n {\n const auto& mapper = space.mapper();\n for (size_t local_ii = 0; local_ii < local_pattern.size(); ++local_ii) {\n const size_t global_ii = mapper.mapToGlobal(test_subdomain, local_ii);\n const auto& local_rows = local_pattern.inner(local_ii);\n for (const auto& local_jj : local_rows) {\n const size_t global_jj = mapper.mapToGlobal(ansatz_subdomain, local_jj);\n global_pattern.insert(global_ii, global_jj);\n }\n }\n } \/\/ ... copy_local_to_global(...)\n\n static void copy_local_to_global(const MatrixType& local_matrix,\n const XT::LA::SparsityPatternDefault& local_pattern,\n const SpaceType& space,\n const size_t test_subdomain,\n const size_t ansatz_subdomain,\n MatrixType& global_matrix)\n {\n for (size_t local_ii = 0; local_ii < local_pattern.size(); ++local_ii) {\n const size_t global_ii = space.mapper().mapToGlobal(test_subdomain, local_ii);\n for (const size_t& local_jj : local_pattern.inner(local_ii)) {\n const size_t global_jj = space.mapper().mapToGlobal(ansatz_subdomain, local_jj);\n global_matrix.add_to_entry(global_ii, global_jj, local_matrix.get_entry(local_ii, local_jj));\n }\n }\n } \/\/ ... copy_local_to_global_matrix(...)\n\n static void copy_local_to_global(const VectorType& local_vector,\n const SpaceType& space,\n const size_t subdomain,\n VectorType& global_vector)\n {\n for (size_t local_ii = 0; local_ii < local_vector.size(); ++local_ii) {\n const size_t global_ii = space.mapper().mapToGlobal(subdomain, local_ii);\n global_vector.add_to_entry(global_ii, local_vector.get_entry(local_ii));\n }\n } \/\/ ... copy_local_to_global_matrix(...)\n}; \/\/ class BlockIpdgDiscretizer\n\n\n} \/\/ namespace LinearElliptic\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"gcd_utility.hpp\"\n#include \"human_interface_device.hpp\"\n#include \"spdlog_utility.hpp\"\n\nnamespace krbn {\nclass hid_grabber final {\npublic:\n struct signal2_combiner_call_while_grabbable {\n typedef grabbable_state result_type;\n\n template \n result_type operator()(input_iterator first_observer,\n input_iterator last_observer) const {\n result_type value = grabbable_state::grabbable;\n for (;\n first_observer != last_observer && value == grabbable_state::grabbable;\n std::advance(first_observer, 1)) {\n value = *first_observer;\n }\n return value;\n }\n };\n\n \/\/ Signals\n\n boost::signals2::signal\n device_grabbing;\n\n boost::signals2::signal device_grabbed;\n\n boost::signals2::signal device_ungrabbed;\n\n \/\/ Methods\n\n hid_grabber(human_interface_device& human_interface_device) : human_interface_device_(human_interface_device),\n grabbed_(false) {\n }\n\n ~hid_grabber(void) {\n ungrab();\n }\n\n bool get_grabbed(void) const {\n return grabbed_;\n }\n\n void grab(void) {\n gcd_utility::dispatch_sync_in_main_queue(^{\n log_reducer_.reset();\n\n timer_ = nullptr;\n\n timer_ = std::make_unique(\n 1 * NSEC_PER_SEC,\n ^{\n if (human_interface_device_.get_removed()) {\n return true;\n }\n\n if (grabbed_) {\n return true;\n }\n\n switch (device_grabbing(human_interface_device_)) {\n case grabbable_state::grabbable:\n break;\n\n case grabbable_state::ungrabbable_temporarily:\n case grabbable_state::device_error:\n \/\/ Retry\n return false;\n\n case grabbable_state::ungrabbable_permanently:\n return true;\n }\n\n \/\/ ----------------------------------------\n auto r = human_interface_device_.open(kIOHIDOptionsTypeSeizeDevice);\n if (r != kIOReturnSuccess) {\n auto message = fmt::format(\"IOHIDDeviceOpen error: {0} ({1}) {2}\",\n iokit_utility::get_error_name(r),\n r,\n human_interface_device_.get_name_for_log());\n log_reducer_.error(message);\n return false;\n }\n\n \/\/ ----------------------------------------\n grabbed_ = true;\n\n device_grabbed(human_interface_device_);\n\n human_interface_device_.queue_start();\n human_interface_device_.schedule();\n\n return true;\n });\n });\n }\n\n void ungrab(void) {\n gcd_utility::dispatch_sync_in_main_queue(^{\n timer_ = nullptr;\n\n if (!grabbed_) {\n return;\n }\n\n human_interface_device_.unschedule();\n human_interface_device_.queue_stop();\n human_interface_device_.close();\n\n grabbed_ = false;\n\n device_ungrabbed(human_interface_device_);\n });\n }\n\nprivate:\n human_interface_device& human_interface_device_;\n bool grabbed_;\n std::unique_ptr timer_;\n spdlog_utility::log_reducer log_reducer_;\n};\n} \/\/ namespace krbn\nuse weak_ptr in hid_grabber#pragma once\n\n#include \"gcd_utility.hpp\"\n#include \"human_interface_device.hpp\"\n#include \"spdlog_utility.hpp\"\n\nnamespace krbn {\nclass hid_grabber final {\npublic:\n struct signal2_combiner_call_while_grabbable {\n typedef grabbable_state result_type;\n\n template \n result_type operator()(input_iterator first_observer,\n input_iterator last_observer) const {\n result_type value = grabbable_state::grabbable;\n for (;\n first_observer != last_observer && value == grabbable_state::grabbable;\n std::advance(first_observer, 1)) {\n value = *first_observer;\n }\n return value;\n }\n };\n\n \/\/ Signals\n\n boost::signals2::signal),\n signal2_combiner_call_while_grabbable>\n device_grabbing;\n\n boost::signals2::signal)> device_grabbed;\n\n boost::signals2::signal)> device_ungrabbed;\n\n \/\/ Methods\n\n hid_grabber(std::shared_ptr human_interface_device) : human_interface_device_(human_interface_device),\n grabbed_(false) {\n }\n\n ~hid_grabber(void) {\n ungrab();\n }\n\n bool get_grabbed(void) const {\n return grabbed_;\n }\n\n void grab(void) {\n gcd_utility::dispatch_sync_in_main_queue(^{\n log_reducer_.reset();\n\n timer_ = nullptr;\n\n timer_ = std::make_unique(\n 1 * NSEC_PER_SEC,\n ^{\n if (auto hid = human_interface_device_.lock()) {\n if (hid->get_removed()) {\n return true;\n }\n\n if (grabbed_) {\n return true;\n }\n\n switch (device_grabbing(hid)) {\n case grabbable_state::grabbable:\n break;\n\n case grabbable_state::ungrabbable_temporarily:\n case grabbable_state::device_error:\n \/\/ Retry\n return false;\n\n case grabbable_state::ungrabbable_permanently:\n return true;\n }\n\n \/\/ ----------------------------------------\n auto r = hid->open(kIOHIDOptionsTypeSeizeDevice);\n if (r != kIOReturnSuccess) {\n auto message = fmt::format(\"IOHIDDeviceOpen error: {0} ({1}) {2}\",\n iokit_utility::get_error_name(r),\n r,\n hid->get_name_for_log());\n log_reducer_.error(message);\n return false;\n }\n\n \/\/ ----------------------------------------\n grabbed_ = true;\n\n device_grabbed(hid);\n\n hid->queue_start();\n hid->schedule();\n }\n\n return true;\n });\n });\n }\n\n void ungrab(void) {\n gcd_utility::dispatch_sync_in_main_queue(^{\n timer_ = nullptr;\n\n if (auto hid = human_interface_device_.lock()) {\n if (!grabbed_) {\n return;\n }\n\n hid->unschedule();\n hid->queue_stop();\n hid->close();\n\n grabbed_ = false;\n\n device_ungrabbed(hid);\n }\n });\n }\n\nprivate:\n std::weak_ptr human_interface_device_;\n bool grabbed_;\n std::unique_ptr timer_;\n spdlog_utility::log_reducer log_reducer_;\n};\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"CppExporter.h\"\n\n#include \"OOModel\/src\/declarations\/Project.h\"\n#include \"OOModel\/src\/expressions\/MetaCallExpression.h\"\n#include \"OOModel\/src\/declarations\/TypeAlias.h\"\n\n#include \"Export\/src\/writer\/Exporter.h\"\n#include \"Export\/src\/writer\/FragmentLayouter.h\"\n#include \"Export\/src\/tree\/CompositeFragment.h\"\n#include \"ModelBase\/src\/model\/TreeManager.h\"\n\n#include \"..\/CodeUnit.h\"\n#include \"..\/CodeComposite.h\"\n#include \"..\/Config.h\"\n\nnamespace CppExport {\n\nQList CppExporter::exportTree(Model::TreeManager* treeManager,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst QString& pathToProjectContainerDirectory)\n{\n\tQList codeUnits;\n\tunits(treeManager->root(), \"\", codeUnits);\n\n\tfor (auto unit : codeUnits) unit->calculateSourceFragments();\n\tfor (auto unit : codeUnits) unit->calculateDependencies(codeUnits);\n\n\tauto directory = new Export::SourceDir(nullptr, pathToProjectContainerDirectory + \"\/src\");\n\tfor (auto codeComposite : mergeUnits(codeUnits))\n\t\tcreateFilesFromComposite(directory, codeComposite);\n\n\tauto layout = layouter();\n\tExport::Exporter::exportToFileSystem(\"\", directory, &layout);\n\n\treturn {};\n\n}\n\nvoid CppExporter::createFilesFromComposite(Export::SourceDir* directory, CodeComposite* codeComposite)\n{\n\tExport::SourceFragment* headerFragment{};\n\tExport::SourceFragment* sourceFragment{};\n\tcodeComposite->fragments(headerFragment, sourceFragment);\n\n\tif (headerFragment) directory->file(codeComposite->name() + \".h\").append(headerFragment);\n\tif (sourceFragment) directory->file(codeComposite->name() + \".cpp\").append(sourceFragment);\n}\n\nvoid CppExporter::units(Model::Node* current, QString namespaceName, QList& result)\n{\n\tif (!DCast(current))\n\t{\n\t\tif (auto ooModule = DCast(current))\n\t\t{\n\t\t\t\/\/ ignore the \"ExternalMacro\" module\n\t\t\tif (ooModule->name() == \"ExternalMacro\") return;\n\n\t\t\tnamespaceName = ooModule->name();\n\t\t}\n\t\telse if (auto ooClass = DCast(current))\n\t\t{\n\t\t\tresult.append(new CodeUnit((namespaceName.isEmpty() ? \"\" : namespaceName + \"\/\") + ooClass->name(), current));\n\t\t\treturn;\n\t\t}\n\t\telse if (auto ooMetaCall = DCast(current))\n\t\t{\n\t\t\tauto ooCalleeReference = DCast(ooMetaCall->callee());\n\t\t\tQ_ASSERT(ooCalleeReference);\n\t\t\tresult.append(new CodeUnit((namespaceName.isEmpty() ? \"\" : namespaceName + \"\/\") + ooCalleeReference->name(),\n\t\t\t\t\t\t\t\t\t\t\t\tcurrent));\n\t\t\treturn;\n\t\t}\n\t}\n\n\tfor (auto child : current->children())\n\t\tunits(child, namespaceName, result);\n}\n\nQList CppExporter::mergeUnits(QList& units)\n{\n\tQHash mergeMap = Config::instance().dependencyUnitMergeMap();\n\n\tQHash nameToCompositeMap;\n\tfor (auto unit : units)\n\t{\n\t\tauto it = mergeMap.find(unit->name());\n\t\tauto compositeName = it != mergeMap.end() ? *it : unit->name();\n\n\t\tauto cIt = nameToCompositeMap.find(compositeName);\n\t\tif (cIt != nameToCompositeMap.end())\n\t\t\t\/\/ case A: the composite that unit is a part of already exists => merge\n\t\t\t(*cIt)->addUnit(unit);\n\t\telse\n\t\t{\n\t\t\t\/\/ case B: the composite that unit is a part of does not yet exist\n\t\t\tauto composite = new CodeComposite(compositeName);\n\t\t\tcomposite->addUnit(unit);\n\t\t\tnameToCompositeMap.insert(composite->name(), composite);\n\t\t}\n\t}\n\n\treturn nameToCompositeMap.values();\n}\n\nExport::FragmentLayouter CppExporter::layouter()\n{\n\tauto result = Export::FragmentLayouter{\"\\t\"};\n\tresult.addRule(\"enumerators\", Export::FragmentLayouter::SpaceAfterSeparator, \"\", \",\", \"\");\n\tresult.addRule(\"vertical\", Export::FragmentLayouter::NoIndentation, \"\", \"\\n\", \"\");\n\tresult.addRule(\"sections\", Export::FragmentLayouter::NoIndentation, \"\", \"\\n\", \"\");\n\tresult.addRule(\"declarationComment\", Export::FragmentLayouter::NoIndentation\n\t\t\t\t\t\t\t| Export::FragmentLayouter::NewLineAfterPostfix, \"\", \"\\n\", \"\");\n\tresult.addRule(\"spacedSections\", Export::FragmentLayouter::NoIndentation, \"\", \"\\n\\n\", \"\");\n\tresult.addRule(\"accessorSections\", Export::FragmentLayouter::IndentChildFragments, \"\", \"\\n\", \"\");\n\tresult.addRule(\"bodySections\", Export::FragmentLayouter::NewLineBefore\n\t\t\t\t\t\t | Export::FragmentLayouter::IndentChildFragments | Export::FragmentLayouter::NewLineAfterPrefix\n\t\t\t\t\t\t | Export::FragmentLayouter::NewLineBeforePostfix, \"{\", \"\\n\", \"}\");\n\tresult.addRule(\"space\", Export::FragmentLayouter::SpaceAtEnd, \"\", \" \", \"\");\n\tresult.addRule(\"comma\", Export::FragmentLayouter::SpaceAfterSeparator, \"\", \",\", \"\");\n\tresult.addRule(\"baseClasses\", Export::FragmentLayouter::SpaceAfterSeparator, \" : public \", \",\", \"\");\n\tresult.addRule(\"initializerList\", Export::FragmentLayouter::SpaceAfterSeparator, \"{\", \",\", \"}\");\n\tresult.addRule(\"argsList\", Export::FragmentLayouter::SpaceAfterSeparator, \"(\", \",\", \")\");\n\tresult.addRule(\"typeArgsList\", Export::FragmentLayouter::SpaceAfterSeparator, \"<\", \",\", \">\");\n\tresult.addRule(\"templateArgsList\", Export::FragmentLayouter::SpaceAfterSeparator\n\t\t\t\t\t\t\t| Export::FragmentLayouter::NewLineAfterPostfix, \"template<\", \",\", \">\");\n\n\tresult.addRule(\"body\", Export::FragmentLayouter::NewLineBefore | Export::FragmentLayouter::IndentChildFragments\n\t\t\t\t\t\t\t| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix,\n\t\t\t\t\t\t\t\"{\", \"\\n\", \"}\");\n\tresult.addRule(\"bodyNoBraces\", Export::FragmentLayouter::NewLineBefore\n\t\t\t\t\t\t\t| Export::FragmentLayouter::IndentChildFragments | Export::FragmentLayouter::NewLineAfterPrefix\n\t\t\t\t\t\t\t| Export::FragmentLayouter::NewLineBeforePostfix, \"\", \"\\n\", \"\");\n\tresult.addRule(\"macroBody\", Export::FragmentLayouter::NewLineBefore | Export::FragmentLayouter::IndentChildFragments\n\t\t\t\t\t\t\t| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix,\n\t\t\t\t\t\t\t\"\", \"\\n\", \"\");\n\tresult.addRule(\"macro\", Export::FragmentLayouter::BackslashAfterLines\n\t\t\t\t\t\t| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix);\n\tresult.addRule(\"emptyLineAtEnd\", Export::FragmentLayouter::EmptyLineAtEnd);\n\n\treturn result;\n}\n\nExport::ExportMapContainer& CppExporter::exportMaps()\n{\n\tstatic Export::ExportMapContainer* container = new Export::ExportMapContainer();\n\treturn *container;\n}\n\n}\nremove unused layout\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"CppExporter.h\"\n\n#include \"OOModel\/src\/declarations\/Project.h\"\n#include \"OOModel\/src\/expressions\/MetaCallExpression.h\"\n#include \"OOModel\/src\/declarations\/TypeAlias.h\"\n\n#include \"Export\/src\/writer\/Exporter.h\"\n#include \"Export\/src\/writer\/FragmentLayouter.h\"\n#include \"Export\/src\/tree\/CompositeFragment.h\"\n#include \"ModelBase\/src\/model\/TreeManager.h\"\n\n#include \"..\/CodeUnit.h\"\n#include \"..\/CodeComposite.h\"\n#include \"..\/Config.h\"\n\nnamespace CppExport {\n\nQList CppExporter::exportTree(Model::TreeManager* treeManager,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst QString& pathToProjectContainerDirectory)\n{\n\tQList codeUnits;\n\tunits(treeManager->root(), \"\", codeUnits);\n\n\tfor (auto unit : codeUnits) unit->calculateSourceFragments();\n\tfor (auto unit : codeUnits) unit->calculateDependencies(codeUnits);\n\n\tauto directory = new Export::SourceDir(nullptr, pathToProjectContainerDirectory + \"\/src\");\n\tfor (auto codeComposite : mergeUnits(codeUnits))\n\t\tcreateFilesFromComposite(directory, codeComposite);\n\n\tauto layout = layouter();\n\tExport::Exporter::exportToFileSystem(\"\", directory, &layout);\n\n\treturn {};\n\n}\n\nvoid CppExporter::createFilesFromComposite(Export::SourceDir* directory, CodeComposite* codeComposite)\n{\n\tExport::SourceFragment* headerFragment{};\n\tExport::SourceFragment* sourceFragment{};\n\tcodeComposite->fragments(headerFragment, sourceFragment);\n\n\tif (headerFragment) directory->file(codeComposite->name() + \".h\").append(headerFragment);\n\tif (sourceFragment) directory->file(codeComposite->name() + \".cpp\").append(sourceFragment);\n}\n\nvoid CppExporter::units(Model::Node* current, QString namespaceName, QList& result)\n{\n\tif (!DCast(current))\n\t{\n\t\tif (auto ooModule = DCast(current))\n\t\t{\n\t\t\t\/\/ ignore the \"ExternalMacro\" module\n\t\t\tif (ooModule->name() == \"ExternalMacro\") return;\n\n\t\t\tnamespaceName = ooModule->name();\n\t\t}\n\t\telse if (auto ooClass = DCast(current))\n\t\t{\n\t\t\tresult.append(new CodeUnit((namespaceName.isEmpty() ? \"\" : namespaceName + \"\/\") + ooClass->name(), current));\n\t\t\treturn;\n\t\t}\n\t\telse if (auto ooMetaCall = DCast(current))\n\t\t{\n\t\t\tauto ooCalleeReference = DCast(ooMetaCall->callee());\n\t\t\tQ_ASSERT(ooCalleeReference);\n\t\t\tresult.append(new CodeUnit((namespaceName.isEmpty() ? \"\" : namespaceName + \"\/\") + ooCalleeReference->name(),\n\t\t\t\t\t\t\t\t\t\t\t\tcurrent));\n\t\t\treturn;\n\t\t}\n\t}\n\n\tfor (auto child : current->children())\n\t\tunits(child, namespaceName, result);\n}\n\nQList CppExporter::mergeUnits(QList& units)\n{\n\tQHash mergeMap = Config::instance().dependencyUnitMergeMap();\n\n\tQHash nameToCompositeMap;\n\tfor (auto unit : units)\n\t{\n\t\tauto it = mergeMap.find(unit->name());\n\t\tauto compositeName = it != mergeMap.end() ? *it : unit->name();\n\n\t\tauto cIt = nameToCompositeMap.find(compositeName);\n\t\tif (cIt != nameToCompositeMap.end())\n\t\t\t\/\/ case A: the composite that unit is a part of already exists => merge\n\t\t\t(*cIt)->addUnit(unit);\n\t\telse\n\t\t{\n\t\t\t\/\/ case B: the composite that unit is a part of does not yet exist\n\t\t\tauto composite = new CodeComposite(compositeName);\n\t\t\tcomposite->addUnit(unit);\n\t\t\tnameToCompositeMap.insert(composite->name(), composite);\n\t\t}\n\t}\n\n\treturn nameToCompositeMap.values();\n}\n\nExport::FragmentLayouter CppExporter::layouter()\n{\n\tauto result = Export::FragmentLayouter{\"\\t\"};\n\tresult.addRule(\"enumerators\", Export::FragmentLayouter::SpaceAfterSeparator, \"\", \",\", \"\");\n\tresult.addRule(\"vertical\", Export::FragmentLayouter::NoIndentation, \"\", \"\\n\", \"\");\n\tresult.addRule(\"sections\", Export::FragmentLayouter::NoIndentation, \"\", \"\\n\", \"\");\n\tresult.addRule(\"declarationComment\", Export::FragmentLayouter::NoIndentation\n\t\t\t\t\t\t\t| Export::FragmentLayouter::NewLineAfterPostfix, \"\", \"\\n\", \"\");\n\tresult.addRule(\"spacedSections\", Export::FragmentLayouter::NoIndentation, \"\", \"\\n\\n\", \"\");\n\tresult.addRule(\"accessorSections\", Export::FragmentLayouter::IndentChildFragments, \"\", \"\\n\", \"\");\n\tresult.addRule(\"bodySections\", Export::FragmentLayouter::NewLineBefore\n\t\t\t\t\t\t | Export::FragmentLayouter::IndentChildFragments | Export::FragmentLayouter::NewLineAfterPrefix\n\t\t\t\t\t\t | Export::FragmentLayouter::NewLineBeforePostfix, \"{\", \"\\n\", \"}\");\n\tresult.addRule(\"space\", Export::FragmentLayouter::SpaceAtEnd, \"\", \" \", \"\");\n\tresult.addRule(\"comma\", Export::FragmentLayouter::SpaceAfterSeparator, \"\", \",\", \"\");\n\tresult.addRule(\"initializerList\", Export::FragmentLayouter::SpaceAfterSeparator, \"{\", \",\", \"}\");\n\tresult.addRule(\"argsList\", Export::FragmentLayouter::SpaceAfterSeparator, \"(\", \",\", \")\");\n\tresult.addRule(\"typeArgsList\", Export::FragmentLayouter::SpaceAfterSeparator, \"<\", \",\", \">\");\n\tresult.addRule(\"templateArgsList\", Export::FragmentLayouter::SpaceAfterSeparator\n\t\t\t\t\t\t\t| Export::FragmentLayouter::NewLineAfterPostfix, \"template<\", \",\", \">\");\n\n\tresult.addRule(\"body\", Export::FragmentLayouter::NewLineBefore | Export::FragmentLayouter::IndentChildFragments\n\t\t\t\t\t\t\t| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix,\n\t\t\t\t\t\t\t\"{\", \"\\n\", \"}\");\n\tresult.addRule(\"bodyNoBraces\", Export::FragmentLayouter::NewLineBefore\n\t\t\t\t\t\t\t| Export::FragmentLayouter::IndentChildFragments | Export::FragmentLayouter::NewLineAfterPrefix\n\t\t\t\t\t\t\t| Export::FragmentLayouter::NewLineBeforePostfix, \"\", \"\\n\", \"\");\n\tresult.addRule(\"macroBody\", Export::FragmentLayouter::NewLineBefore | Export::FragmentLayouter::IndentChildFragments\n\t\t\t\t\t\t\t| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix,\n\t\t\t\t\t\t\t\"\", \"\\n\", \"\");\n\tresult.addRule(\"macro\", Export::FragmentLayouter::BackslashAfterLines\n\t\t\t\t\t\t| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix);\n\tresult.addRule(\"emptyLineAtEnd\", Export::FragmentLayouter::EmptyLineAtEnd);\n\n\treturn result;\n}\n\nExport::ExportMapContainer& CppExporter::exportMaps()\n{\n\tstatic Export::ExportMapContainer* container = new Export::ExportMapContainer();\n\treturn *container;\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Modified by Cloudius Systems\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \"core\/shared_ptr.hh\"\n#include \"core\/sstring.hh\"\n#include \"types.hh\"\n#include \"keys.hh\"\n#include \"utils\/managed_bytes.hh\"\n#include \n#include \n#include \n\nnamespace sstables {\n\nclass key_view;\n\n}\n\nnamespace dht {\n\n\/\/\n\/\/ Origin uses a complex class hierarchy where Token is an abstract class,\n\/\/ and various subclasses use different implementations (LongToken vs.\n\/\/ BigIntegerToken vs. StringToken), plus other variants to to signify the\n\/\/ the beginning of the token space etc.\n\/\/\n\/\/ We'll fold all of that into the token class and push all of the variations\n\/\/ into its users.\n\nclass decorated_key;\nclass token;\nclass ring_position;\n\nclass token {\npublic:\n enum class kind {\n before_all_keys,\n key,\n after_all_keys,\n };\n kind _kind;\n \/\/ _data can be interpreted as a big endian binary fraction\n \/\/ in the range [0.0, 1.0).\n \/\/\n \/\/ So, [] == 0.0\n \/\/ [0x00] == 0.0\n \/\/ [0x80] == 0.5\n \/\/ [0x00, 0x80] == 1\/512\n \/\/ [0xff, 0x80] == 1 - 1\/512\n managed_bytes _data;\n token(kind k, managed_bytes d) : _kind(std::move(k)), _data(std::move(d)) {\n }\n\n bool is_minimum() const {\n return _kind == kind::before_all_keys;\n }\n\n bool is_maximum() const {\n return _kind == kind::after_all_keys;\n }\n\n\n void serialize(bytes::iterator& out) const;\n static token deserialize(bytes_view& in);\n size_t serialized_size() const;\n};\n\ntoken midpoint_unsigned(const token& t1, const token& t2);\ntoken minimum_token();\ntoken maximum_token();\nbool operator==(const token& t1, const token& t2);\nbool operator<(const token& t1, const token& t2);\nint tri_compare(const token& t1, const token& t2);\ninline bool operator!=(const token& t1, const token& t2) { return std::rel_ops::operator!=(t1, t2); }\ninline bool operator>(const token& t1, const token& t2) { return std::rel_ops::operator>(t1, t2); }\ninline bool operator<=(const token& t1, const token& t2) { return std::rel_ops::operator<=(t1, t2); }\ninline bool operator>=(const token& t1, const token& t2) { return std::rel_ops::operator>=(t1, t2); }\nstd::ostream& operator<<(std::ostream& out, const token& t);\n\ntemplate \ninline auto get_random_number() {\n static thread_local std::random_device rd;\n static thread_local std::default_random_engine re(rd());\n static thread_local std::uniform_int_distribution dist{};\n return dist(re);\n}\n\n\/\/ Wraps partition_key with its corresponding token.\n\/\/\n\/\/ Total ordering defined by comparators is compatible with Origin's ordering.\nclass decorated_key {\npublic:\n dht::token _token;\n partition_key _key;\n\n struct less_comparator {\n schema_ptr s;\n less_comparator(schema_ptr s);\n bool operator()(const decorated_key& k1, const decorated_key& k2) const;\n bool operator()(const decorated_key& k1, const ring_position& k2) const;\n bool operator()(const ring_position& k1, const decorated_key& k2) const;\n };\n\n bool equal(const schema& s, const decorated_key& other) const;\n\n bool less_compare(const schema& s, const decorated_key& other) const;\n bool less_compare(const schema& s, const ring_position& other) const;\n\n \/\/ Trichotomic comparators defining total ordering on the union of\n \/\/ decorated_key and ring_position objects.\n int tri_compare(const schema& s, const decorated_key& other) const;\n int tri_compare(const schema& s, const ring_position& other) const;\n\n const dht::token& token() const {\n return _token;\n }\n\n const partition_key& key() const {\n return _key;\n }\n};\n\nusing decorated_key_opt = std::experimental::optional;\n\nclass i_partitioner {\npublic:\n virtual ~i_partitioner() {}\n\n \/**\n * Transform key to object representation of the on-disk format.\n *\n * @param key the raw, client-facing key\n * @return decorated version of key\n *\/\n decorated_key decorate_key(const schema& s, const partition_key& key) {\n return { get_token(s, key), key };\n }\n\n \/**\n * Transform key to object representation of the on-disk format.\n *\n * @param key the raw, client-facing key\n * @return decorated version of key\n *\/\n decorated_key decorate_key(const schema& s, partition_key&& key) {\n auto token = get_token(s, key);\n return { std::move(token), std::move(key) };\n }\n\n \/**\n * Calculate a token representing the approximate \"middle\" of the given\n * range.\n *\n * @return The approximate midpoint between left and right.\n *\/\n virtual token midpoint(const token& left, const token& right) const = 0;\n\n \/**\n * @return A token smaller than all others in the range that is being partitioned.\n * Not legal to assign to a node or key. (But legal to use in range scans.)\n *\/\n token get_minimum_token() {\n return dht::minimum_token();\n }\n\n \/**\n * @return a token that can be used to route a given key\n * (This is NOT a method to create a token from its string representation;\n * for that, use tokenFactory.fromString.)\n *\/\n virtual token get_token(const schema& s, partition_key_view key) = 0;\n virtual token get_token(const sstables::key_view& key) = 0;\n\n\n \/**\n * @return a partitioner-specific string representation of this token\n *\/\n virtual sstring to_sstring(const dht::token& t) const = 0;\n\n \/**\n * @return a token from its partitioner-specific string representation\n *\/\n virtual dht::token from_sstring(const sstring& t) const = 0;\n\n \/**\n * @return a randomly generated token\n *\/\n virtual token get_random_token() = 0;\n\n \/\/ FIXME: token.tokenFactory\n \/\/virtual token.tokenFactory gettokenFactory() = 0;\n\n \/**\n * @return True if the implementing class preserves key order in the tokens\n * it generates.\n *\/\n virtual bool preserves_order() = 0;\n\n \/**\n * Calculate the deltas between tokens in the ring in order to compare\n * relative sizes.\n *\n * @param sortedtokens a sorted List of tokens\n * @return the mapping from 'token' to 'percentage of the ring owned by that token'.\n *\/\n virtual std::map describe_ownership(const std::vector& sorted_tokens) = 0;\n\n virtual data_type get_token_validator() = 0;\n\n \/**\n * @return name of partitioner.\n *\/\n virtual const sstring name() = 0;\n\n \/**\n * Calculates the shard that handles a particular token.\n *\/\n virtual unsigned shard_of(const token& t) const = 0;\n\n \/**\n * @return bytes that represent the token as required by get_token_validator().\n *\/\n virtual bytes token_to_bytes(const token& t) const {\n return bytes(t._data.begin(), t._data.end());\n }\nprotected:\n \/**\n * @return < 0 if if t1's _data array is less, t2's. 0 if they are equal, and > 0 otherwise. _kind comparison should be done separately.\n *\/\n virtual int tri_compare(const token& t1, const token& t2);\n \/**\n * @return true if t1's _data array is equal t2's. _kind comparison should be done separately.\n *\/\n bool is_equal(const token& t1, const token& t2) {\n return tri_compare(t1, t2) == 0;\n }\n \/**\n * @return true if t1's _data array is less then t2's. _kind comparison should be done separately.\n *\/\n bool is_less(const token& t1, const token& t2) {\n return tri_compare(t1, t2) < 0;\n }\n\n friend bool operator==(const token& t1, const token& t2);\n friend bool operator<(const token& t1, const token& t2);\n friend int tri_compare(const token& t1, const token& t2);\n};\n\n\/\/\n\/\/ Represents position in the ring of partitions, where partitions are ordered\n\/\/ according to decorated_key ordering (first by token, then by key value).\n\/\/ Intended to be used for defining partition ranges.\n\/\/\n\/\/ The 'key' part is optional. When it's absent, this object represents a position\n\/\/ which is either before or after all keys sharing given token. That's determined\n\/\/ by relation_to_keys().\n\/\/\n\/\/ For example for the following data:\n\/\/\n\/\/ tokens: | t1 | t2 |\n\/\/ +----+----+----+\n\/\/ keys: | k1 | k2 | k3 |\n\/\/\n\/\/ The ordering is:\n\/\/\n\/\/ ring_position(t1, token_bound::start) < ring_position(k1)\n\/\/ ring_position(k1) < ring_position(k2)\n\/\/ ring_position(k1) == decorated_key(k1)\n\/\/ ring_position(k2) == decorated_key(k2)\n\/\/ ring_position(k2) < ring_position(t1, token_bound::end)\n\/\/ ring_position(k2) < ring_position(k3)\n\/\/ ring_position(t1, token_bound::end) < ring_position(t2, token_bound::start)\n\/\/\n\/\/ Maps to org.apache.cassandra.db.RowPosition and its derivatives in Origin.\n\/\/\nclass ring_position {\npublic:\n enum class token_bound : int8_t { start = -1, end = 1 };\nprivate:\n dht::token _token;\n token_bound _token_bound; \/\/ valid when !_key\n std::experimental::optional _key;\npublic:\n static ring_position starting_at(dht::token token) {\n return { std::move(token), token_bound::start };\n }\n\n static ring_position ending_at(dht::token token) {\n return { std::move(token), token_bound::end };\n }\n\n ring_position(dht::token token, token_bound bound)\n : _token(std::move(token))\n , _token_bound(bound)\n { }\n\n ring_position(dht::token token, partition_key key)\n : _token(std::move(token))\n , _key(std::experimental::make_optional(std::move(key)))\n { }\n\n ring_position(const dht::decorated_key& dk)\n : _token(dk._token)\n , _key(std::experimental::make_optional(dk._key))\n { }\n\n const dht::token& token() const {\n return _token;\n }\n\n \/\/ Valid when !has_key()\n token_bound bound() const {\n return _token_bound;\n }\n\n \/\/ Returns -1 if smaller than keys with the same token, +1 if greater.\n \/\/ Valid when !has_key().\n int relation_to_keys() const {\n return static_cast(_token_bound);\n }\n\n const std::experimental::optional& key() const {\n return _key;\n }\n\n bool has_key() const {\n return bool(_key);\n }\n\n \/\/ Call only when has_key()\n dht::decorated_key as_decorated_key() const {\n return { _token, *_key };\n }\n\n bool equal(const schema&, const ring_position&) const;\n\n \/\/ Trichotomic comparator defining a total ordering on ring_position objects\n int tri_compare(const schema&, const ring_position&) const;\n\n \/\/ \"less\" comparator corresponding to tri_compare()\n bool less_compare(const schema&, const ring_position&) const;\n\n size_t serialized_size() const;\n void serialize(bytes::iterator& out) const;\n static ring_position deserialize(bytes_view& in);\n\n friend std::ostream& operator<<(std::ostream&, const ring_position&);\n};\n\n\/\/ Trichotomic comparator for ring_position\nstruct ring_position_comparator {\n const schema& s;\n ring_position_comparator(const schema& s_) : s(s_) {}\n int operator()(const ring_position& lh, const ring_position& rh) const;\n};\n\n\/\/ \"less\" comparator for ring_position\nstruct ring_position_less_comparator {\n const schema& s;\n ring_position_less_comparator(const schema& s_) : s(s_) {}\n bool operator()(const ring_position& lh, const ring_position& rh) const {\n return lh.less_compare(s, rh);\n }\n};\n\nstruct token_comparator {\n \/\/ Return values are those of a trichotomic comparison.\n int operator()(const token& t1, const token& t2) const;\n};\n\nstd::ostream& operator<<(std::ostream& out, const token& t);\n\nstd::ostream& operator<<(std::ostream& out, const decorated_key& t);\n\nvoid set_global_partitioner(const sstring& class_name);\ni_partitioner& global_partitioner();\n\nunsigned shard_of(const token&);\n\n} \/\/ dht\n\nnamespace std {\ntemplate<>\nstruct hash {\n size_t operator()(const dht::token& t) const {\n return (t._kind == dht::token::kind::key) ? std::hash()(t._data) : 0;\n }\n};\n}\nAdd ring_position constructor needed by serializer.\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Modified by Cloudius Systems\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \"core\/shared_ptr.hh\"\n#include \"core\/sstring.hh\"\n#include \"types.hh\"\n#include \"keys.hh\"\n#include \"utils\/managed_bytes.hh\"\n#include \n#include \n#include \n\nnamespace sstables {\n\nclass key_view;\n\n}\n\nnamespace dht {\n\n\/\/\n\/\/ Origin uses a complex class hierarchy where Token is an abstract class,\n\/\/ and various subclasses use different implementations (LongToken vs.\n\/\/ BigIntegerToken vs. StringToken), plus other variants to to signify the\n\/\/ the beginning of the token space etc.\n\/\/\n\/\/ We'll fold all of that into the token class and push all of the variations\n\/\/ into its users.\n\nclass decorated_key;\nclass token;\nclass ring_position;\n\nclass token {\npublic:\n enum class kind {\n before_all_keys,\n key,\n after_all_keys,\n };\n kind _kind;\n \/\/ _data can be interpreted as a big endian binary fraction\n \/\/ in the range [0.0, 1.0).\n \/\/\n \/\/ So, [] == 0.0\n \/\/ [0x00] == 0.0\n \/\/ [0x80] == 0.5\n \/\/ [0x00, 0x80] == 1\/512\n \/\/ [0xff, 0x80] == 1 - 1\/512\n managed_bytes _data;\n token(kind k, managed_bytes d) : _kind(std::move(k)), _data(std::move(d)) {\n }\n\n bool is_minimum() const {\n return _kind == kind::before_all_keys;\n }\n\n bool is_maximum() const {\n return _kind == kind::after_all_keys;\n }\n\n\n void serialize(bytes::iterator& out) const;\n static token deserialize(bytes_view& in);\n size_t serialized_size() const;\n};\n\ntoken midpoint_unsigned(const token& t1, const token& t2);\ntoken minimum_token();\ntoken maximum_token();\nbool operator==(const token& t1, const token& t2);\nbool operator<(const token& t1, const token& t2);\nint tri_compare(const token& t1, const token& t2);\ninline bool operator!=(const token& t1, const token& t2) { return std::rel_ops::operator!=(t1, t2); }\ninline bool operator>(const token& t1, const token& t2) { return std::rel_ops::operator>(t1, t2); }\ninline bool operator<=(const token& t1, const token& t2) { return std::rel_ops::operator<=(t1, t2); }\ninline bool operator>=(const token& t1, const token& t2) { return std::rel_ops::operator>=(t1, t2); }\nstd::ostream& operator<<(std::ostream& out, const token& t);\n\ntemplate \ninline auto get_random_number() {\n static thread_local std::random_device rd;\n static thread_local std::default_random_engine re(rd());\n static thread_local std::uniform_int_distribution dist{};\n return dist(re);\n}\n\n\/\/ Wraps partition_key with its corresponding token.\n\/\/\n\/\/ Total ordering defined by comparators is compatible with Origin's ordering.\nclass decorated_key {\npublic:\n dht::token _token;\n partition_key _key;\n\n struct less_comparator {\n schema_ptr s;\n less_comparator(schema_ptr s);\n bool operator()(const decorated_key& k1, const decorated_key& k2) const;\n bool operator()(const decorated_key& k1, const ring_position& k2) const;\n bool operator()(const ring_position& k1, const decorated_key& k2) const;\n };\n\n bool equal(const schema& s, const decorated_key& other) const;\n\n bool less_compare(const schema& s, const decorated_key& other) const;\n bool less_compare(const schema& s, const ring_position& other) const;\n\n \/\/ Trichotomic comparators defining total ordering on the union of\n \/\/ decorated_key and ring_position objects.\n int tri_compare(const schema& s, const decorated_key& other) const;\n int tri_compare(const schema& s, const ring_position& other) const;\n\n const dht::token& token() const {\n return _token;\n }\n\n const partition_key& key() const {\n return _key;\n }\n};\n\nusing decorated_key_opt = std::experimental::optional;\n\nclass i_partitioner {\npublic:\n virtual ~i_partitioner() {}\n\n \/**\n * Transform key to object representation of the on-disk format.\n *\n * @param key the raw, client-facing key\n * @return decorated version of key\n *\/\n decorated_key decorate_key(const schema& s, const partition_key& key) {\n return { get_token(s, key), key };\n }\n\n \/**\n * Transform key to object representation of the on-disk format.\n *\n * @param key the raw, client-facing key\n * @return decorated version of key\n *\/\n decorated_key decorate_key(const schema& s, partition_key&& key) {\n auto token = get_token(s, key);\n return { std::move(token), std::move(key) };\n }\n\n \/**\n * Calculate a token representing the approximate \"middle\" of the given\n * range.\n *\n * @return The approximate midpoint between left and right.\n *\/\n virtual token midpoint(const token& left, const token& right) const = 0;\n\n \/**\n * @return A token smaller than all others in the range that is being partitioned.\n * Not legal to assign to a node or key. (But legal to use in range scans.)\n *\/\n token get_minimum_token() {\n return dht::minimum_token();\n }\n\n \/**\n * @return a token that can be used to route a given key\n * (This is NOT a method to create a token from its string representation;\n * for that, use tokenFactory.fromString.)\n *\/\n virtual token get_token(const schema& s, partition_key_view key) = 0;\n virtual token get_token(const sstables::key_view& key) = 0;\n\n\n \/**\n * @return a partitioner-specific string representation of this token\n *\/\n virtual sstring to_sstring(const dht::token& t) const = 0;\n\n \/**\n * @return a token from its partitioner-specific string representation\n *\/\n virtual dht::token from_sstring(const sstring& t) const = 0;\n\n \/**\n * @return a randomly generated token\n *\/\n virtual token get_random_token() = 0;\n\n \/\/ FIXME: token.tokenFactory\n \/\/virtual token.tokenFactory gettokenFactory() = 0;\n\n \/**\n * @return True if the implementing class preserves key order in the tokens\n * it generates.\n *\/\n virtual bool preserves_order() = 0;\n\n \/**\n * Calculate the deltas between tokens in the ring in order to compare\n * relative sizes.\n *\n * @param sortedtokens a sorted List of tokens\n * @return the mapping from 'token' to 'percentage of the ring owned by that token'.\n *\/\n virtual std::map describe_ownership(const std::vector& sorted_tokens) = 0;\n\n virtual data_type get_token_validator() = 0;\n\n \/**\n * @return name of partitioner.\n *\/\n virtual const sstring name() = 0;\n\n \/**\n * Calculates the shard that handles a particular token.\n *\/\n virtual unsigned shard_of(const token& t) const = 0;\n\n \/**\n * @return bytes that represent the token as required by get_token_validator().\n *\/\n virtual bytes token_to_bytes(const token& t) const {\n return bytes(t._data.begin(), t._data.end());\n }\nprotected:\n \/**\n * @return < 0 if if t1's _data array is less, t2's. 0 if they are equal, and > 0 otherwise. _kind comparison should be done separately.\n *\/\n virtual int tri_compare(const token& t1, const token& t2);\n \/**\n * @return true if t1's _data array is equal t2's. _kind comparison should be done separately.\n *\/\n bool is_equal(const token& t1, const token& t2) {\n return tri_compare(t1, t2) == 0;\n }\n \/**\n * @return true if t1's _data array is less then t2's. _kind comparison should be done separately.\n *\/\n bool is_less(const token& t1, const token& t2) {\n return tri_compare(t1, t2) < 0;\n }\n\n friend bool operator==(const token& t1, const token& t2);\n friend bool operator<(const token& t1, const token& t2);\n friend int tri_compare(const token& t1, const token& t2);\n};\n\n\/\/\n\/\/ Represents position in the ring of partitions, where partitions are ordered\n\/\/ according to decorated_key ordering (first by token, then by key value).\n\/\/ Intended to be used for defining partition ranges.\n\/\/\n\/\/ The 'key' part is optional. When it's absent, this object represents a position\n\/\/ which is either before or after all keys sharing given token. That's determined\n\/\/ by relation_to_keys().\n\/\/\n\/\/ For example for the following data:\n\/\/\n\/\/ tokens: | t1 | t2 |\n\/\/ +----+----+----+\n\/\/ keys: | k1 | k2 | k3 |\n\/\/\n\/\/ The ordering is:\n\/\/\n\/\/ ring_position(t1, token_bound::start) < ring_position(k1)\n\/\/ ring_position(k1) < ring_position(k2)\n\/\/ ring_position(k1) == decorated_key(k1)\n\/\/ ring_position(k2) == decorated_key(k2)\n\/\/ ring_position(k2) < ring_position(t1, token_bound::end)\n\/\/ ring_position(k2) < ring_position(k3)\n\/\/ ring_position(t1, token_bound::end) < ring_position(t2, token_bound::start)\n\/\/\n\/\/ Maps to org.apache.cassandra.db.RowPosition and its derivatives in Origin.\n\/\/\nclass ring_position {\npublic:\n enum class token_bound : int8_t { start = -1, end = 1 };\nprivate:\n dht::token _token;\n token_bound _token_bound; \/\/ valid when !_key\n std::experimental::optional _key;\npublic:\n static ring_position starting_at(dht::token token) {\n return { std::move(token), token_bound::start };\n }\n\n static ring_position ending_at(dht::token token) {\n return { std::move(token), token_bound::end };\n }\n\n ring_position(dht::token token, token_bound bound)\n : _token(std::move(token))\n , _token_bound(bound)\n { }\n\n ring_position(dht::token token, partition_key key)\n : _token(std::move(token))\n , _key(std::experimental::make_optional(std::move(key)))\n { }\n\n ring_position(dht::token token, token_bound bound, std::experimental::optional key)\n : _token(std::move(token))\n , _token_bound(bound)\n , _key(std::move(key))\n { }\n\n ring_position(const dht::decorated_key& dk)\n : _token(dk._token)\n , _key(std::experimental::make_optional(dk._key))\n { }\n\n const dht::token& token() const {\n return _token;\n }\n\n \/\/ Valid when !has_key()\n token_bound bound() const {\n return _token_bound;\n }\n\n \/\/ Returns -1 if smaller than keys with the same token, +1 if greater.\n \/\/ Valid when !has_key().\n int relation_to_keys() const {\n return static_cast(_token_bound);\n }\n\n const std::experimental::optional& key() const {\n return _key;\n }\n\n bool has_key() const {\n return bool(_key);\n }\n\n \/\/ Call only when has_key()\n dht::decorated_key as_decorated_key() const {\n return { _token, *_key };\n }\n\n bool equal(const schema&, const ring_position&) const;\n\n \/\/ Trichotomic comparator defining a total ordering on ring_position objects\n int tri_compare(const schema&, const ring_position&) const;\n\n \/\/ \"less\" comparator corresponding to tri_compare()\n bool less_compare(const schema&, const ring_position&) const;\n\n size_t serialized_size() const;\n void serialize(bytes::iterator& out) const;\n static ring_position deserialize(bytes_view& in);\n\n friend std::ostream& operator<<(std::ostream&, const ring_position&);\n};\n\n\/\/ Trichotomic comparator for ring_position\nstruct ring_position_comparator {\n const schema& s;\n ring_position_comparator(const schema& s_) : s(s_) {}\n int operator()(const ring_position& lh, const ring_position& rh) const;\n};\n\n\/\/ \"less\" comparator for ring_position\nstruct ring_position_less_comparator {\n const schema& s;\n ring_position_less_comparator(const schema& s_) : s(s_) {}\n bool operator()(const ring_position& lh, const ring_position& rh) const {\n return lh.less_compare(s, rh);\n }\n};\n\nstruct token_comparator {\n \/\/ Return values are those of a trichotomic comparison.\n int operator()(const token& t1, const token& t2) const;\n};\n\nstd::ostream& operator<<(std::ostream& out, const token& t);\n\nstd::ostream& operator<<(std::ostream& out, const decorated_key& t);\n\nvoid set_global_partitioner(const sstring& class_name);\ni_partitioner& global_partitioner();\n\nunsigned shard_of(const token&);\n\n} \/\/ dht\n\nnamespace std {\ntemplate<>\nstruct hash {\n size_t operator()(const dht::token& t) const {\n return (t._kind == dht::token::kind::key) ? std::hash()(t._data) : 0;\n }\n};\n}\n<|endoftext|>"} {"text":"#include \"eightpuzzlestate.h\"\n\nEightPuzzle::EightPuzzleState::EightPuzzleState(EightPuzzleId* id, EightPuzzleState* father, EightPuzzleOperator* fatherOperator, int depth, double cost) : State(id, father, fatherOperator, depth, cost)\n{\n}\n\nEightPuzzle::EightPuzzleState::~EightPuzzleState()\n{\n}\n\nbool EightPuzzle::EightPuzzleState::isFinal()\n{\n return ((EightPuzzleId*)getId())->getIdValue().compare(\"12345678x\") == 0;\n}\n\nstd::vector EightPuzzle::EightPuzzleState::getAllowedOperators()\n{\n std::pair pos = getBlankPiecePos();\n std::vector operatorAllowed;\n\n Operator* up = new EightPuzzleOperator(\"up\");\n Operator* down = new EightPuzzleOperator(\"down\");\n Operator* left = new EightPuzzleOperator(\"left\");\n Operator* right = new EightPuzzleOperator(\"right\");\n\n operatorAllowed.push_back(up);\n operatorAllowed.push_back(down);\n operatorAllowed.push_back(left);\n operatorAllowed.push_back(right);\n\n switch (pos.first) {\n case 0:\n operatorAllowed.erase(std::remove(operatorAllowed.begin(), operatorAllowed.end(), up), operatorAllowed.end());\n break;\n case 2:\n operatorAllowed.erase(std::remove(operatorAllowed.begin(), operatorAllowed.end(), down), operatorAllowed.end());\n break;\n default:\n break;\n }\n\n switch (pos.second) {\n case 0:\n operatorAllowed.erase(std::remove(operatorAllowed.begin(), operatorAllowed.end(), left), operatorAllowed.end());\n break;\n case 2:\n operatorAllowed.erase(std::remove(operatorAllowed.begin(), operatorAllowed.end(), right), operatorAllowed.end());\n break;\n default:\n break;\n }\n\n for (Operator* var : operatorAllowed) {\n std::cout << \"|\" << ((EightPuzzleOperator*)var)->getOperatorValue() << \"|\";\n }\n std::cout << std::endl;\n\n return operatorAllowed;\n}\n\nstd::vector EightPuzzle::EightPuzzleState::genChilds(std::vector allowedOperators)\n{\n std::vector childs;\n\n for (int var = 0; var < allowedOperators.size(); ++var) {\n\n Operator* side = allowedOperators[var];\n\n childs.push_back(new EightPuzzleState((EightPuzzleId*)applyOperator(side), this, (EightPuzzleOperator*)side, getDepth() + 1, getCost() + 1));\n }\n\n return childs;\n}\n\nstd::pair EightPuzzle::EightPuzzleState::getBlankPiecePos()\n{\n std::size_t pos = ((EightPuzzleId*)getId())->getIdValue().find(\"x\");\n int row = pos \/ 3;\n int col = pos % 3;\n return std::pair(row, col);\n}\n\nId* EightPuzzle::EightPuzzleState::applyOperator(Operator* op)\n{\n std::string newId = ((EightPuzzleId*)getId())->getIdValue();\n std::pair blankPos = getBlankPiecePos();\n std::pair numberPos;\n\n if (((EightPuzzleOperator*)op)->getOperatorValue().compare(\"up\") == 0)\n {\n numberPos = std::pair(blankPos.first - 1, blankPos.second);\n }\n else if (((EightPuzzleOperator*)op)->getOperatorValue().compare(\"down\") == 0)\n {\n numberPos = std::pair(blankPos.first + 1, blankPos.second);\n }\n else if (((EightPuzzleOperator*)op)->getOperatorValue().compare(\"left\") == 0)\n {\n numberPos = std::pair(blankPos.first, blankPos.second - 1);\n }\n else if (((EightPuzzleOperator*)op)->getOperatorValue().compare(\"right\") == 0)\n {\n numberPos = std::pair(blankPos.first, blankPos.second + 1);\n }\n\n std::string letter1 = \"\";\n std::string letter2 = \"\";\n\n letter1 += ((EightPuzzleId*)getId())->getIdValue().at(numberPos.first * 3 + numberPos.second);\n letter2 += ((EightPuzzleId*)getId())->getIdValue().at(blankPos.first * 3 + blankPos.second);\n\n newId.replace(blankPos.first * 3 + blankPos.second, 1, letter1.c_str());\n newId.replace(numberPos.first * 3 + numberPos.second, 1, letter2.c_str());\n\n return new EightPuzzleId(newId);\n}\nRemove some debugs#include \"eightpuzzlestate.h\"\n\nEightPuzzle::EightPuzzleState::EightPuzzleState(EightPuzzleId* id, EightPuzzleState* father, EightPuzzleOperator* fatherOperator, int depth, double cost) : State(id, father, fatherOperator, depth, cost)\n{\n}\n\nEightPuzzle::EightPuzzleState::~EightPuzzleState()\n{\n}\n\nbool EightPuzzle::EightPuzzleState::isFinal()\n{\n return ((EightPuzzleId*)getId())->getIdValue().compare(\"12345678x\") == 0;\n}\n\nstd::vector EightPuzzle::EightPuzzleState::getAllowedOperators()\n{\n std::pair pos = getBlankPiecePos();\n std::vector operatorAllowed;\n\n Operator* up = new EightPuzzleOperator(\"up\");\n Operator* down = new EightPuzzleOperator(\"down\");\n Operator* left = new EightPuzzleOperator(\"left\");\n Operator* right = new EightPuzzleOperator(\"right\");\n\n operatorAllowed.push_back(up);\n operatorAllowed.push_back(down);\n operatorAllowed.push_back(left);\n operatorAllowed.push_back(right);\n\n switch (pos.first) {\n case 0:\n operatorAllowed.erase(std::remove(operatorAllowed.begin(), operatorAllowed.end(), up), operatorAllowed.end());\n break;\n case 2:\n operatorAllowed.erase(std::remove(operatorAllowed.begin(), operatorAllowed.end(), down), operatorAllowed.end());\n break;\n default:\n break;\n }\n\n switch (pos.second) {\n case 0:\n operatorAllowed.erase(std::remove(operatorAllowed.begin(), operatorAllowed.end(), left), operatorAllowed.end());\n break;\n case 2:\n operatorAllowed.erase(std::remove(operatorAllowed.begin(), operatorAllowed.end(), right), operatorAllowed.end());\n break;\n default:\n break;\n }\n\n return operatorAllowed;\n}\n\nstd::vector EightPuzzle::EightPuzzleState::genChilds(std::vector allowedOperators)\n{\n std::vector childs;\n\n for (int var = 0; var < allowedOperators.size(); ++var) {\n\n Operator* side = allowedOperators[var];\n\n childs.push_back(new EightPuzzleState((EightPuzzleId*)applyOperator(side), this, (EightPuzzleOperator*)side, getDepth() + 1, getCost() + 1));\n }\n\n return childs;\n}\n\nstd::pair EightPuzzle::EightPuzzleState::getBlankPiecePos()\n{\n std::size_t pos = ((EightPuzzleId*)getId())->getIdValue().find(\"x\");\n int row = pos \/ 3;\n int col = pos % 3;\n return std::pair(row, col);\n}\n\nId* EightPuzzle::EightPuzzleState::applyOperator(Operator* op)\n{\n std::string newId = ((EightPuzzleId*)getId())->getIdValue();\n std::pair blankPos = getBlankPiecePos();\n std::pair numberPos;\n\n if (((EightPuzzleOperator*)op)->getOperatorValue().compare(\"up\") == 0)\n {\n numberPos = std::pair(blankPos.first - 1, blankPos.second);\n }\n else if (((EightPuzzleOperator*)op)->getOperatorValue().compare(\"down\") == 0)\n {\n numberPos = std::pair(blankPos.first + 1, blankPos.second);\n }\n else if (((EightPuzzleOperator*)op)->getOperatorValue().compare(\"left\") == 0)\n {\n numberPos = std::pair(blankPos.first, blankPos.second - 1);\n }\n else if (((EightPuzzleOperator*)op)->getOperatorValue().compare(\"right\") == 0)\n {\n numberPos = std::pair(blankPos.first, blankPos.second + 1);\n }\n\n std::string letter1 = \"\";\n std::string letter2 = \"\";\n\n letter1 += ((EightPuzzleId*)getId())->getIdValue().at(numberPos.first * 3 + numberPos.second);\n letter2 += ((EightPuzzleId*)getId())->getIdValue().at(blankPos.first * 3 + blankPos.second);\n\n newId.replace(blankPos.first * 3 + blankPos.second, 1, letter1.c_str());\n newId.replace(numberPos.first * 3 + numberPos.second, 1, letter2.c_str());\n\n return new EightPuzzleId(newId);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/utility\/source\/process_thread_impl.h\"\n\n#include \"webrtc\/base\/checks.h\"\n#include \"webrtc\/modules\/interface\/module.h\"\n#include \"webrtc\/system_wrappers\/interface\/logging.h\"\n#include \"webrtc\/system_wrappers\/interface\/tick_util.h\"\n\nnamespace webrtc {\nnamespace {\n\n\/\/ We use this constant internally to signal that a module has requested\n\/\/ a callback right away. When this is set, no call to TimeUntilNextProcess\n\/\/ should be made, but Process() should be called directly.\nconst int64_t kCallProcessImmediately = -1;\n\nint64_t GetNextCallbackTime(Module* module, int64_t time_now) {\n int64_t interval = module->TimeUntilNextProcess();\n \/\/ Currently some implementations erroneously return error codes from\n \/\/ TimeUntilNextProcess(). So, as is, we correct that and log an error.\n if (interval < 0) {\n LOG(LS_ERROR) << \"TimeUntilNextProcess returned an invalid value \"\n << interval;\n interval = 0;\n }\n return time_now + interval;\n}\n}\n\nProcessThread::~ProcessThread() {}\n\n\/\/ static\nrtc::scoped_ptr ProcessThread::Create() {\n return rtc::scoped_ptr(new ProcessThreadImpl()).Pass();\n}\n\nProcessThreadImpl::ProcessThreadImpl()\n : wake_up_(EventWrapper::Create()), stop_(false) {\n}\n\nProcessThreadImpl::~ProcessThreadImpl() {\n DCHECK(thread_checker_.CalledOnValidThread());\n DCHECK(!thread_.get());\n DCHECK(!stop_);\n\n while (!queue_.empty()) {\n delete queue_.front();\n queue_.pop();\n }\n}\n\nvoid ProcessThreadImpl::Start() {\n DCHECK(thread_checker_.CalledOnValidThread());\n DCHECK(!thread_.get());\n if (thread_.get())\n return;\n\n DCHECK(!stop_);\n\n for (ModuleCallback& m : modules_)\n m.module->ProcessThreadAttached(this);\n\n thread_ = ThreadWrapper::CreateThread(\n &ProcessThreadImpl::Run, this, \"ProcessThread\");\n CHECK(thread_->Start());\n}\n\nvoid ProcessThreadImpl::Stop() {\n DCHECK(thread_checker_.CalledOnValidThread());\n if(!thread_.get())\n return;\n\n {\n rtc::CritScope lock(&lock_);\n stop_ = true;\n }\n\n wake_up_->Set();\n\n CHECK(thread_->Stop());\n thread_.reset();\n stop_ = false;\n\n for (ModuleCallback& m : modules_)\n m.module->ProcessThreadAttached(nullptr);\n}\n\nvoid ProcessThreadImpl::WakeUp(Module* module) {\n \/\/ Allowed to be called on any thread.\n {\n rtc::CritScope lock(&lock_);\n for (ModuleCallback& m : modules_) {\n if (m.module == module)\n m.next_callback = kCallProcessImmediately;\n }\n }\n wake_up_->Set();\n}\n\nvoid ProcessThreadImpl::PostTask(rtc::scoped_ptr task) {\n \/\/ Allowed to be called on any thread.\n {\n rtc::CritScope lock(&lock_);\n queue_.push(task.release());\n }\n wake_up_->Set();\n}\n\nvoid ProcessThreadImpl::RegisterModule(Module* module) {\n \/\/ Allowed to be called on any thread.\n DCHECK(module);\n\n#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))\n {\n \/\/ Catch programmer error.\n rtc::CritScope lock(&lock_);\n for (const ModuleCallback& mc : modules_)\n DCHECK(mc.module != module);\n }\n#endif\n\n \/\/ Now that we know the module isn't in the list, we'll call out to notify\n \/\/ the module that it's attached to the worker thread. We don't hold\n \/\/ the lock while we make this call.\n if (thread_.get())\n module->ProcessThreadAttached(this);\n\n {\n rtc::CritScope lock(&lock_);\n modules_.push_back(ModuleCallback(module));\n }\n\n \/\/ Wake the thread calling ProcessThreadImpl::Process() to update the\n \/\/ waiting time. The waiting time for the just registered module may be\n \/\/ shorter than all other registered modules.\n wake_up_->Set();\n}\n\nvoid ProcessThreadImpl::DeRegisterModule(Module* module) {\n \/\/ Allowed to be called on any thread.\n DCHECK(module);\n {\n rtc::CritScope lock(&lock_);\n modules_.remove_if([&module](const ModuleCallback& m) {\n return m.module == module;\n });\n }\n\n \/\/ Notify the module that it's been detached, while not holding the lock.\n if (thread_.get())\n module->ProcessThreadAttached(nullptr);\n}\n\n\/\/ static\nbool ProcessThreadImpl::Run(void* obj) {\n return static_cast(obj)->Process();\n}\n\nbool ProcessThreadImpl::Process() {\n int64_t now = TickTime::MillisecondTimestamp();\n int64_t next_checkpoint = now + (1000 * 60);\n\n {\n rtc::CritScope lock(&lock_);\n if (stop_)\n return false;\n for (ModuleCallback& m : modules_) {\n \/\/ TODO(tommi): Would be good to measure the time TimeUntilNextProcess\n \/\/ takes and dcheck if it takes too long (e.g. >=10ms). Ideally this\n \/\/ operation should not require taking a lock, so querying all modules\n \/\/ should run in a matter of nanoseconds.\n if (m.next_callback == 0)\n m.next_callback = GetNextCallbackTime(m.module, now);\n\n if (m.next_callback <= now ||\n m.next_callback == kCallProcessImmediately) {\n m.module->Process();\n \/\/ Use a new 'now' reference to calculate when the next callback\n \/\/ should occur. We'll continue to use 'now' above for the baseline\n \/\/ of calculating how long we should wait, to reduce variance.\n int64_t new_now = TickTime::MillisecondTimestamp();\n m.next_callback = GetNextCallbackTime(m.module, new_now);\n }\n\n if (m.next_callback < next_checkpoint)\n next_checkpoint = m.next_callback;\n }\n\n while (!queue_.empty()) {\n ProcessTask* task = queue_.front();\n queue_.pop();\n lock_.Leave();\n task->Run();\n delete task;\n lock_.Enter();\n }\n }\n\n int64_t time_to_wait = next_checkpoint - TickTime::MillisecondTimestamp();\n if (time_to_wait > 0)\n wake_up_->Wait(static_cast(time_to_wait));\n\n return true;\n}\n} \/\/ namespace webrtc\nAdd locks to Start(), Stop() methods in ProcessThread. This is necessary unfortunately since there are a few places where DeRegisterModule does not reliably occur on the same thread.\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/utility\/source\/process_thread_impl.h\"\n\n#include \"webrtc\/base\/checks.h\"\n#include \"webrtc\/modules\/interface\/module.h\"\n#include \"webrtc\/system_wrappers\/interface\/logging.h\"\n#include \"webrtc\/system_wrappers\/interface\/tick_util.h\"\n\nnamespace webrtc {\nnamespace {\n\n\/\/ We use this constant internally to signal that a module has requested\n\/\/ a callback right away. When this is set, no call to TimeUntilNextProcess\n\/\/ should be made, but Process() should be called directly.\nconst int64_t kCallProcessImmediately = -1;\n\nint64_t GetNextCallbackTime(Module* module, int64_t time_now) {\n int64_t interval = module->TimeUntilNextProcess();\n \/\/ Currently some implementations erroneously return error codes from\n \/\/ TimeUntilNextProcess(). So, as is, we correct that and log an error.\n if (interval < 0) {\n LOG(LS_ERROR) << \"TimeUntilNextProcess returned an invalid value \"\n << interval;\n interval = 0;\n }\n return time_now + interval;\n}\n}\n\nProcessThread::~ProcessThread() {}\n\n\/\/ static\nrtc::scoped_ptr ProcessThread::Create() {\n return rtc::scoped_ptr(new ProcessThreadImpl()).Pass();\n}\n\nProcessThreadImpl::ProcessThreadImpl()\n : wake_up_(EventWrapper::Create()), stop_(false) {\n}\n\nProcessThreadImpl::~ProcessThreadImpl() {\n DCHECK(thread_checker_.CalledOnValidThread());\n DCHECK(!thread_.get());\n DCHECK(!stop_);\n\n while (!queue_.empty()) {\n delete queue_.front();\n queue_.pop();\n }\n}\n\nvoid ProcessThreadImpl::Start() {\n DCHECK(thread_checker_.CalledOnValidThread());\n DCHECK(!thread_.get());\n if (thread_.get())\n return;\n\n DCHECK(!stop_);\n\n {\n \/\/ TODO(tommi): Since DeRegisterModule is currently being called from\n \/\/ different threads in some cases (ChannelOwner), we need to lock access to\n \/\/ the modules_ collection even on the controller thread.\n \/\/ Once we've cleaned up those places, we can remove this lock.\n rtc::CritScope lock(&lock_);\n for (ModuleCallback& m : modules_)\n m.module->ProcessThreadAttached(this);\n }\n\n thread_ = ThreadWrapper::CreateThread(\n &ProcessThreadImpl::Run, this, \"ProcessThread\");\n CHECK(thread_->Start());\n}\n\nvoid ProcessThreadImpl::Stop() {\n DCHECK(thread_checker_.CalledOnValidThread());\n if(!thread_.get())\n return;\n\n {\n rtc::CritScope lock(&lock_);\n stop_ = true;\n }\n\n wake_up_->Set();\n\n CHECK(thread_->Stop());\n thread_.reset();\n stop_ = false;\n\n \/\/ TODO(tommi): Since DeRegisterModule is currently being called from\n \/\/ different threads in some cases (ChannelOwner), we need to lock access to\n \/\/ the modules_ collection even on the controller thread.\n \/\/ Once we've cleaned up those places, we can remove this lock.\n rtc::CritScope lock(&lock_);\n for (ModuleCallback& m : modules_)\n m.module->ProcessThreadAttached(nullptr);\n}\n\nvoid ProcessThreadImpl::WakeUp(Module* module) {\n \/\/ Allowed to be called on any thread.\n \/\/ TODO(tommi): Disallow this ^^^\n {\n rtc::CritScope lock(&lock_);\n for (ModuleCallback& m : modules_) {\n if (m.module == module)\n m.next_callback = kCallProcessImmediately;\n }\n }\n wake_up_->Set();\n}\n\nvoid ProcessThreadImpl::PostTask(rtc::scoped_ptr task) {\n \/\/ Allowed to be called on any thread.\n \/\/ TODO(tommi): Disallow this ^^^\n {\n rtc::CritScope lock(&lock_);\n queue_.push(task.release());\n }\n wake_up_->Set();\n}\n\nvoid ProcessThreadImpl::RegisterModule(Module* module) {\n \/\/ Allowed to be called on any thread.\n DCHECK(module);\n\n#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))\n {\n \/\/ Catch programmer error.\n rtc::CritScope lock(&lock_);\n for (const ModuleCallback& mc : modules_)\n DCHECK(mc.module != module);\n }\n#endif\n\n \/\/ Now that we know the module isn't in the list, we'll call out to notify\n \/\/ the module that it's attached to the worker thread. We don't hold\n \/\/ the lock while we make this call.\n if (thread_.get())\n module->ProcessThreadAttached(this);\n\n {\n rtc::CritScope lock(&lock_);\n modules_.push_back(ModuleCallback(module));\n }\n\n \/\/ Wake the thread calling ProcessThreadImpl::Process() to update the\n \/\/ waiting time. The waiting time for the just registered module may be\n \/\/ shorter than all other registered modules.\n wake_up_->Set();\n}\n\nvoid ProcessThreadImpl::DeRegisterModule(Module* module) {\n \/\/ Allowed to be called on any thread.\n DCHECK(module);\n {\n rtc::CritScope lock(&lock_);\n modules_.remove_if([&module](const ModuleCallback& m) {\n return m.module == module;\n });\n }\n\n \/\/ Notify the module that it's been detached, while not holding the lock.\n if (thread_.get())\n module->ProcessThreadAttached(nullptr);\n}\n\n\/\/ static\nbool ProcessThreadImpl::Run(void* obj) {\n return static_cast(obj)->Process();\n}\n\nbool ProcessThreadImpl::Process() {\n int64_t now = TickTime::MillisecondTimestamp();\n int64_t next_checkpoint = now + (1000 * 60);\n\n {\n rtc::CritScope lock(&lock_);\n if (stop_)\n return false;\n for (ModuleCallback& m : modules_) {\n \/\/ TODO(tommi): Would be good to measure the time TimeUntilNextProcess\n \/\/ takes and dcheck if it takes too long (e.g. >=10ms). Ideally this\n \/\/ operation should not require taking a lock, so querying all modules\n \/\/ should run in a matter of nanoseconds.\n if (m.next_callback == 0)\n m.next_callback = GetNextCallbackTime(m.module, now);\n\n if (m.next_callback <= now ||\n m.next_callback == kCallProcessImmediately) {\n m.module->Process();\n \/\/ Use a new 'now' reference to calculate when the next callback\n \/\/ should occur. We'll continue to use 'now' above for the baseline\n \/\/ of calculating how long we should wait, to reduce variance.\n int64_t new_now = TickTime::MillisecondTimestamp();\n m.next_callback = GetNextCallbackTime(m.module, new_now);\n }\n\n if (m.next_callback < next_checkpoint)\n next_checkpoint = m.next_callback;\n }\n\n while (!queue_.empty()) {\n ProcessTask* task = queue_.front();\n queue_.pop();\n lock_.Leave();\n task->Run();\n delete task;\n lock_.Enter();\n }\n }\n\n int64_t time_to_wait = next_checkpoint - TickTime::MillisecondTimestamp();\n if (time_to_wait > 0)\n wake_up_->Wait(static_cast(time_to_wait));\n\n return true;\n}\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"ENH: Fixed coverity 107502<|endoftext|>"} {"text":"#include \"blackhole\/sink\/asynchronous.hpp\"\n\n#include \n\n#include \"blackhole\/config\/node.hpp\"\n#include \"blackhole\/config\/option.hpp\"\n#include \"blackhole\/registry.hpp\"\n\n#include \"blackhole\/detail\/sink\/asynchronous.hpp\"\n\n#include \n\nnamespace blackhole {\ninline namespace v1 {\nnamespace experimental {\nnamespace sink {\nnamespace {\n\nstatic auto exp2(std::size_t factor) -> std::size_t {\n if (factor > 20) {\n throw std::invalid_argument(\"factor should fit in [0; 20] range\");\n }\n\n return static_cast(std::exp2(factor));\n}\n\n} \/\/ namespace\n\nclass drop_overflow_policy_t : public overflow_policy_t {\n typedef overflow_policy_t::action_t action_t;\n\npublic:\n \/\/\/ Drops on overlow.\n virtual auto overflow() -> action_t {\n return action_t::drop;\n }\n\n \/\/\/ Does nothing on wakeup.\n virtual auto wakeup() -> void {}\n};\n\nclass wait_overflow_policy_t : public overflow_policy_t {\n typedef overflow_policy_t::action_t action_t;\n\n mutable std::mutex mutex;\n std::condition_variable cv;\n\npublic:\n virtual auto overflow() -> action_t {\n std::unique_lock lock(mutex);\n cv.wait(lock);\n return action_t::retry;\n }\n\n virtual auto wakeup() -> void {\n cv.notify_one();\n }\n};\n\nasynchronous_t::asynchronous_t(std::unique_ptr wrapped, std::size_t factor) :\n queue(exp2(factor)),\n stopped(false),\n wrapped(std::move(wrapped)),\n overflow_policy(new wait_overflow_policy_t),\n thread(std::bind(&asynchronous_t::run, this))\n{}\n\nasynchronous_t::~asynchronous_t() {\n stopped.store(true);\n thread.join();\n}\n\nauto asynchronous_t::emit(const record_t& record, const string_view& message) -> void {\n if (stopped) {\n throw std::logic_error(\"queue is sealed\");\n }\n\n while (true) {\n const auto enqueued = queue.enqueue_with([&](value_type& value) {\n value = {recordbuf_t(record), message.to_string()};\n });\n\n if (enqueued) {\n \/\/ TODO: underflow_policy->wakeup();\n return;\n } else {\n switch (overflow_policy->overflow()) {\n case overflow_policy_t::action_t::retry:\n continue;\n case overflow_policy_t::action_t::drop:\n return;\n }\n }\n }\n}\n\nauto asynchronous_t::run() -> void {\n while (true) {\n value_type result;\n const auto dequeued = queue.dequeue_with([&](value_type& value) {\n result = std::move(value);\n });\n\n if (dequeued) {\n try {\n wrapped->emit(result.record.into_view(), result.message);\n overflow_policy->wakeup();\n } catch (...) {\n \/\/ TODO: exception_policy->process(std::current_exception()); []\n }\n\n } else {\n ::usleep(1000);\n \/\/ TODO: underflow_policy->underflow(); [wait for enqueue, sleep].\n }\n\n if (stopped && !dequeued) {\n return;\n }\n }\n}\n\n} \/\/ namespace sink\n\nauto factory::type() const noexcept -> const char* {\n return \"asynchronous\";\n}\n\nauto factory::from(const config::node_t& config) const -> std::unique_ptr {\n auto factory = registry.sink(*config[\"sink\"][\"type\"].to_string());\n return std::unique_ptr(new sink::asynchronous_t(factory(*config[\"sink\"].unwrap())));\n}\n\n} \/\/ namespace experimental\n} \/\/ namespace v1\n} \/\/ namespace blackhole\nfix: proper break logic#include \"blackhole\/sink\/asynchronous.hpp\"\n\n#include \n\n#include \"blackhole\/config\/node.hpp\"\n#include \"blackhole\/config\/option.hpp\"\n#include \"blackhole\/registry.hpp\"\n\n#include \"blackhole\/detail\/sink\/asynchronous.hpp\"\n\n#include \n\nnamespace blackhole {\ninline namespace v1 {\nnamespace experimental {\nnamespace sink {\nnamespace {\n\nstatic auto exp2(std::size_t factor) -> std::size_t {\n if (factor > 20) {\n throw std::invalid_argument(\"factor should fit in [0; 20] range\");\n }\n\n return static_cast(std::exp2(factor));\n}\n\n} \/\/ namespace\n\nclass drop_overflow_policy_t : public overflow_policy_t {\n typedef overflow_policy_t::action_t action_t;\n\npublic:\n \/\/\/ Drops on overlow.\n virtual auto overflow() -> action_t {\n return action_t::drop;\n }\n\n \/\/\/ Does nothing on wakeup.\n virtual auto wakeup() -> void {}\n};\n\nclass wait_overflow_policy_t : public overflow_policy_t {\n typedef overflow_policy_t::action_t action_t;\n\n mutable std::mutex mutex;\n std::condition_variable cv;\n\npublic:\n virtual auto overflow() -> action_t {\n std::unique_lock lock(mutex);\n cv.wait(lock);\n return action_t::retry;\n }\n\n virtual auto wakeup() -> void {\n cv.notify_one();\n }\n};\n\nasynchronous_t::asynchronous_t(std::unique_ptr wrapped, std::size_t factor) :\n queue(exp2(factor)),\n stopped(false),\n wrapped(std::move(wrapped)),\n overflow_policy(new drop_overflow_policy_t),\n thread(std::bind(&asynchronous_t::run, this))\n{}\n\nasynchronous_t::~asynchronous_t() {\n stopped.store(true);\n thread.join();\n}\n\nauto asynchronous_t::emit(const record_t& record, const string_view& message) -> void {\n if (stopped) {\n throw std::logic_error(\"queue is sealed\");\n }\n\n while (true) {\n const auto enqueued = queue.enqueue_with([&](value_type& value) {\n value = {recordbuf_t(record), message.to_string()};\n });\n\n if (enqueued) {\n \/\/ TODO: underflow_policy->wakeup();\n return;\n } else {\n switch (overflow_policy->overflow()) {\n case overflow_policy_t::action_t::retry:\n continue;\n case overflow_policy_t::action_t::drop:\n return;\n }\n }\n }\n}\n\nauto asynchronous_t::run() -> void {\n while (true) {\n value_type result;\n const auto dequeued = queue.dequeue_with([&](value_type& value) {\n result = std::move(value);\n });\n\n if (stopped && !dequeued) {\n return;\n }\n\n if (dequeued) {\n try {\n wrapped->emit(result.record.into_view(), result.message);\n overflow_policy->wakeup();\n } catch (...) {\n throw;\n \/\/ TODO: exception_policy->process(std::current_exception()); []\n }\n\n } else {\n ::usleep(1000);\n \/\/ TODO: underflow_policy->underflow(); [wait for enqueue, sleep].\n }\n }\n}\n\n} \/\/ namespace sink\n\nauto factory::type() const noexcept -> const char* {\n return \"asynchronous\";\n}\n\nauto factory::from(const config::node_t& config) const -> std::unique_ptr {\n auto factory = registry.sink(*config[\"sink\"][\"type\"].to_string());\n return std::unique_ptr(new sink::asynchronous_t(factory(*config[\"sink\"].unwrap())));\n}\n\n} \/\/ namespace experimental\n} \/\/ namespace v1\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"\/******************************************************************************\n * This file is part of the Mula project\n * Copyright (c) 2011 Laszlo Papp \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"indexfile.h\"\n\n#include \"file.h\"\n#include \"wordentry.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace MulaPluginStarDict;\n\nclass IndexFile::Private\n{\n public:\n Private()\n {\n }\n\n ~Private()\n {\n }\n\n QList wordEntryList;\n};\n\nIndexFile::IndexFile()\n : d(new Private)\n{\n}\n\nIndexFile::~IndexFile()\n{\n}\n\nbool\nIndexFile::load(const QString& filePath, qulonglong fileSize)\n{\n QFile file(filePath);\n if (!file.open(QIODevice::ReadOnly))\n {\n qDebug() << Q_FUNC_INFO << \"Failed to open file:\" << filePath;\n return false;\n }\n\n QByteArray indexDataBuffer = file.read(fileSize);\n\n file.close();\n\n qulonglong position = 0;\n d->wordEntryList.clear();\n while (fileSize > position)\n {\n WordEntry wordEntry;\n wordEntry.setData(indexDataBuffer.mid(position));\n ++position;\n wordEntry.setDataOffset(qFromBigEndian(*reinterpret_cast(indexDataBuffer.mid(position).data())));\n position += sizeof(quint32);\n wordEntry.setDataSize(qFromBigEndian(*reinterpret_cast(indexDataBuffer.mid(position).data())));\n position += sizeof(quint32);\n\n d->wordEntryList.append(wordEntry);\n }\n\n return true;\n}\n\nQByteArray\nIndexFile::key(long index)\n{\n return d->wordEntryList.at(index).data();\n}\n\ninline bool\nlessThanCompare(const QString string1, const QString string2)\n{\n return stardictStringCompare(string1, string2) < 0;\n}\n\nbool\nIndexFile::lookup(const QByteArray &word, int &index)\n{\n bool found = false;\n QStringList wordList;\n foreach (const WordEntry &wordEntry, d->wordEntryList)\n wordList.append(QString::fromUtf8(wordEntry.data()));\n\n QStringList::iterator i = qBinaryFind(wordList.begin(), wordList.end(), QString::fromUtf8(word), lessThanCompare);\n\n if (i == wordList.end())\n {\n index = -1;\n }\n else\n {\n index = i - wordList.begin();\n found = true;\n }\n\n return found;\n}\nCache the value of the 32 bits\/******************************************************************************\n * This file is part of the Mula project\n * Copyright (c) 2011 Laszlo Papp \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"indexfile.h\"\n\n#include \"file.h\"\n#include \"wordentry.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace MulaPluginStarDict;\n\nclass IndexFile::Private\n{\n public:\n Private()\n {\n }\n\n ~Private()\n {\n }\n\n QList wordEntryList;\n};\n\nIndexFile::IndexFile()\n : d(new Private)\n{\n}\n\nIndexFile::~IndexFile()\n{\n}\n\nbool\nIndexFile::load(const QString& filePath, qulonglong fileSize)\n{\n QFile file(filePath);\n if (!file.open(QIODevice::ReadOnly))\n {\n qDebug() << Q_FUNC_INFO << \"Failed to open file:\" << filePath;\n return false;\n }\n\n QByteArray indexDataBuffer = file.read(fileSize);\n\n file.close();\n\n qulonglong position = 0;\n d->wordEntryList.clear();\n int squint32 = sizeof(quint32);\n\n while (fileSize > position)\n {\n WordEntry wordEntry;\n wordEntry.setData(indexDataBuffer.mid(position));\n ++position;\n wordEntry.setDataOffset(qFromBigEndian(*reinterpret_cast(indexDataBuffer.mid(position).data())));\n position += squint32;\n wordEntry.setDataSize(qFromBigEndian(*reinterpret_cast(indexDataBuffer.mid(position).data())));\n position += squint32;\n\n d->wordEntryList.append(wordEntry);\n }\n\n return true;\n}\n\nQByteArray\nIndexFile::key(long index)\n{\n return d->wordEntryList.at(index).data();\n}\n\ninline bool\nlessThanCompare(const QString string1, const QString string2)\n{\n return stardictStringCompare(string1, string2) < 0;\n}\n\nbool\nIndexFile::lookup(const QByteArray &word, int &index)\n{\n bool found = false;\n QStringList wordList;\n foreach (const WordEntry &wordEntry, d->wordEntryList)\n wordList.append(QString::fromUtf8(wordEntry.data()));\n\n QStringList::iterator i = qBinaryFind(wordList.begin(), wordList.end(), QString::fromUtf8(word), lessThanCompare);\n\n if (i == wordList.end())\n {\n index = -1;\n }\n else\n {\n index = i - wordList.begin();\n found = true;\n }\n\n return found;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2008-2018 SLIBIO \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\n#include \"slib\/ui\/check_box.h\"\n\n#include \"slib\/ui\/core.h\"\n#include \"slib\/ui\/resource.h\"\n#include \"slib\/core\/safe_static.h\"\n\nnamespace slib\n{\n\n\tclass _priv_CheckBox_Icon : public Drawable\n\t{\n\tpublic:\n\t\tRef m_penBorder;\n\t\tRef m_brush;\n\t\tRef m_penCheck;\n\t\t\n\tpublic:\n\t\t_priv_CheckBox_Icon(const Ref& penBorder, const Color& backColor, const Ref& penCheck)\n\t\t{\n\t\t\tm_penBorder = penBorder;\n\t\t\tif (backColor.a > 0) {\n\t\t\t\tm_brush = Brush::createSolidBrush(backColor);\n\t\t\t}\n\t\t\tm_penCheck = penCheck;\n\t\t}\n\t\t\n\tpublic:\n\t\tvoid onDrawAll(Canvas* canvas, const Rectangle& rect, const DrawParam& param) override\n\t\t{\n\t\t\tsl_bool flagAntiAlias = canvas->isAntiAlias();\n\t\t\tcanvas->setAntiAlias(sl_false);\n\t\t\tcanvas->drawRectangle(rect, m_penBorder, m_brush);\n\t\t\tcanvas->setAntiAlias(flagAntiAlias);\n\t\t\t\n\t\t\tif (m_penCheck.isNotNull()) {\n\t\t\t\tPoint pts[3];\n\t\t\t\tpts[0] = Point(0.2f, 0.6f);\n\t\t\t\tpts[1] = Point(0.4f, 0.8f);\n\t\t\t\tpts[2] = Point(0.8f, 0.3f);\n\t\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\t\tpts[i].x = rect.left + rect.getWidth() * pts[i].x;\n\t\t\t\t\tpts[i].y = rect.top + rect.getHeight() * pts[i].y;\n\t\t\t\t}\n\t\t\t\tcanvas->drawLines(pts, 3, m_penCheck);\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\n\tclass _priv_CheckBox_Categories\n\t{\n\tpublic:\n\t\tButtonCategory categories[2];\n\t\t\n\tpublic:\n\t\t_priv_CheckBox_Categories()\n\t\t{\n\t\t\tsl_real w = (sl_real)(UIResource::toUiPos(UIResource::dpToPixel(1)));\n\t\t\tColor colorBackNormal = Color::White;\n\t\t\tColor colorBackHover = Color::White;\n\t\t\tColor colorBackDown(220, 230, 255);\n\t\t\tColor colorBackDisabled(220, 220, 220);\n\t\t\tRef penNormal = Pen::createSolidPen(w, Color::Black);\n\t\t\tRef penHover = Pen::createSolidPen(w, Color(0, 80, 200));\n\t\t\tRef penDown = penHover;\n\t\t\tRef penDisabled = Pen::createSolidPen(w, Color(90, 90, 90));\n\t\t\tRef penCheckNormal = Pen::createSolidPen(w*2, Color::Black);\n\t\t\tRef penCheckHover = Pen::createSolidPen(w*2, Color(0, 80, 200));\n\t\t\tRef penCheckDown = penCheckHover;\n\t\t\tRef penCheckDisabled = Pen::createSolidPen(w*2, Color(90, 90, 90));\n\t\t\tcategories[0].properties[(int)ButtonState::Normal].icon = new _priv_CheckBox_Icon(penNormal, colorBackNormal, Ref::null());\n\t\t\tcategories[0].properties[(int)ButtonState::Disabled].icon = new _priv_CheckBox_Icon(penDisabled, colorBackDisabled, Ref::null());\n\t\t\tcategories[0].properties[(int)ButtonState::Hover].icon = new _priv_CheckBox_Icon(penHover, colorBackHover, Ref::null());\n\t\t\tcategories[0].properties[(int)ButtonState::Pressed].icon = new _priv_CheckBox_Icon(penDown, colorBackDown, Ref::null());\n\t\t\t\n\t\t\tcategories[1] = categories[0];\n\t\t\tcategories[1].properties[(int)ButtonState::Normal].icon = new _priv_CheckBox_Icon(penNormal, colorBackNormal, penCheckNormal);\n\t\t\tcategories[1].properties[(int)ButtonState::Disabled].icon = new _priv_CheckBox_Icon(penDisabled, colorBackDisabled, penCheckDisabled);\n\t\t\tcategories[1].properties[(int)ButtonState::Hover].icon = new _priv_CheckBox_Icon(penHover, colorBackHover, penCheckHover);\n\t\t\tcategories[1].properties[(int)ButtonState::Pressed].icon = new _priv_CheckBox_Icon(penDown, colorBackDown, penCheckDown);\n\t\t}\n\t\t\n\tpublic:\n\t\tstatic ButtonCategory* getCategories()\n\t\t{\n\t\t\tSLIB_SAFE_STATIC(_priv_CheckBox_Categories, ret)\n\t\t\tif (SLIB_SAFE_STATIC_CHECK_FREED(ret)) {\n\t\t\t\treturn sl_null;\n\t\t\t}\n\t\t\treturn ret.categories;\n\t\t}\n\t};\n\n\tSLIB_DEFINE_OBJECT(CheckBox, Button)\n\n\tCheckBox::CheckBox() : CheckBox(2, _priv_CheckBox_Categories::getCategories())\n\t{\n\t}\n\n\tCheckBox::CheckBox(sl_uint32 nCategories, ButtonCategory* categories) : Button(nCategories, categories)\n\t{\n\t\tsetCreatingNativeWidget(sl_false);\n\t\t\n\t\tm_flagChecked = sl_false;\n\t\t\n\t\tsetGravity(Alignment::MiddleLeft, UIUpdateMode::Init);\n\t\tsetIconAlignment(Alignment::MiddleLeft, UIUpdateMode::Init);\n\t\tsetTextAlignment(Alignment::MiddleLeft, UIUpdateMode::Init);\n\t\t\n\t\tsetBorder(sl_false, UIUpdateMode::Init);\n\t\tsetBackground(Ref::null(), UIUpdateMode::Init);\n\t\t\n\t\tsetTextColor(Color::Black, UIUpdateMode::Init);\n\t\tsetTextMarginLeft(2 * UIResource::toUiPos(UIResource::dpToPixel(1)), UIUpdateMode::Init);\n\t}\n\n\tCheckBox::~CheckBox()\n\t{\n\t}\n\n\tsl_bool CheckBox::isChecked()\n\t{\n\t\tif (isNativeWidget()) {\n\t\t\t_getChecked_NW();\n\t\t}\n\t\treturn m_flagChecked;\n\t}\n\n\tvoid CheckBox::setChecked(sl_bool flag, UIUpdateMode mode)\n\t{\n\t\tm_flagChecked = flag;\n\t\tif (isNativeWidget()) {\n\t\t\tsetCurrentCategory(flag ? 1 : 0, UIUpdateMode::None);\n\t\t\t_setChecked_NW(flag);\n\t\t} else {\n\t\t\tsetCurrentCategory(flag ? 1 : 0, mode);\n\t\t}\n\t}\n\t\n\tUISize _priv_CheckBox_macOS_measureSize(Button* view);\n\tUISize _priv_CheckBox_Win32_measureSize(Button* view);\n\n\tUISize CheckBox::measureLayoutContentSize()\n\t{\n#if defined(SLIB_PLATFORM_IS_MACOS)\n\t\tif (isCreatingNativeWidget()) {\n\t\t\treturn _priv_CheckBox_macOS_measureSize(this);\n\t\t}\n#endif\n#if defined(SLIB_PLATFORM_IS_WIN32)\n\t\tif (isCreatingNativeWidget()) {\n\t\t\treturn _priv_CheckBox_Win32_measureSize(this);\n\t\t}\n#endif\n\t\treturn measureContentSize();\n\t}\n\n\tvoid CheckBox::onClickEvent(UIEvent* ev)\n\t{\n\t\tif (isNativeWidget()) {\n\t\t\t_getChecked_NW();\n\t\t} else {\n\t\t\tsetChecked(!m_flagChecked);\n\t\t}\n\t}\n\n#if !defined(SLIB_UI_IS_MACOS) && !defined(SLIB_UI_IS_WIN32)\n\tRef CheckBox::createNativeWidget(ViewInstance* parent)\n\t{\n\t\treturn sl_null;\n\t}\n\n\tvoid CheckBox::_getChecked_NW()\n\t{\n\t}\n\n\tvoid CheckBox::_setChecked_NW(sl_bool flag)\n\t{\n\t}\n#endif\n\n}\n\nui\/CheckBox: adjust icon margin\/*\n * Copyright (c) 2008-2018 SLIBIO \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\n#include \"slib\/ui\/check_box.h\"\n\n#include \"slib\/ui\/core.h\"\n#include \"slib\/ui\/resource.h\"\n#include \"slib\/core\/safe_static.h\"\n\nnamespace slib\n{\n\n\tclass _priv_CheckBox_Icon : public Drawable\n\t{\n\tpublic:\n\t\tRef m_penBorder;\n\t\tRef m_brush;\n\t\tRef m_penCheck;\n\t\t\n\tpublic:\n\t\t_priv_CheckBox_Icon(const Ref& penBorder, const Color& backColor, const Ref& penCheck)\n\t\t{\n\t\t\tm_penBorder = penBorder;\n\t\t\tif (backColor.a > 0) {\n\t\t\t\tm_brush = Brush::createSolidBrush(backColor);\n\t\t\t}\n\t\t\tm_penCheck = penCheck;\n\t\t}\n\t\t\n\tpublic:\n\t\tvoid onDrawAll(Canvas* canvas, const Rectangle& rect, const DrawParam& param) override\n\t\t{\n\t\t\tsl_bool flagAntiAlias = canvas->isAntiAlias();\n\t\t\tcanvas->setAntiAlias(sl_false);\n\t\t\tcanvas->drawRectangle(rect, m_penBorder, m_brush);\n\t\t\tcanvas->setAntiAlias(flagAntiAlias);\n\t\t\t\n\t\t\tif (m_penCheck.isNotNull()) {\n\t\t\t\tPoint pts[3];\n\t\t\t\tpts[0] = Point(0.2f, 0.6f);\n\t\t\t\tpts[1] = Point(0.4f, 0.8f);\n\t\t\t\tpts[2] = Point(0.8f, 0.3f);\n\t\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\t\tpts[i].x = rect.left + rect.getWidth() * pts[i].x;\n\t\t\t\t\tpts[i].y = rect.top + rect.getHeight() * pts[i].y;\n\t\t\t\t}\n\t\t\t\tcanvas->drawLines(pts, 3, m_penCheck);\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\n\tclass _priv_CheckBox_Categories\n\t{\n\tpublic:\n\t\tButtonCategory categories[2];\n\t\t\n\tpublic:\n\t\t_priv_CheckBox_Categories()\n\t\t{\n\t\t\tsl_real w = (sl_real)(UIResource::toUiPos(UIResource::dpToPixel(1)));\n\t\t\tColor colorBackNormal = Color::White;\n\t\t\tColor colorBackHover = Color::White;\n\t\t\tColor colorBackDown(220, 230, 255);\n\t\t\tColor colorBackDisabled(220, 220, 220);\n\t\t\tRef penNormal = Pen::createSolidPen(w, Color::Black);\n\t\t\tRef penHover = Pen::createSolidPen(w, Color(0, 80, 200));\n\t\t\tRef penDown = penHover;\n\t\t\tRef penDisabled = Pen::createSolidPen(w, Color(90, 90, 90));\n\t\t\tRef penCheckNormal = Pen::createSolidPen(w*2, Color::Black);\n\t\t\tRef penCheckHover = Pen::createSolidPen(w*2, Color(0, 80, 200));\n\t\t\tRef penCheckDown = penCheckHover;\n\t\t\tRef penCheckDisabled = Pen::createSolidPen(w*2, Color(90, 90, 90));\n\t\t\tcategories[0].properties[(int)ButtonState::Normal].icon = new _priv_CheckBox_Icon(penNormal, colorBackNormal, Ref::null());\n\t\t\tcategories[0].properties[(int)ButtonState::Disabled].icon = new _priv_CheckBox_Icon(penDisabled, colorBackDisabled, Ref::null());\n\t\t\tcategories[0].properties[(int)ButtonState::Hover].icon = new _priv_CheckBox_Icon(penHover, colorBackHover, Ref::null());\n\t\t\tcategories[0].properties[(int)ButtonState::Pressed].icon = new _priv_CheckBox_Icon(penDown, colorBackDown, Ref::null());\n\t\t\t\n\t\t\tcategories[1] = categories[0];\n\t\t\tcategories[1].properties[(int)ButtonState::Normal].icon = new _priv_CheckBox_Icon(penNormal, colorBackNormal, penCheckNormal);\n\t\t\tcategories[1].properties[(int)ButtonState::Disabled].icon = new _priv_CheckBox_Icon(penDisabled, colorBackDisabled, penCheckDisabled);\n\t\t\tcategories[1].properties[(int)ButtonState::Hover].icon = new _priv_CheckBox_Icon(penHover, colorBackHover, penCheckHover);\n\t\t\tcategories[1].properties[(int)ButtonState::Pressed].icon = new _priv_CheckBox_Icon(penDown, colorBackDown, penCheckDown);\n\t\t}\n\t\t\n\tpublic:\n\t\tstatic ButtonCategory* getCategories()\n\t\t{\n\t\t\tSLIB_SAFE_STATIC(_priv_CheckBox_Categories, ret)\n\t\t\tif (SLIB_SAFE_STATIC_CHECK_FREED(ret)) {\n\t\t\t\treturn sl_null;\n\t\t\t}\n\t\t\treturn ret.categories;\n\t\t}\n\t};\n\n\tSLIB_DEFINE_OBJECT(CheckBox, Button)\n\n\tCheckBox::CheckBox() : CheckBox(2, _priv_CheckBox_Categories::getCategories())\n\t{\n\t}\n\n\tCheckBox::CheckBox(sl_uint32 nCategories, ButtonCategory* categories) : Button(nCategories, categories)\n\t{\n\t\tsetCreatingNativeWidget(sl_false);\n\t\t\n\t\tm_flagChecked = sl_false;\n\t\t\n\t\tsetGravity(Alignment::MiddleLeft, UIUpdateMode::Init);\n\t\tsetIconAlignment(Alignment::MiddleLeft, UIUpdateMode::Init);\n\t\tsetTextAlignment(Alignment::MiddleLeft, UIUpdateMode::Init);\n\t\t\n\t\tsetBorder(sl_false, UIUpdateMode::Init);\n\t\tsetBackground(Ref::null(), UIUpdateMode::Init);\n\t\t\n\t\tsetTextColor(Color::Black, UIUpdateMode::Init);\n\t\tsetTextMargin(2 * UIResource::toUiPos(UIResource::dpToPixel(1)), 1, 1, 2, UIUpdateMode::Init);\n\t\tsetIconMargin(1, 2, 1, 1, UIUpdateMode::Init);\n\t}\n\n\tCheckBox::~CheckBox()\n\t{\n\t}\n\n\tsl_bool CheckBox::isChecked()\n\t{\n\t\tif (isNativeWidget()) {\n\t\t\t_getChecked_NW();\n\t\t}\n\t\treturn m_flagChecked;\n\t}\n\n\tvoid CheckBox::setChecked(sl_bool flag, UIUpdateMode mode)\n\t{\n\t\tm_flagChecked = flag;\n\t\tif (isNativeWidget()) {\n\t\t\tsetCurrentCategory(flag ? 1 : 0, UIUpdateMode::None);\n\t\t\t_setChecked_NW(flag);\n\t\t} else {\n\t\t\tsetCurrentCategory(flag ? 1 : 0, mode);\n\t\t}\n\t}\n\t\n\tUISize _priv_CheckBox_macOS_measureSize(Button* view);\n\tUISize _priv_CheckBox_Win32_measureSize(Button* view);\n\n\tUISize CheckBox::measureLayoutContentSize()\n\t{\n#if defined(SLIB_PLATFORM_IS_MACOS)\n\t\tif (isCreatingNativeWidget()) {\n\t\t\treturn _priv_CheckBox_macOS_measureSize(this);\n\t\t}\n#endif\n#if defined(SLIB_PLATFORM_IS_WIN32)\n\t\tif (isCreatingNativeWidget()) {\n\t\t\treturn _priv_CheckBox_Win32_measureSize(this);\n\t\t}\n#endif\n\t\treturn measureContentSize();\n\t}\n\n\tvoid CheckBox::onClickEvent(UIEvent* ev)\n\t{\n\t\tif (isNativeWidget()) {\n\t\t\t_getChecked_NW();\n\t\t} else {\n\t\t\tsetChecked(!m_flagChecked);\n\t\t}\n\t}\n\n#if !defined(SLIB_UI_IS_MACOS) && !defined(SLIB_UI_IS_WIN32)\n\tRef CheckBox::createNativeWidget(ViewInstance* parent)\n\t{\n\t\treturn sl_null;\n\t}\n\n\tvoid CheckBox::_getChecked_NW()\n\t{\n\t}\n\n\tvoid CheckBox::_setChecked_NW(sl_bool flag)\n\t{\n\t}\n#endif\n\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/configuration_policy_provider.h\"\n\n#include \"base\/values.h\"\n\nnamespace {\n\n\/\/ TODO(avi): Use this mapping to auto-generate MCX manifests and Windows\n\/\/ ADM\/ADMX files. http:\/\/crbug.com\/49316\n\nstruct InternalPolicyValueMapEntry {\n ConfigurationPolicyStore::PolicyType policy_type;\n Value::ValueType value_type;\n const char* name;\n};\n\nconst InternalPolicyValueMapEntry kPolicyValueMap[] = {\n { ConfigurationPolicyStore::kPolicyHomePage,\n Value::TYPE_STRING, \"HomepageLocation\" },\n { ConfigurationPolicyStore::kPolicyHomepageIsNewTabPage,\n Value::TYPE_BOOLEAN, \"HomepageIsNewTabPage\" },\n { ConfigurationPolicyStore::kPolicyProxyServerMode,\n Value::TYPE_INTEGER, \"ProxyServerMode\" },\n { ConfigurationPolicyStore::kPolicyProxyServer,\n Value::TYPE_STRING, \"ProxyServer\" },\n { ConfigurationPolicyStore::kPolicyProxyPacUrl,\n Value::TYPE_STRING, \"ProxyPacUrl\" },\n { ConfigurationPolicyStore::kPolicyProxyBypassList,\n Value::TYPE_STRING, \"ProxyBypassList\" },\n { ConfigurationPolicyStore::kPolicyAlternateErrorPagesEnabled,\n Value::TYPE_BOOLEAN, \"AlternateErrorPagesEnabled\" },\n { ConfigurationPolicyStore::kPolicySearchSuggestEnabled,\n Value::TYPE_BOOLEAN, \"SearchSuggestEnabled\" },\n { ConfigurationPolicyStore::kPolicyDnsPrefetchingEnabled,\n Value::TYPE_BOOLEAN, \"DnsPrefetchingEnabled\" },\n { ConfigurationPolicyStore::kPolicySafeBrowsingEnabled,\n Value::TYPE_BOOLEAN, \"SafeBrowsingEnabled\" },\n { ConfigurationPolicyStore::kPolicyMetricsReportingEnabled,\n Value::TYPE_BOOLEAN, \"MetricsReportingEnabled\" },\n { ConfigurationPolicyStore::kPolicyPasswordManagerEnabled,\n Value::TYPE_BOOLEAN, \"PasswordManagerEnabled\" },\n { ConfigurationPolicyStore::kPolicyDisabledPlugins,\n Value::TYPE_STRING, \"DisabledPluginsList\" },\n { ConfigurationPolicyStore::kPolicyApplicationLocale,\r\n Value::TYPE_STRING, \"ApplicationLocaleValue\" },\n { ConfigurationPolicyStore::kPolicySyncDisabled,\n Value::TYPE_BOOLEAN, \"SyncDisabled\" },\n};\n\n} \/\/ namespace\n\n\/* static *\/\nconst ConfigurationPolicyProvider::PolicyValueMap*\n ConfigurationPolicyProvider::PolicyValueMapping() {\n static PolicyValueMap* mapping;\n if (!mapping) {\n mapping = new PolicyValueMap();\n for (size_t i = 0; i < arraysize(kPolicyValueMap); ++i) {\n const InternalPolicyValueMapEntry& internal_entry = kPolicyValueMap[i];\n PolicyValueMapEntry entry;\n entry.policy_type = internal_entry.policy_type;\n entry.value_type = internal_entry.value_type;\n entry.name = std::string(internal_entry.name);\n mapping->push_back(entry);\n }\n }\n return mapping;\n}\nFix wrong line ending.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/configuration_policy_provider.h\"\n\n#include \"base\/values.h\"\n\nnamespace {\n\n\/\/ TODO(avi): Use this mapping to auto-generate MCX manifests and Windows\n\/\/ ADM\/ADMX files. http:\/\/crbug.com\/49316\n\nstruct InternalPolicyValueMapEntry {\n ConfigurationPolicyStore::PolicyType policy_type;\n Value::ValueType value_type;\n const char* name;\n};\n\nconst InternalPolicyValueMapEntry kPolicyValueMap[] = {\n { ConfigurationPolicyStore::kPolicyHomePage,\n Value::TYPE_STRING, \"HomepageLocation\" },\n { ConfigurationPolicyStore::kPolicyHomepageIsNewTabPage,\n Value::TYPE_BOOLEAN, \"HomepageIsNewTabPage\" },\n { ConfigurationPolicyStore::kPolicyProxyServerMode,\n Value::TYPE_INTEGER, \"ProxyServerMode\" },\n { ConfigurationPolicyStore::kPolicyProxyServer,\n Value::TYPE_STRING, \"ProxyServer\" },\n { ConfigurationPolicyStore::kPolicyProxyPacUrl,\n Value::TYPE_STRING, \"ProxyPacUrl\" },\n { ConfigurationPolicyStore::kPolicyProxyBypassList,\n Value::TYPE_STRING, \"ProxyBypassList\" },\n { ConfigurationPolicyStore::kPolicyAlternateErrorPagesEnabled,\n Value::TYPE_BOOLEAN, \"AlternateErrorPagesEnabled\" },\n { ConfigurationPolicyStore::kPolicySearchSuggestEnabled,\n Value::TYPE_BOOLEAN, \"SearchSuggestEnabled\" },\n { ConfigurationPolicyStore::kPolicyDnsPrefetchingEnabled,\n Value::TYPE_BOOLEAN, \"DnsPrefetchingEnabled\" },\n { ConfigurationPolicyStore::kPolicySafeBrowsingEnabled,\n Value::TYPE_BOOLEAN, \"SafeBrowsingEnabled\" },\n { ConfigurationPolicyStore::kPolicyMetricsReportingEnabled,\n Value::TYPE_BOOLEAN, \"MetricsReportingEnabled\" },\n { ConfigurationPolicyStore::kPolicyPasswordManagerEnabled,\n Value::TYPE_BOOLEAN, \"PasswordManagerEnabled\" },\n { ConfigurationPolicyStore::kPolicyDisabledPlugins,\n Value::TYPE_STRING, \"DisabledPluginsList\" },\n { ConfigurationPolicyStore::kPolicyApplicationLocale,\n Value::TYPE_STRING, \"ApplicationLocaleValue\" },\n { ConfigurationPolicyStore::kPolicySyncDisabled,\n Value::TYPE_BOOLEAN, \"SyncDisabled\" },\n};\n\n} \/\/ namespace\n\n\/* static *\/\nconst ConfigurationPolicyProvider::PolicyValueMap*\n ConfigurationPolicyProvider::PolicyValueMapping() {\n static PolicyValueMap* mapping;\n if (!mapping) {\n mapping = new PolicyValueMap();\n for (size_t i = 0; i < arraysize(kPolicyValueMap); ++i) {\n const InternalPolicyValueMapEntry& internal_entry = kPolicyValueMap[i];\n PolicyValueMapEntry entry;\n entry.policy_type = internal_entry.policy_type;\n entry.value_type = internal_entry.value_type;\n entry.name = std::string(internal_entry.name);\n mapping->push_back(entry);\n }\n }\n return mapping;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace config;\n\nclass MyConfigRequest : public ConfigRequest\n{\npublic:\n MyConfigRequest(const ConfigKey & key)\n : _key(key)\n { }\n\n const ConfigKey & getKey() const override { return _key; }\n bool abort() override { return false; }\n bool isAborted() const override { return false; }\n void setError(int errorCode) override { (void) errorCode; }\n const ConfigKey _key;\n};\n\nclass MyConfigResponse : public ConfigResponse\n{\npublic:\n MyConfigResponse(const ConfigKey & key, const ConfigValue & value, bool isUpdated, bool valid,\n int64_t timestamp, const vespalib::string & md5, const std::string & errorMsg, int errorC0de, bool iserror)\n : _key(key),\n _value(value),\n _isUpdated(isUpdated),\n _fillCalled(false),\n _valid(valid),\n _state(md5, timestamp),\n _errorMessage(errorMsg),\n _errorCode(errorC0de),\n _isError(iserror)\n { }\n\n const ConfigKey& getKey() const override { return _key; }\n const ConfigValue & getValue() const override { return _value; }\n const ConfigState & getConfigState() const override { return _state; }\n bool hasValidResponse() const override { return _valid; }\n bool validateResponse() override { return _valid; }\n void fill() override { _fillCalled = true; }\n vespalib::string errorMessage() const override { return _errorMessage; }\n int errorCode() const override { return _errorCode; }\n bool isError() const override { return _isError; }\n const Trace & getTrace() const override { return _trace; }\n\n const ConfigKey _key;\n const ConfigValue _value;\n bool _isUpdated;\n bool _fillCalled;\n bool _valid;\n const ConfigState _state;\n vespalib::string _errorMessage;\n int _errorCode;\n bool _isError;\n Trace _trace;\n\n\n\/**\n MyConfigResponse(const ConfigKey & key, const ConfigValue & value, bool isUpdated, bool valid,\n int64_t timestamp, const vespalib::string & md5, int64_t prevTimestamp, const vespalib::string &prevMd5,\n const std::string & errorMsg, int errorC0de, bool iserror)\n*\/\n static ConfigResponse::UP createOKResponse(const ConfigKey & key, const ConfigValue & value)\n {\n return ConfigResponse::UP(new MyConfigResponse(key, value, true, true, 10, \"a\", \"\", 0, false));\n }\n\n static ConfigResponse::UP createServerErrorResponse(const ConfigKey & key, const ConfigValue & value)\n {\n return ConfigResponse::UP(new MyConfigResponse(key, value, false, true, 10, \"a\", \"whinewhine\", 2, true));\n }\n\n static ConfigResponse::UP createConfigErrorResponse(const ConfigKey & key, const ConfigValue & value)\n {\n return ConfigResponse::UP(new MyConfigResponse(key, value, false, false, 10, \"a\", \"\", 0, false));\n }\n};\n\nclass MyHolder : public IConfigHolder\n{\npublic:\n MyHolder()\n : _update()\n {\n }\n\n std::unique_ptr provide() override\n {\n return std::move(_update);\n }\n\n bool wait(uint64_t timeout) override\n {\n (void) timeout;\n return true;\n }\n\n void handle(std::unique_ptr update) override\n {\n _update = std::move(update);\n }\n\n bool poll() override { return true; }\n void interrupt() override { }\nprivate:\n std::unique_ptr _update;\n};\n\n\nConfigValue createValue(const std::string & myField, const std::string & md5)\n{\n std::vector< vespalib::string > lines;\n lines.push_back(\"myField \\\"\" + myField + \"\\\"\");\n return ConfigValue(lines, md5);\n}\n\nstatic TimingValues testTimingValues(\n 2000, \/\/ successTimeout\n 500, \/\/ errorTimeout\n 500, \/\/ initialTimeout\n 4000, \/\/ subscribeTimeout\n 0, \/\/ fixedDelay\n 250, \/\/ successDelay\n 250, \/\/ unconfiguredDelay\n 500, \/\/ configuredErrorDelay\n 5,\n 1000,\n 2000); \/\/ maxDelayMultiplier\n\nTEST(\"require that agent returns correct values\") {\n FRTConfigAgent handler(IConfigHolder::SP(new MyHolder()), testTimingValues);\n ASSERT_EQUAL(500u, handler.getTimeout());\n ASSERT_EQUAL(0u, handler.getWaitTime());\n ConfigState cs;\n ASSERT_EQUAL(cs.md5, handler.getConfigState().md5);\n ASSERT_EQUAL(cs.generation, handler.getConfigState().generation);\n}\n\nTEST(\"require that successful request is delivered to holder\") {\n const ConfigKey testKey(ConfigKey::create(\"mykey\"));\n const ConfigValue testValue(createValue(\"l33t\", \"a\"));\n IConfigHolder::SP latch(new MyHolder());\n\n FRTConfigAgent handler(latch, testTimingValues);\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createOKResponse(testKey, testValue));\n ASSERT_TRUE(latch->poll());\n ConfigUpdate::UP update(latch->provide());\n ASSERT_TRUE(update.get() != NULL);\n ASSERT_TRUE(update->hasChanged());\n MyConfig cfg(update->getValue());\n ASSERT_EQUAL(\"l33t\", cfg.myField);\n}\n\nTEST(\"require that successful request sets correct wait time\") {\n const ConfigKey testKey(ConfigKey::create(\"mykey\"));\n const ConfigValue testValue(createValue(\"l33t\", \"a\"));\n IConfigHolder::SP latch(new MyHolder());\n FRTConfigAgent handler(latch, testTimingValues);\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createOKResponse(testKey, testValue));\n ASSERT_EQUAL(250u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createOKResponse(testKey, testValue));\n ASSERT_EQUAL(250u, handler.getWaitTime());\n}\n\nTEST(\"require that bad config response returns false\") {\n const ConfigKey testKey(ConfigKey::create(\"mykey\"));\n const ConfigValue testValue(createValue(\"myval\", \"a\"));\n IConfigHolder::SP latch(new MyHolder());\n FRTConfigAgent handler(latch, testTimingValues);\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(250u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(500u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(750u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1000u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1250u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1250u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createOKResponse(testKey, testValue));\n ASSERT_EQUAL(250u, handler.getWaitTime());\n ASSERT_EQUAL(2000u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(500u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n}\n\nTEST(\"require that bad response returns false\") {\n const ConfigKey testKey(ConfigKey::create(\"mykey\"));\n std::vector lines;\n const ConfigValue testValue(lines, \"a\");\n\n IConfigHolder::SP latch(new MyHolder());\n FRTConfigAgent handler(latch, testTimingValues);\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(250u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(500u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(750u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1000u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1250u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1250u, handler.getWaitTime());\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\nAdd a test proving that we can loose a config change.\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace config;\n\nclass MyConfigRequest : public ConfigRequest\n{\npublic:\n MyConfigRequest(const ConfigKey & key)\n : _key(key)\n { }\n\n const ConfigKey & getKey() const override { return _key; }\n bool abort() override { return false; }\n bool isAborted() const override { return false; }\n void setError(int errorCode) override { (void) errorCode; }\n const ConfigKey _key;\n};\n\nclass MyConfigResponse : public ConfigResponse\n{\npublic:\n MyConfigResponse(const ConfigKey & key, const ConfigValue & value, bool valid, int64_t timestamp,\n const vespalib::string & md5, const std::string & errorMsg, int errorC0de, bool iserror)\n : _key(key),\n _value(value),\n _fillCalled(false),\n _valid(valid),\n _state(md5, timestamp),\n _errorMessage(errorMsg),\n _errorCode(errorC0de),\n _isError(iserror)\n { }\n\n const ConfigKey& getKey() const override { return _key; }\n const ConfigValue & getValue() const override { return _value; }\n const ConfigState & getConfigState() const override { return _state; }\n bool hasValidResponse() const override { return _valid; }\n bool validateResponse() override { return _valid; }\n void fill() override { _fillCalled = true; }\n vespalib::string errorMessage() const override { return _errorMessage; }\n int errorCode() const override { return _errorCode; }\n bool isError() const override { return _isError; }\n const Trace & getTrace() const override { return _trace; }\n\n const ConfigKey _key;\n const ConfigValue _value;\n bool _fillCalled;\n bool _valid;\n const ConfigState _state;\n vespalib::string _errorMessage;\n int _errorCode;\n bool _isError;\n Trace _trace;\n\n\n static ConfigResponse::UP createOKResponse(const ConfigKey & key, const ConfigValue & value, uint64_t timestamp = 10, const vespalib::string & md5 = \"a\")\n {\n return ConfigResponse::UP(new MyConfigResponse(key, value, true, timestamp, md5, \"\", 0, false));\n }\n\n static ConfigResponse::UP createServerErrorResponse(const ConfigKey & key, const ConfigValue & value)\n {\n return ConfigResponse::UP(new MyConfigResponse(key, value, true, 10, \"a\", \"whinewhine\", 2, true));\n }\n\n static ConfigResponse::UP createConfigErrorResponse(const ConfigKey & key, const ConfigValue & value)\n {\n return ConfigResponse::UP(new MyConfigResponse(key, value, false, 10, \"a\", \"\", 0, false));\n }\n};\n\nclass MyHolder : public IConfigHolder\n{\npublic:\n MyHolder()\n : _update()\n {\n }\n\n std::unique_ptr provide() override\n {\n return std::move(_update);\n }\n\n bool wait(uint64_t timeout) override\n {\n (void) timeout;\n return true;\n }\n\n void handle(std::unique_ptr update) override\n {\n _update = std::move(update);\n }\n\n bool poll() override { return true; }\n void interrupt() override { }\nprivate:\n std::unique_ptr _update;\n};\n\n\nConfigValue createValue(const std::string & myField, const std::string & md5)\n{\n std::vector< vespalib::string > lines;\n lines.push_back(\"myField \\\"\" + myField + \"\\\"\");\n return ConfigValue(lines, md5);\n}\n\nstatic TimingValues testTimingValues(\n 2000, \/\/ successTimeout\n 500, \/\/ errorTimeout\n 500, \/\/ initialTimeout\n 4000, \/\/ subscribeTimeout\n 0, \/\/ fixedDelay\n 250, \/\/ successDelay\n 250, \/\/ unconfiguredDelay\n 500, \/\/ configuredErrorDelay\n 5,\n 1000,\n 2000); \/\/ maxDelayMultiplier\n\nTEST(\"require that agent returns correct values\") {\n FRTConfigAgent handler(IConfigHolder::SP(new MyHolder()), testTimingValues);\n ASSERT_EQUAL(500u, handler.getTimeout());\n ASSERT_EQUAL(0u, handler.getWaitTime());\n ConfigState cs;\n ASSERT_EQUAL(cs.md5, handler.getConfigState().md5);\n ASSERT_EQUAL(cs.generation, handler.getConfigState().generation);\n}\n\nTEST(\"require that successful request is delivered to holder\") {\n const ConfigKey testKey(ConfigKey::create(\"mykey\"));\n const ConfigValue testValue(createValue(\"l33t\", \"a\"));\n IConfigHolder::SP latch(new MyHolder());\n\n FRTConfigAgent handler(latch, testTimingValues);\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createOKResponse(testKey, testValue));\n ASSERT_TRUE(latch->poll());\n ConfigUpdate::UP update(latch->provide());\n ASSERT_TRUE(update);\n ASSERT_TRUE(update->hasChanged());\n MyConfig cfg(update->getValue());\n ASSERT_EQUAL(\"l33t\", cfg.myField);\n}\n\nTEST(\"require that important(the change) request is delivered to holder even if it was not the last\") {\n const ConfigKey testKey(ConfigKey::create(\"mykey\"));\n const ConfigValue testValue1(createValue(\"l33t\", \"a\"));\n const ConfigValue testValue2(createValue(\"l34t\", \"b\"));\n IConfigHolder::SP latch(new MyHolder());\n\n FRTConfigAgent handler(latch, testTimingValues);\n handler.handleResponse(MyConfigRequest(testKey),\n MyConfigResponse::createOKResponse(testKey, testValue1, 1, testValue1.getMd5()));\n ASSERT_TRUE(latch->poll());\n ConfigUpdate::UP update(latch->provide());\n ASSERT_TRUE(update);\n ASSERT_TRUE(update->hasChanged());\n MyConfig cfg(update->getValue());\n ASSERT_EQUAL(\"l33t\", cfg.myField);\n\n handler.handleResponse(MyConfigRequest(testKey),\n MyConfigResponse::createOKResponse(testKey, testValue2, 2, testValue2.getMd5()));\n handler.handleResponse(MyConfigRequest(testKey),\n MyConfigResponse::createOKResponse(testKey, testValue2, 3, testValue2.getMd5()));\n ASSERT_TRUE(latch->poll());\n update = latch->provide();\n ASSERT_TRUE(update);\n ASSERT_FALSE(update->hasChanged()); \/\/ This is a bug. We are loosing the change on generation 1->2\n MyConfig cfg2(update->getValue());\n ASSERT_EQUAL(\"l34t\", cfg2.myField);\n}\n\nTEST(\"require that successful request sets correct wait time\") {\n const ConfigKey testKey(ConfigKey::create(\"mykey\"));\n const ConfigValue testValue(createValue(\"l33t\", \"a\"));\n IConfigHolder::SP latch(new MyHolder());\n FRTConfigAgent handler(latch, testTimingValues);\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createOKResponse(testKey, testValue));\n ASSERT_EQUAL(250u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createOKResponse(testKey, testValue));\n ASSERT_EQUAL(250u, handler.getWaitTime());\n}\n\nTEST(\"require that bad config response returns false\") {\n const ConfigKey testKey(ConfigKey::create(\"mykey\"));\n const ConfigValue testValue(createValue(\"myval\", \"a\"));\n IConfigHolder::SP latch(new MyHolder());\n FRTConfigAgent handler(latch, testTimingValues);\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(250u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(500u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(750u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1000u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1250u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1250u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createOKResponse(testKey, testValue));\n ASSERT_EQUAL(250u, handler.getWaitTime());\n ASSERT_EQUAL(2000u, handler.getTimeout());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createConfigErrorResponse(testKey, testValue));\n ASSERT_EQUAL(500u, handler.getWaitTime());\n ASSERT_EQUAL(500u, handler.getTimeout());\n}\n\nTEST(\"require that bad response returns false\") {\n const ConfigKey testKey(ConfigKey::create(\"mykey\"));\n std::vector lines;\n const ConfigValue testValue(lines, \"a\");\n\n IConfigHolder::SP latch(new MyHolder());\n FRTConfigAgent handler(latch, testTimingValues);\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(250u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(500u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(750u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1000u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1250u, handler.getWaitTime());\n\n handler.handleResponse(MyConfigRequest(testKey), MyConfigResponse::createServerErrorResponse(testKey, testValue));\n ASSERT_EQUAL(1250u, handler.getWaitTime());\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ACatalog.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 02:10:59 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#ifndef _CONNECTIVITY_ADO_CATALOG_HXX_\n#include \"ado\/ACatalog.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_\n#include \"ado\/AConnection.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_GROUPS_HXX_\n#include \"ado\/AGroups.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_USERS_HXX_\n#include \"ado\/AUsers.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_TABLES_HXX_\n#include \"ado\/ATables.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_VIEWS_HXX_\n#include \"ado\/AViews.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include \n#endif\n\n\n\/\/ -------------------------------------------------------------------------\nusing namespace connectivity;\nusing namespace connectivity::ado;\n\/\/ -------------------------------------------------------------------------\nOCatalog::OCatalog(_ADOCatalog* _pCatalog,OConnection* _pCon) : connectivity::sdbcx::OCatalog(_pCon)\n ,m_pConnection(_pCon)\n ,m_aCatalog(_pCatalog)\n{\n}\n\/\/ -----------------------------------------------------------------------------\nOCatalog::~OCatalog()\n{\n if(m_aCatalog.IsValid())\n m_aCatalog.putref_ActiveConnection(NULL);\n m_aCatalog.clear();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OCatalog::refreshTables()\n{\n TStringVector aVector;\n\n WpADOTables aTables(m_aCatalog.get_Tables());\n if ( aTables.IsValid() )\n {\n aTables.Refresh();\n sal_Int32 nCount = aTables.GetItemCount();\n aVector.reserve(nCount);\n for(sal_Int32 i=0;i< nCount;++i)\n {\n WpADOTable aElement = aTables.GetItem(i);\n if ( aElement.IsValid() )\n {\n ::rtl::OUString sTypeName = aElement.get_Type();\n if ( !sTypeName.equalsIgnoreAsciiCaseAscii(\"SYSTEM TABLE\") && !sTypeName.equalsIgnoreAsciiCaseAscii(\"ACCESS TABLE\") )\n aVector.push_back(aElement.get_Name());\n }\n }\n }\n\n if(m_pTables)\n m_pTables->reFill(aVector);\n else\n m_pTables = new OTables(this,m_aMutex,aVector,aTables,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OCatalog::refreshViews()\n{\n TStringVector aVector;\n\n WpADOViews aViews = m_aCatalog.get_Views();\n aViews.fillElementNames(aVector);\n\n if(m_pViews)\n m_pViews->reFill(aVector);\n else\n m_pViews = new OViews(this,m_aMutex,aVector,aViews,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OCatalog::refreshGroups()\n{\n TStringVector aVector;\n\n WpADOGroups aGroups = m_aCatalog.get_Groups();\n aGroups.fillElementNames(aVector);\n\n if(m_pGroups)\n m_pGroups->reFill(aVector);\n else\n m_pGroups = new OGroups(this,m_aMutex,aVector,aGroups,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OCatalog::refreshUsers()\n{\n TStringVector aVector;\n\n WpADOUsers aUsers = m_aCatalog.get_Users();\n aUsers.fillElementNames(aVector);\n\n if(m_pUsers)\n m_pUsers->reFill(aVector);\n else\n m_pUsers = new OUsers(this,m_aMutex,aVector,aUsers,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());\n}\n\/\/ -------------------------------------------------------------------------\n\n\nINTEGRATION: CWS changefileheader (1.12.216); FILE MERGED 2008\/04\/01 10:52:48 thb 1.12.216.2: #i85898# Stripping all external header guards 2008\/03\/28 15:23:25 rt 1.12.216.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ACatalog.cxx,v $\n * $Revision: 1.13 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n#include \"ado\/ACatalog.hxx\"\n#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_\n#include \"ado\/AConnection.hxx\"\n#endif\n#include \"ado\/AGroups.hxx\"\n#include \"ado\/AUsers.hxx\"\n#include \"ado\/ATables.hxx\"\n#include \"ado\/AViews.hxx\"\n#include \n#include \n\n\n\/\/ -------------------------------------------------------------------------\nusing namespace connectivity;\nusing namespace connectivity::ado;\n\/\/ -------------------------------------------------------------------------\nOCatalog::OCatalog(_ADOCatalog* _pCatalog,OConnection* _pCon) : connectivity::sdbcx::OCatalog(_pCon)\n ,m_pConnection(_pCon)\n ,m_aCatalog(_pCatalog)\n{\n}\n\/\/ -----------------------------------------------------------------------------\nOCatalog::~OCatalog()\n{\n if(m_aCatalog.IsValid())\n m_aCatalog.putref_ActiveConnection(NULL);\n m_aCatalog.clear();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OCatalog::refreshTables()\n{\n TStringVector aVector;\n\n WpADOTables aTables(m_aCatalog.get_Tables());\n if ( aTables.IsValid() )\n {\n aTables.Refresh();\n sal_Int32 nCount = aTables.GetItemCount();\n aVector.reserve(nCount);\n for(sal_Int32 i=0;i< nCount;++i)\n {\n WpADOTable aElement = aTables.GetItem(i);\n if ( aElement.IsValid() )\n {\n ::rtl::OUString sTypeName = aElement.get_Type();\n if ( !sTypeName.equalsIgnoreAsciiCaseAscii(\"SYSTEM TABLE\") && !sTypeName.equalsIgnoreAsciiCaseAscii(\"ACCESS TABLE\") )\n aVector.push_back(aElement.get_Name());\n }\n }\n }\n\n if(m_pTables)\n m_pTables->reFill(aVector);\n else\n m_pTables = new OTables(this,m_aMutex,aVector,aTables,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OCatalog::refreshViews()\n{\n TStringVector aVector;\n\n WpADOViews aViews = m_aCatalog.get_Views();\n aViews.fillElementNames(aVector);\n\n if(m_pViews)\n m_pViews->reFill(aVector);\n else\n m_pViews = new OViews(this,m_aMutex,aVector,aViews,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OCatalog::refreshGroups()\n{\n TStringVector aVector;\n\n WpADOGroups aGroups = m_aCatalog.get_Groups();\n aGroups.fillElementNames(aVector);\n\n if(m_pGroups)\n m_pGroups->reFill(aVector);\n else\n m_pGroups = new OGroups(this,m_aMutex,aVector,aGroups,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OCatalog::refreshUsers()\n{\n TStringVector aVector;\n\n WpADOUsers aUsers = m_aCatalog.get_Users();\n aUsers.fillElementNames(aVector);\n\n if(m_pUsers)\n m_pUsers->reFill(aVector);\n else\n m_pUsers = new OUsers(this,m_aMutex,aVector,aUsers,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());\n}\n\/\/ -------------------------------------------------------------------------\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 \"content\/common\/mojo\/service_registry_impl.h\"\n\n#include \"mojo\/common\/common_type_converters.h\"\n\nnamespace content {\n\nServiceRegistryImpl::ServiceRegistryImpl()\n : binding_(this), weak_factory_(this) {\n binding_.set_connection_error_handler(\n base::Bind(&ServiceRegistryImpl::OnConnectionError,\n base::Unretained(this)));\n}\n\nServiceRegistryImpl::~ServiceRegistryImpl() {\n while (!pending_connects_.empty()) {\n mojo::CloseRaw(pending_connects_.front().second);\n pending_connects_.pop();\n }\n}\n\nvoid ServiceRegistryImpl::Bind(\n mojo::InterfaceRequest request) {\n binding_.Bind(request.Pass());\n}\n\nvoid ServiceRegistryImpl::BindRemoteServiceProvider(\n mojo::ServiceProviderPtr service_provider) {\n CHECK(!remote_provider_);\n remote_provider_ = service_provider.Pass();\n while (!pending_connects_.empty()) {\n remote_provider_->ConnectToService(\n mojo::String::From(pending_connects_.front().first),\n mojo::ScopedMessagePipeHandle(pending_connects_.front().second));\n pending_connects_.pop();\n }\n}\n\nvoid ServiceRegistryImpl::AddService(\n const std::string& service_name,\n const base::Callback service_factory) {\n service_factories_[service_name] = service_factory;\n}\n\nvoid ServiceRegistryImpl::RemoveService(const std::string& service_name) {\n service_factories_.erase(service_name);\n}\n\nvoid ServiceRegistryImpl::ConnectToRemoteService(\n const base::StringPiece& service_name,\n mojo::ScopedMessagePipeHandle handle) {\n if (!remote_provider_) {\n pending_connects_.push(\n std::make_pair(service_name.as_string(), handle.release()));\n return;\n }\n remote_provider_->ConnectToService(mojo::String::From(service_name),\n handle.Pass());\n}\n\nbool ServiceRegistryImpl::IsBound() const {\n return binding_.is_bound();\n}\n\nbase::WeakPtr ServiceRegistryImpl::GetWeakPtr() {\n return weak_factory_.GetWeakPtr();\n}\n\nvoid ServiceRegistryImpl::ConnectToService(\n const mojo::String& name,\n mojo::ScopedMessagePipeHandle client_handle) {\n std::map >::iterator it =\n service_factories_.find(name);\n if (it == service_factories_.end())\n return;\n\n it->second.Run(client_handle.Pass());\n}\n\nvoid ServiceRegistryImpl::OnConnectionError() {\n binding_.Close();\n}\n\n} \/\/ namespace content\nReduce conversion template use for StringPiece.\/\/ 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 \"content\/common\/mojo\/service_registry_impl.h\"\n\n#include \"mojo\/common\/common_type_converters.h\"\n\nnamespace content {\n\nServiceRegistryImpl::ServiceRegistryImpl()\n : binding_(this), weak_factory_(this) {\n binding_.set_connection_error_handler(\n base::Bind(&ServiceRegistryImpl::OnConnectionError,\n base::Unretained(this)));\n}\n\nServiceRegistryImpl::~ServiceRegistryImpl() {\n while (!pending_connects_.empty()) {\n mojo::CloseRaw(pending_connects_.front().second);\n pending_connects_.pop();\n }\n}\n\nvoid ServiceRegistryImpl::Bind(\n mojo::InterfaceRequest request) {\n binding_.Bind(request.Pass());\n}\n\nvoid ServiceRegistryImpl::BindRemoteServiceProvider(\n mojo::ServiceProviderPtr service_provider) {\n CHECK(!remote_provider_);\n remote_provider_ = service_provider.Pass();\n while (!pending_connects_.empty()) {\n remote_provider_->ConnectToService(\n mojo::String::From(pending_connects_.front().first),\n mojo::ScopedMessagePipeHandle(pending_connects_.front().second));\n pending_connects_.pop();\n }\n}\n\nvoid ServiceRegistryImpl::AddService(\n const std::string& service_name,\n const base::Callback service_factory) {\n service_factories_[service_name] = service_factory;\n}\n\nvoid ServiceRegistryImpl::RemoveService(const std::string& service_name) {\n service_factories_.erase(service_name);\n}\n\nvoid ServiceRegistryImpl::ConnectToRemoteService(\n const base::StringPiece& service_name,\n mojo::ScopedMessagePipeHandle handle) {\n if (!remote_provider_) {\n pending_connects_.push(\n std::make_pair(service_name.as_string(), handle.release()));\n return;\n }\n remote_provider_->ConnectToService(\n mojo::String::From(service_name.as_string()), handle.Pass());\n}\n\nbool ServiceRegistryImpl::IsBound() const {\n return binding_.is_bound();\n}\n\nbase::WeakPtr ServiceRegistryImpl::GetWeakPtr() {\n return weak_factory_.GetWeakPtr();\n}\n\nvoid ServiceRegistryImpl::ConnectToService(\n const mojo::String& name,\n mojo::ScopedMessagePipeHandle client_handle) {\n std::map >::iterator it =\n service_factories_.find(name);\n if (it == service_factories_.end())\n return;\n\n it->second.Run(client_handle.Pass());\n}\n\nvoid ServiceRegistryImpl::OnConnectionError() {\n binding_.Close();\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"\n#include \"GasMeter.h\"\n\n#include \n#include \n#include \n\n#include \"Type.h\"\n#include \"Ext.h\"\n#include \"RuntimeManager.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nnamespace \/\/ Helper functions\n{\n\nuint64_t const c_stepGas = 1;\nuint64_t const c_balanceGas = 20;\nuint64_t const c_sha3Gas = 10;\nuint64_t const c_sha3WordGas = 10;\nuint64_t const c_sloadGas = 20;\nuint64_t const c_sstoreSetGas = 300;\nuint64_t const c_sstoreResetGas = 100;\nuint64_t const c_sstoreRefundGas = 100;\nuint64_t const c_createGas = 100;\nuint64_t const c_createDataGas = 5;\nuint64_t const c_callGas = 20;\nuint64_t const c_expGas = 1;\nuint64_t const c_expByteGas = 1;\nuint64_t const c_memoryGas = 1;\nuint64_t const c_txDataZeroGas = 1;\nuint64_t const c_txDataNonZeroGas = 5;\nuint64_t const c_txGas = 500;\nuint64_t const c_logGas = 32;\nuint64_t const c_logDataGas = 1;\nuint64_t const c_logTopicGas = 32;\nuint64_t const c_copyGas = 1;\n\nuint64_t getStepCost(Instruction inst)\n{\n\tswitch (inst)\n\t{\n\tdefault: \/\/ Assumes instruction code is valid\n\t\treturn c_stepGas;\n\n\tcase Instruction::STOP:\n\tcase Instruction::SUICIDE:\n\tcase Instruction::SSTORE: \/\/ Handle cost of SSTORE separately in GasMeter::countSStore()\n\t\treturn 0;\n\n\tcase Instruction::EXP:\t\treturn c_expGas;\n\n\tcase Instruction::SLOAD:\treturn c_sloadGas;\n\n\tcase Instruction::SHA3:\t\treturn c_sha3Gas;\n\n\tcase Instruction::BALANCE:\treturn c_balanceGas;\n\n\tcase Instruction::CALL:\n\tcase Instruction::CALLCODE:\treturn c_callGas;\n\n\tcase Instruction::CREATE:\treturn c_createGas;\n\n\tcase Instruction::LOG0:\n\tcase Instruction::LOG1:\n\tcase Instruction::LOG2:\n\tcase Instruction::LOG3:\n\tcase Instruction::LOG4:\n\t{\n\t\tauto numTopics = static_cast(inst) - static_cast(Instruction::LOG0);\n\t\treturn c_logGas + numTopics * c_logTopicGas;\n\t}\n\t}\n}\n\n}\n\nGasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) :\n\tCompilerHelper(_builder),\n\tm_runtimeManager(_runtimeManager)\n{\n\tauto module = getModule();\n\n\tllvm::Type* gasCheckArgs[] = {Type::RuntimePtr, Type::Word};\n\tm_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, gasCheckArgs, false), llvm::Function::PrivateLinkage, \"gas.check\", module);\n\tInsertPointGuard guard(m_builder);\n\n\tauto checkBB = llvm::BasicBlock::Create(_builder.getContext(), \"Check\", m_gasCheckFunc);\n\tauto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), \"OutOfGas\", m_gasCheckFunc);\n\tauto updateBB = llvm::BasicBlock::Create(_builder.getContext(), \"Update\", m_gasCheckFunc);\n\n\tm_builder.SetInsertPoint(checkBB);\n\tauto arg = m_gasCheckFunc->arg_begin();\n\targ->setName(\"rt\");\n\t++arg;\n\targ->setName(\"cost\");\n\tauto cost = arg;\n\tauto gas = m_runtimeManager.getGas();\n\tauto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, \"isOutOfGas\");\n\tm_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB);\n\n\tm_builder.SetInsertPoint(outOfGasBB);\n\tm_runtimeManager.raiseException(ReturnCode::OutOfGas);\n\tm_builder.CreateUnreachable();\n\n\tm_builder.SetInsertPoint(updateBB);\n\tgas = m_builder.CreateSub(gas, cost);\n\tm_runtimeManager.setGas(gas);\n\tm_builder.CreateRetVoid();\n}\n\nvoid GasMeter::count(Instruction _inst)\n{\n\tif (!m_checkCall)\n\t{\n\t\t\/\/ Create gas check call with mocked block cost at begining of current cost-block\n\t\tm_checkCall = createCall(m_gasCheckFunc, {m_runtimeManager.getRuntimePtr(), llvm::UndefValue::get(Type::Word)});\n\t}\n\n\tm_blockCost += getStepCost(_inst);\n}\n\nvoid GasMeter::count(llvm::Value* _cost)\n{\n\tcreateCall(m_gasCheckFunc, {m_runtimeManager.getRuntimePtr(), _cost});\n}\n\nvoid GasMeter::countExp(llvm::Value* _exponent)\n{\n\t\/\/ Additional cost is 1 per significant byte of exponent\n\t\/\/ lz - leading zeros\n\t\/\/ cost = ((256 - lz) + 7) \/ 8\n\n\t\/\/ OPT: All calculations can be done on 32\/64 bits\n\n\tauto ctlz = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::ctlz, Type::Word);\n\tauto lz = m_builder.CreateCall2(ctlz, _exponent, m_builder.getInt1(false));\n\tauto sigBits = m_builder.CreateSub(Constant::get(256), lz);\n\tauto sigBytes = m_builder.CreateUDiv(m_builder.CreateAdd(sigBits, Constant::get(7)), Constant::get(8));\n\tcount(sigBytes);\n}\n\nvoid GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)\n{\n\tauto oldValue = _ext.sload(_index);\n\tauto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), \"oldValueIsZero\");\n\tauto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), \"newValueIsZero\");\n\tauto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), \"oldValueIsntZero\");\n\tauto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), \"newValueIsntZero\");\n\tauto isInsert = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, \"isInsert\");\n\tauto isDelete = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, \"isDelete\");\n\tauto cost = m_builder.CreateSelect(isInsert, Constant::get(c_sstoreSetGas), Constant::get(c_sstoreResetGas), \"cost\");\n\tcost = m_builder.CreateSelect(isDelete, Constant::get(0), cost, \"cost\");\n\tcount(cost);\n}\n\nvoid GasMeter::countLogData(llvm::Value* _dataLength)\n{\n\tassert(m_checkCall);\n\tassert(m_blockCost > 0); \/\/ LOGn instruction is already counted\n\tstatic_assert(c_logDataGas == 1, \"Log data gas cost has changed. Update GasMeter.\");\n\tcount(_dataLength);\n}\n\nvoid GasMeter::countSha3Data(llvm::Value* _dataLength)\n{\n\tassert(m_checkCall);\n\tassert(m_blockCost > 0); \/\/ SHA3 instruction is already counted\n\n\t\/\/ TODO: This round ups to 32 happens in many places\n\t\/\/ FIXME: Overflow possible but Memory::require() also called. Probably 64-bit arith can be used.\n\tstatic_assert(c_sha3WordGas != 1, \"SHA3 data cost has changed. Update GasMeter\");\n\tauto words = m_builder.CreateUDiv(m_builder.CreateAdd(_dataLength, Constant::get(31)), Constant::get(32));\n\tauto cost = m_builder.CreateNUWMul(Constant::get(c_sha3WordGas), words);\n\tcount(cost);\n}\n\nvoid GasMeter::giveBack(llvm::Value* _gas)\n{\n\tm_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas));\n}\n\nvoid GasMeter::commitCostBlock()\n{\n\t\/\/ If any uncommited block\n\tif (m_checkCall)\n\t{\n\t\tif (m_blockCost == 0) \/\/ Do not check 0\n\t\t{\n\t\t\tm_checkCall->eraseFromParent(); \/\/ Remove the gas check call\n\t\t\tm_checkCall = nullptr;\n\t\t\treturn;\n\t\t}\n\n\t\tm_checkCall->setArgOperand(1, Constant::get(m_blockCost)); \/\/ Update block cost in gas check call\n\t\tm_checkCall = nullptr; \/\/ End cost-block\n\t\tm_blockCost = 0;\n\t}\n\tassert(m_blockCost == 0);\n}\n\nvoid GasMeter::countMemory(llvm::Value* _additionalMemoryInWords)\n{\n\tstatic_assert(c_memoryGas == 1, \"Memory gas cost has changed. Update GasMeter.\");\n\tcount(_additionalMemoryInWords);\n}\n\nvoid GasMeter::countCopy(llvm::Value* _copyWords)\n{\n\tstatic_assert(c_copyGas == 1, \"Copy gas cost has changed. Update GasMeter.\");\n\tcount(_copyWords);\n}\n\n}\n}\n}\n\nCompute SHA3 additional gas cost in 64-bit precision\n#include \"GasMeter.h\"\n\n#include \n#include \n#include \n\n#include \"Type.h\"\n#include \"Ext.h\"\n#include \"RuntimeManager.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nnamespace \/\/ Helper functions\n{\n\nuint64_t const c_stepGas = 1;\nuint64_t const c_balanceGas = 20;\nuint64_t const c_sha3Gas = 10;\nuint64_t const c_sha3WordGas = 10;\nuint64_t const c_sloadGas = 20;\nuint64_t const c_sstoreSetGas = 300;\nuint64_t const c_sstoreResetGas = 100;\nuint64_t const c_sstoreRefundGas = 100;\nuint64_t const c_createGas = 100;\nuint64_t const c_createDataGas = 5;\nuint64_t const c_callGas = 20;\nuint64_t const c_expGas = 1;\nuint64_t const c_expByteGas = 1;\nuint64_t const c_memoryGas = 1;\nuint64_t const c_txDataZeroGas = 1;\nuint64_t const c_txDataNonZeroGas = 5;\nuint64_t const c_txGas = 500;\nuint64_t const c_logGas = 32;\nuint64_t const c_logDataGas = 1;\nuint64_t const c_logTopicGas = 32;\nuint64_t const c_copyGas = 1;\n\nuint64_t getStepCost(Instruction inst)\n{\n\tswitch (inst)\n\t{\n\tdefault: \/\/ Assumes instruction code is valid\n\t\treturn c_stepGas;\n\n\tcase Instruction::STOP:\n\tcase Instruction::SUICIDE:\n\tcase Instruction::SSTORE: \/\/ Handle cost of SSTORE separately in GasMeter::countSStore()\n\t\treturn 0;\n\n\tcase Instruction::EXP:\t\treturn c_expGas;\n\n\tcase Instruction::SLOAD:\treturn c_sloadGas;\n\n\tcase Instruction::SHA3:\t\treturn c_sha3Gas;\n\n\tcase Instruction::BALANCE:\treturn c_balanceGas;\n\n\tcase Instruction::CALL:\n\tcase Instruction::CALLCODE:\treturn c_callGas;\n\n\tcase Instruction::CREATE:\treturn c_createGas;\n\n\tcase Instruction::LOG0:\n\tcase Instruction::LOG1:\n\tcase Instruction::LOG2:\n\tcase Instruction::LOG3:\n\tcase Instruction::LOG4:\n\t{\n\t\tauto numTopics = static_cast(inst) - static_cast(Instruction::LOG0);\n\t\treturn c_logGas + numTopics * c_logTopicGas;\n\t}\n\t}\n}\n\n}\n\nGasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) :\n\tCompilerHelper(_builder),\n\tm_runtimeManager(_runtimeManager)\n{\n\tauto module = getModule();\n\n\tllvm::Type* gasCheckArgs[] = {Type::RuntimePtr, Type::Word};\n\tm_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, gasCheckArgs, false), llvm::Function::PrivateLinkage, \"gas.check\", module);\n\tInsertPointGuard guard(m_builder);\n\n\tauto checkBB = llvm::BasicBlock::Create(_builder.getContext(), \"Check\", m_gasCheckFunc);\n\tauto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), \"OutOfGas\", m_gasCheckFunc);\n\tauto updateBB = llvm::BasicBlock::Create(_builder.getContext(), \"Update\", m_gasCheckFunc);\n\n\tm_builder.SetInsertPoint(checkBB);\n\tauto arg = m_gasCheckFunc->arg_begin();\n\targ->setName(\"rt\");\n\t++arg;\n\targ->setName(\"cost\");\n\tauto cost = arg;\n\tauto gas = m_runtimeManager.getGas();\n\tauto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, \"isOutOfGas\");\n\tm_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB);\n\n\tm_builder.SetInsertPoint(outOfGasBB);\n\tm_runtimeManager.raiseException(ReturnCode::OutOfGas);\n\tm_builder.CreateUnreachable();\n\n\tm_builder.SetInsertPoint(updateBB);\n\tgas = m_builder.CreateSub(gas, cost);\n\tm_runtimeManager.setGas(gas);\n\tm_builder.CreateRetVoid();\n}\n\nvoid GasMeter::count(Instruction _inst)\n{\n\tif (!m_checkCall)\n\t{\n\t\t\/\/ Create gas check call with mocked block cost at begining of current cost-block\n\t\tm_checkCall = createCall(m_gasCheckFunc, {m_runtimeManager.getRuntimePtr(), llvm::UndefValue::get(Type::Word)});\n\t}\n\n\tm_blockCost += getStepCost(_inst);\n}\n\nvoid GasMeter::count(llvm::Value* _cost)\n{\n\tcreateCall(m_gasCheckFunc, {m_runtimeManager.getRuntimePtr(), _cost});\n}\n\nvoid GasMeter::countExp(llvm::Value* _exponent)\n{\n\t\/\/ Additional cost is 1 per significant byte of exponent\n\t\/\/ lz - leading zeros\n\t\/\/ cost = ((256 - lz) + 7) \/ 8\n\n\t\/\/ OPT: All calculations can be done on 32\/64 bits\n\n\tauto ctlz = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::ctlz, Type::Word);\n\tauto lz = m_builder.CreateCall2(ctlz, _exponent, m_builder.getInt1(false));\n\tauto sigBits = m_builder.CreateSub(Constant::get(256), lz);\n\tauto sigBytes = m_builder.CreateUDiv(m_builder.CreateAdd(sigBits, Constant::get(7)), Constant::get(8));\n\tcount(sigBytes);\n}\n\nvoid GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)\n{\n\tauto oldValue = _ext.sload(_index);\n\tauto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), \"oldValueIsZero\");\n\tauto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), \"newValueIsZero\");\n\tauto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), \"oldValueIsntZero\");\n\tauto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), \"newValueIsntZero\");\n\tauto isInsert = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, \"isInsert\");\n\tauto isDelete = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, \"isDelete\");\n\tauto cost = m_builder.CreateSelect(isInsert, Constant::get(c_sstoreSetGas), Constant::get(c_sstoreResetGas), \"cost\");\n\tcost = m_builder.CreateSelect(isDelete, Constant::get(0), cost, \"cost\");\n\tcount(cost);\n}\n\nvoid GasMeter::countLogData(llvm::Value* _dataLength)\n{\n\tassert(m_checkCall);\n\tassert(m_blockCost > 0); \/\/ LOGn instruction is already counted\n\tstatic_assert(c_logDataGas == 1, \"Log data gas cost has changed. Update GasMeter.\");\n\tcount(_dataLength);\n}\n\nvoid GasMeter::countSha3Data(llvm::Value* _dataLength)\n{\n\tassert(m_checkCall);\n\tassert(m_blockCost > 0); \/\/ SHA3 instruction is already counted\n\n\t\/\/ TODO: This round ups to 32 happens in many places\n\t\/\/ FIXME: 64-bit arith used, but not verified\n\tstatic_assert(c_sha3WordGas != 1, \"SHA3 data cost has changed. Update GasMeter\");\n\tauto dataLength64 = getBuilder().CreateTrunc(_dataLength, Type::lowPrecision);\n\tauto words64 = m_builder.CreateUDiv(m_builder.CreateAdd(dataLength64, getBuilder().getInt64(31)), getBuilder().getInt64(32));\n\tauto cost64 = m_builder.CreateNUWMul(getBuilder().getInt64(c_sha3WordGas), words64);\n\tauto cost = getBuilder().CreateZExt(cost64, Type::Word);\n\tcount(cost);\n}\n\nvoid GasMeter::giveBack(llvm::Value* _gas)\n{\n\tm_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas));\n}\n\nvoid GasMeter::commitCostBlock()\n{\n\t\/\/ If any uncommited block\n\tif (m_checkCall)\n\t{\n\t\tif (m_blockCost == 0) \/\/ Do not check 0\n\t\t{\n\t\t\tm_checkCall->eraseFromParent(); \/\/ Remove the gas check call\n\t\t\tm_checkCall = nullptr;\n\t\t\treturn;\n\t\t}\n\n\t\tm_checkCall->setArgOperand(1, Constant::get(m_blockCost)); \/\/ Update block cost in gas check call\n\t\tm_checkCall = nullptr; \/\/ End cost-block\n\t\tm_blockCost = 0;\n\t}\n\tassert(m_blockCost == 0);\n}\n\nvoid GasMeter::countMemory(llvm::Value* _additionalMemoryInWords)\n{\n\tstatic_assert(c_memoryGas == 1, \"Memory gas cost has changed. Update GasMeter.\");\n\tcount(_additionalMemoryInWords);\n}\n\nvoid GasMeter::countCopy(llvm::Value* _copyWords)\n{\n\tstatic_assert(c_copyGas == 1, \"Copy gas cost has changed. Update GasMeter.\");\n\tcount(_copyWords);\n}\n\n}\n}\n}\n\n<|endoftext|>"} {"text":"Hackerrank > Algorithms > Warmup > Plus Minus<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 Andrew Duggan\n * Copyright (C) 2014 Synaptics Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"hiddevice.h\"\n#include \"rmi4update.h\"\n\n#define RMI4UPDATE_GETOPTS\t\"hfd:\"\n\nvoid printHelp(const char *prog_name)\n{\n\tfprintf(stdout, \"Usage: %s [OPTIONS] FIRMWAREFILE\\n\", prog_name);\n\tfprintf(stdout, \"\\t-h, --help\\tPrint this message\\n\");\n\tfprintf(stdout, \"\\t-f, --force\\tForce updating firmware even it the image provided is older\\n\\t\\t\\tthen the current firmware on the device.\\n\");\n\tfprintf(stdout, \"\\t-d, --device\\thidraw device file associated with the device being updated.\\n\");\n}\n\nint UpdateDevice(FirmwareImage & image, bool force, const char * deviceFile)\n{\n\tHIDDevice rmidevice;\n\tint rc;\n\n\trc = rmidevice.Open(deviceFile);\n\tif (rc)\n\t\treturn rc;\n\n\tRMI4Update update(rmidevice, image);\n\trc = update.UpdateFirmware(force);\n\tif (rc != UPDATE_SUCCESS)\n\t\treturn rc;\n\n\treturn rc;\n}\n\nint WriteDeviceNameToFile(const char * file, const char * str)\n{\n\tint fd;\n\tssize_t size;\n\n\tfd = open(file, O_WRONLY);\n\tif (fd < 0)\n\t\treturn UPDATE_FAIL;\n\n\tfor (;;) {\n\t\tsize = write(fd, str, 19);\n\t\tif (size < 0) {\n\t\t\tif (errno == EINTR)\n\t\t\t\tcontinue;\n\n\t\t\treturn UPDATE_FAIL;\n\t\t}\n\t\tbreak;\n\t}\n\n\tclose(fd);\n\n\treturn UPDATE_SUCCESS;\n}\n\n\/*\n * We need to rebind the driver to the device after firmware update for two reasons\n * \ta) The parameters of the device may have changed in the new firmware so the\n *\t driver should redo the initialization to read the new values.\n *\tb) Kernel commit 0f5a24c6 will now power down the device once we close the\n *\t file descriptor for the hidraw device file. Reloading the driver powers the\n *\t device back on.\n *\/\nvoid RebindDriver(const char * hidraw)\n{\n\tint rc;\n\tssize_t size;\n\tchar bindFile[PATH_MAX];\n\tchar unbindFile[PATH_MAX];\n\tchar deviceLink[PATH_MAX];\n\tchar driverName[PATH_MAX];\n\tchar driverLink[PATH_MAX];\n\tchar linkBuf[PATH_MAX];\n\tchar hidDeviceString[20];\n\tint i;\n\n\tsnprintf(unbindFile, PATH_MAX, \"\/sys\/class\/hidraw\/%s\/device\/driver\/unbind\", hidraw);\n\tsnprintf(deviceLink, PATH_MAX, \"\/sys\/class\/hidraw\/%s\/device\", hidraw);\n\n\tsize = readlink(deviceLink, linkBuf, PATH_MAX);\n\tif (size < 0) {\n\t\tfprintf(stderr, \"Failed to find the HID string for this device: %s\\n\",\n\t\t\thidraw);\n\t\treturn;\n\t}\n\tlinkBuf[size] = 0;\n\n\tstrncpy(hidDeviceString, StripPath(linkBuf, size), 20);\n\n\tsnprintf(driverLink, PATH_MAX, \"\/sys\/class\/hidraw\/%s\/device\/driver\", hidraw);\n\n\tsize = readlink(driverLink, linkBuf, PATH_MAX);\n\tif (size < 0) {\n\t\tfprintf(stderr, \"Failed to find the HID string for this device: %s\\n\",\n\t\t\thidraw);\n\t\treturn;\n\t}\n\tlinkBuf[size] = 0;\n\n\tstrncpy(driverName, StripPath(linkBuf, size), PATH_MAX);\n\n\tsnprintf(bindFile, PATH_MAX, \"\/sys\/bus\/hid\/drivers\/%s\/bind\", driverName);\n\n\trc = WriteDeviceNameToFile(unbindFile, hidDeviceString);\n\tif (rc != UPDATE_SUCCESS) {\n\t\tfprintf(stderr, \"Failed to unbind HID device %s: %s\\n\",\n\t\t\thidDeviceString, strerror(errno));\n\t\treturn;\n\t}\n\n\tfor (i = 0;; ++i) {\n\t\tstruct timespec req;\n\t\tstruct timespec rem;\n\n\t\trc = WriteDeviceNameToFile(bindFile, hidDeviceString);\n\t\tif (rc == UPDATE_SUCCESS)\n\t\t\treturn;\n\n\t\tif (i <= 4)\n\t\t\tbreak;\n\n\t\t\/* device might not be ready yet to bind to *\/\n\t\treq.tv_sec = 0;\n\t\treq.tv_nsec = 100 * 1000 * 1000; \/* 100 ms *\/\n\t\tfor (;;) {\n\t\t\trc = nanosleep(&req, &rem);\n\t\t\tif (rc < 0) {\n\t\t\t\tif (errno == EINTR) {\n\t\t\t\t\treq = rem;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tfprintf(stderr, \"Failed to bind HID device %s: %s\\n\",\n\t\thidDeviceString, strerror(errno));\n}\n\nint main(int argc, char **argv)\n{\n\tint rc;\n\tFirmwareImage image;\n\tint opt;\n\tint index;\n\tconst char *deviceName = NULL;\n\tconst char *firmwareName = NULL;\n\tbool force = false;\n\tstatic struct option long_options[] = {\n\t\t{\"help\", 0, NULL, 'h'},\n\t\t{\"force\", 0, NULL, 'f'},\n\t\t{\"device\", 1, NULL, 'd'},\n\t\t{0, 0, 0, 0},\n\t};\n\tstruct dirent * devDirEntry;\n\tDIR * devDir;\n\n\twhile ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {\n\t\tswitch (opt) {\n\t\t\tcase 'h':\n\t\t\t\tprintHelp(argv[0]);\n\t\t\t\treturn 0;\n\t\t\tcase 'f':\n\t\t\t\tforce = true;\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tdeviceName = optarg;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\n\t\t}\n\t}\n\n\tif (optind < argc) {\n\t\tfirmwareName = argv[optind];\n\t} else {\n\t\tprintHelp(argv[0]);\n\t\treturn -1;\n\t}\n\n\trc = image.Initialize(firmwareName);\n\tif (rc != UPDATE_SUCCESS) {\n\t\tfprintf(stderr, \"Failed to initialize the firmware image: %s\\n\", update_err_to_string(rc));\n\t\treturn 1;\n\t}\n\n\tif (deviceName) {\n\t\treturn UpdateDevice(image, force, deviceName);\n\t} else {\n\t\tchar rawDevice[PATH_MAX];\n\t\tchar deviceFile[PATH_MAX];\n\t\tbool found = false;\n\n\t\tdevDir = opendir(\"\/dev\");\n\t\tif (!devDir)\n\t\t\treturn -1;\n\n\t\twhile ((devDirEntry = readdir(devDir)) != NULL) {\n\t\t\tif (strstr(devDirEntry->d_name, \"hidraw\")) {\n\t\t\t\tstrncpy(rawDevice, devDirEntry->d_name, PATH_MAX);\n\t\t\t\tsnprintf(deviceFile, PATH_MAX, \"\/dev\/%s\", devDirEntry->d_name);\n\t\t\t\trc = UpdateDevice(image, force, deviceFile);\n\t\t\t\tif (rc != 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tRebindDriver(rawDevice);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(devDir);\n\n\t\tif (!found)\n\t\t\treturn rc;\n\t}\n\n\treturn 0;\n}\nAdd an option to print a string describing the firmware version and build id.\/*\n * Copyright (C) 2014 Andrew Duggan\n * Copyright (C) 2014 Synaptics Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"hiddevice.h\"\n#include \"rmi4update.h\"\n\n#define RMI4UPDATE_GETOPTS\t\"hfd:p\"\n\nvoid printHelp(const char *prog_name)\n{\n\tfprintf(stdout, \"Usage: %s [OPTIONS] FIRMWAREFILE\\n\", prog_name);\n\tfprintf(stdout, \"\\t-h, --help\\tPrint this message\\n\");\n\tfprintf(stdout, \"\\t-f, --force\\tForce updating firmware even it the image provided is older\\n\\t\\t\\tthen the current firmware on the device.\\n\");\n\tfprintf(stdout, \"\\t-d, --device\\thidraw device file associated with the device being updated.\\n\");\n\tfprintf(stdout, \"\\t-p, --fw-props\\tPrint the firmware properties.\\n\");\n}\n\nint UpdateDevice(FirmwareImage & image, bool force, const char * deviceFile)\n{\n\tHIDDevice rmidevice;\n\tint rc;\n\n\trc = rmidevice.Open(deviceFile);\n\tif (rc)\n\t\treturn rc;\n\n\tRMI4Update update(rmidevice, image);\n\trc = update.UpdateFirmware(force);\n\tif (rc != UPDATE_SUCCESS)\n\t\treturn rc;\n\n\treturn rc;\n}\n\nint WriteDeviceNameToFile(const char * file, const char * str)\n{\n\tint fd;\n\tssize_t size;\n\n\tfd = open(file, O_WRONLY);\n\tif (fd < 0)\n\t\treturn UPDATE_FAIL;\n\n\tfor (;;) {\n\t\tsize = write(fd, str, 19);\n\t\tif (size < 0) {\n\t\t\tif (errno == EINTR)\n\t\t\t\tcontinue;\n\n\t\t\treturn UPDATE_FAIL;\n\t\t}\n\t\tbreak;\n\t}\n\n\tclose(fd);\n\n\treturn UPDATE_SUCCESS;\n}\n\n\/*\n * We need to rebind the driver to the device after firmware update for two reasons\n * \ta) The parameters of the device may have changed in the new firmware so the\n *\t driver should redo the initialization to read the new values.\n *\tb) Kernel commit 0f5a24c6 will now power down the device once we close the\n *\t file descriptor for the hidraw device file. Reloading the driver powers the\n *\t device back on.\n *\/\nvoid RebindDriver(const char * hidraw)\n{\n\tint rc;\n\tssize_t size;\n\tchar bindFile[PATH_MAX];\n\tchar unbindFile[PATH_MAX];\n\tchar deviceLink[PATH_MAX];\n\tchar driverName[PATH_MAX];\n\tchar driverLink[PATH_MAX];\n\tchar linkBuf[PATH_MAX];\n\tchar hidDeviceString[20];\n\tint i;\n\n\tsnprintf(unbindFile, PATH_MAX, \"\/sys\/class\/hidraw\/%s\/device\/driver\/unbind\", hidraw);\n\tsnprintf(deviceLink, PATH_MAX, \"\/sys\/class\/hidraw\/%s\/device\", hidraw);\n\n\tsize = readlink(deviceLink, linkBuf, PATH_MAX);\n\tif (size < 0) {\n\t\tfprintf(stderr, \"Failed to find the HID string for this device: %s\\n\",\n\t\t\thidraw);\n\t\treturn;\n\t}\n\tlinkBuf[size] = 0;\n\n\tstrncpy(hidDeviceString, StripPath(linkBuf, size), 20);\n\n\tsnprintf(driverLink, PATH_MAX, \"\/sys\/class\/hidraw\/%s\/device\/driver\", hidraw);\n\n\tsize = readlink(driverLink, linkBuf, PATH_MAX);\n\tif (size < 0) {\n\t\tfprintf(stderr, \"Failed to find the HID string for this device: %s\\n\",\n\t\t\thidraw);\n\t\treturn;\n\t}\n\tlinkBuf[size] = 0;\n\n\tstrncpy(driverName, StripPath(linkBuf, size), PATH_MAX);\n\n\tsnprintf(bindFile, PATH_MAX, \"\/sys\/bus\/hid\/drivers\/%s\/bind\", driverName);\n\n\trc = WriteDeviceNameToFile(unbindFile, hidDeviceString);\n\tif (rc != UPDATE_SUCCESS) {\n\t\tfprintf(stderr, \"Failed to unbind HID device %s: %s\\n\",\n\t\t\thidDeviceString, strerror(errno));\n\t\treturn;\n\t}\n\n\tfor (i = 0;; ++i) {\n\t\tstruct timespec req;\n\t\tstruct timespec rem;\n\n\t\trc = WriteDeviceNameToFile(bindFile, hidDeviceString);\n\t\tif (rc == UPDATE_SUCCESS)\n\t\t\treturn;\n\n\t\tif (i <= 4)\n\t\t\tbreak;\n\n\t\t\/* device might not be ready yet to bind to *\/\n\t\treq.tv_sec = 0;\n\t\treq.tv_nsec = 100 * 1000 * 1000; \/* 100 ms *\/\n\t\tfor (;;) {\n\t\t\trc = nanosleep(&req, &rem);\n\t\t\tif (rc < 0) {\n\t\t\t\tif (errno == EINTR) {\n\t\t\t\t\treq = rem;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tfprintf(stderr, \"Failed to bind HID device %s: %s\\n\",\n\t\thidDeviceString, strerror(errno));\n}\n\nint GetFirmwareProps(const char * deviceFile, std::string &props)\n{\n\tHIDDevice rmidevice;\n\tint rc = UPDATE_SUCCESS;\n\tstd::stringstream ss;\n\n\trc = rmidevice.Open(deviceFile);\n\tif (rc)\n\t\treturn rc;\n\n\trmidevice.ScanPDT();\n\trmidevice.QueryBasicProperties();\n\n\tss << rmidevice.GetFirmwareVersionMajor() << \".\"\n\t\t<< rmidevice.GetFirmwareVersionMinor() << \".\"\n\t\t<< std::hex << rmidevice.GetFirmwareID();\n\n\tprops = ss.str();\n\n\treturn rc;\n}\n\nint main(int argc, char **argv)\n{\n\tint rc;\n\tFirmwareImage image;\n\tint opt;\n\tint index;\n\tconst char *deviceName = NULL;\n\tconst char *firmwareName = NULL;\n\tbool force = false;\n\tstatic struct option long_options[] = {\n\t\t{\"help\", 0, NULL, 'h'},\n\t\t{\"force\", 0, NULL, 'f'},\n\t\t{\"device\", 1, NULL, 'd'},\n\t\t{\"fw-props\", 0, NULL, 'p'},\n\t\t{0, 0, 0, 0},\n\t};\n\tstruct dirent * devDirEntry;\n\tDIR * devDir;\n\tbool printFirmwareProps = false;\n\n\twhile ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {\n\t\tswitch (opt) {\n\t\t\tcase 'h':\n\t\t\t\tprintHelp(argv[0]);\n\t\t\t\treturn 0;\n\t\t\tcase 'f':\n\t\t\t\tforce = true;\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tdeviceName = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'p':\n\t\t\t\tprintFirmwareProps = true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\n\t\t}\n\t}\n\n\tif (printFirmwareProps) {\n\t\tstd::string props;\n\n\t\tif (!deviceName) {\n\t\t\tfprintf(stderr, \"Specifiy which device to query\\n\");\n\t\t\treturn 1;\n\t\t}\n\t\trc = GetFirmwareProps(deviceName, props);\n\t\tif (rc) {\n\t\t\tfprintf(stderr, \"Failed to read properties from device: %s\\n\", update_err_to_string(rc));\n\t\t\treturn 1;\n\t\t}\n\t\tfprintf(stdout, \"%s\\n\", props.c_str());\n\t\treturn 0;\n\t}\n\n\tif (optind < argc) {\n\t\tfirmwareName = argv[optind];\n\t} else {\n\t\tprintHelp(argv[0]);\n\t\treturn -1;\n\t}\n\n\trc = image.Initialize(firmwareName);\n\tif (rc != UPDATE_SUCCESS) {\n\t\tfprintf(stderr, \"Failed to initialize the firmware image: %s\\n\", update_err_to_string(rc));\n\t\treturn 1;\n\t}\n\n\tif (deviceName) {\n\t\treturn UpdateDevice(image, force, deviceName);\n\t} else {\n\t\tchar rawDevice[PATH_MAX];\n\t\tchar deviceFile[PATH_MAX];\n\t\tbool found = false;\n\n\t\tdevDir = opendir(\"\/dev\");\n\t\tif (!devDir)\n\t\t\treturn -1;\n\n\t\twhile ((devDirEntry = readdir(devDir)) != NULL) {\n\t\t\tif (strstr(devDirEntry->d_name, \"hidraw\")) {\n\t\t\t\tstrncpy(rawDevice, devDirEntry->d_name, PATH_MAX);\n\t\t\t\tsnprintf(deviceFile, PATH_MAX, \"\/dev\/%s\", devDirEntry->d_name);\n\t\t\t\trc = UpdateDevice(image, force, deviceFile);\n\t\t\t\tif (rc != 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tRebindDriver(rawDevice);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclosedir(devDir);\n\n\t\tif (!found)\n\t\t\treturn rc;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"Do not update settings that haven't changed.<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"ShapeContextHandler.hxx\"\n#include \"oox\/vml\/vmldrawingfragment.hxx\"\n#include \"oox\/vml\/vmlshape.hxx\"\n#include \"oox\/vml\/vmlshapecontainer.hxx\"\n\nnamespace oox { namespace shape {\n\nusing namespace ::com::sun::star;\nusing namespace core;\nusing namespace drawingml;\n\n::rtl::OUString SAL_CALL ShapeContextHandler_getImplementationName()\n{\n return CREATE_OUSTRING( \"com.sun.star.comp.oox.ShapeContextHandler\" );\n}\n\nuno::Sequence< ::rtl::OUString > SAL_CALL\nShapeContextHandler_getSupportedServiceNames()\n{\n uno::Sequence< ::rtl::OUString > s(1);\n s[0] = CREATE_OUSTRING( \"com.sun.star.xml.sax.FastShapeContextHandler\" );\n return s;\n}\n\nuno::Reference< uno::XInterface > SAL_CALL\nShapeContextHandler_createInstance( const uno::Reference< uno::XComponentContext > & context)\n SAL_THROW((uno::Exception))\n{\n return static_cast< ::cppu::OWeakObject* >( new ShapeContextHandler(context) );\n}\n\n\nShapeContextHandler::ShapeContextHandler\n(uno::Reference< uno::XComponentContext > const & context) :\nmnStartToken(0), m_xContext(context)\n{\n try\n {\n mxFilterBase.set( new ShapeFilterBase(context) );\n }\n catch( uno::Exception& )\n {\n }\n}\n\nShapeContextHandler::~ShapeContextHandler()\n{\n}\n\nuno::Reference\nShapeContextHandler::getGraphicShapeContext(::sal_Int32 Element )\n{\n if (! mxGraphicShapeContext.is())\n {\n FragmentHandlerRef rFragmentHandler\n (new ShapeFragmentHandler(*mxFilterBase, msRelationFragmentPath));\n ShapePtr pMasterShape;\n\n switch (Element & 0xffff)\n {\n case XML_graphic:\n mpShape.reset(new Shape(\"com.sun.star.drawing.GraphicObjectShape\" ));\n mxGraphicShapeContext.set\n (new GraphicalObjectFrameContext(*rFragmentHandler, pMasterShape, mpShape, true));\n break;\n case XML_pic:\n mpShape.reset(new Shape(\"com.sun.star.drawing.GraphicObjectShape\" ));\n mxGraphicShapeContext.set\n (new GraphicShapeContext(*rFragmentHandler, pMasterShape, mpShape));\n break;\n default:\n break;\n }\n }\n\n return mxGraphicShapeContext;\n}\n\nuno::Reference\nShapeContextHandler::getDrawingShapeContext()\n{\n if (!mxDrawingFragmentHandler.is())\n {\n mpDrawing.reset( new oox::vml::Drawing( *mxFilterBase, mxDrawPage, oox::vml::VMLDRAWING_WORD ) );\n mxDrawingFragmentHandler.set\n (dynamic_cast\n (new oox::vml::DrawingFragment\n ( *mxFilterBase, msRelationFragmentPath, *mpDrawing )));\n }\n\n return mxDrawingFragmentHandler;\n}\n\nuno::Reference\nShapeContextHandler::getContextHandler()\n{\n uno::Reference xResult;\n\n switch (getNamespace( mnStartToken ))\n {\n case NMSP_doc:\n case NMSP_vml:\n xResult.set(getDrawingShapeContext());\n break;\n default:\n xResult.set(getGraphicShapeContext(mnStartToken));\n break;\n }\n\n return xResult;\n}\n\n\/\/ ::com::sun::star::xml::sax::XFastContextHandler:\nvoid SAL_CALL ShapeContextHandler::startFastElement\n(::sal_Int32 Element,\n const uno::Reference< xml::sax::XFastAttributeList > & Attribs)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n static const ::rtl::OUString sInputStream\n (RTL_CONSTASCII_USTRINGPARAM (\"InputStream\"));\n\n uno::Sequence aSeq(1);\n aSeq[0].Name = sInputStream;\n aSeq[0].Value <<= mxInputStream;\n mxFilterBase->filter(aSeq);\n\n mpThemePtr.reset(new Theme());\n\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xContextHandler->startFastElement(Element, Attribs);\n}\n\nvoid SAL_CALL ShapeContextHandler::startUnknownElement\n(const ::rtl::OUString & Namespace, const ::rtl::OUString & Name,\n const uno::Reference< xml::sax::XFastAttributeList > & Attribs)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xContextHandler->startUnknownElement(Namespace, Name, Attribs);\n}\n\nvoid SAL_CALL ShapeContextHandler::endFastElement(::sal_Int32 Element)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xContextHandler->endFastElement(Element);\n}\n\nvoid SAL_CALL ShapeContextHandler::endUnknownElement\n(const ::rtl::OUString & Namespace,\n const ::rtl::OUString & Name)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xContextHandler->endUnknownElement(Namespace, Name);\n}\n\nuno::Reference< xml::sax::XFastContextHandler > SAL_CALL\nShapeContextHandler::createFastChildContext\n(::sal_Int32 Element,\n const uno::Reference< xml::sax::XFastAttributeList > & Attribs)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference< xml::sax::XFastContextHandler > xResult;\n uno::Reference< xml::sax::XFastContextHandler > xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xResult.set(xContextHandler->createFastChildContext\n (Element, Attribs));\n\n return xResult;\n}\n\nuno::Reference< xml::sax::XFastContextHandler > SAL_CALL\nShapeContextHandler::createUnknownChildContext\n(const ::rtl::OUString & Namespace,\n const ::rtl::OUString & Name,\n const uno::Reference< xml::sax::XFastAttributeList > & Attribs)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n return xContextHandler->createUnknownChildContext\n (Namespace, Name, Attribs);\n\n return uno::Reference< xml::sax::XFastContextHandler >();\n}\n\nvoid SAL_CALL ShapeContextHandler::characters(const ::rtl::OUString & aChars)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xContextHandler->characters(aChars);\n}\n\n\/\/ ::com::sun::star::xml::sax::XFastShapeContextHandler:\nuno::Reference< drawing::XShape > SAL_CALL\nShapeContextHandler::getShape() throw (uno::RuntimeException)\n{\n uno::Reference< drawing::XShape > xResult;\n uno::Reference< drawing::XShapes > xShapes( mxDrawPage, uno::UNO_QUERY );\n\n if (mxFilterBase.is() && xShapes.is())\n {\n if ( getContextHandler() == getDrawingShapeContext() )\n {\n mpDrawing->finalizeFragmentImport();\n if( const ::oox::vml::ShapeBase* pShape = mpDrawing->getShapes().getFirstShape() )\n {\n mpDrawing->getShapes( ).clearShapes( );\n xResult = pShape->convertAndInsert( xShapes );\n }\n }\n else if (mpShape.get() != NULL)\n {\n basegfx::B2DHomMatrix aTransformation;\n mpShape->addShape(*mxFilterBase, mpThemePtr.get(), xShapes, aTransformation);\n xResult.set(mpShape->getXShape());\n mxGraphicShapeContext.clear( );\n }\n }\n\n return xResult;\n}\n\ncss::uno::Reference< css::drawing::XDrawPage > SAL_CALL\nShapeContextHandler::getDrawPage() throw (css::uno::RuntimeException)\n{\n return mxDrawPage;\n}\n\nvoid SAL_CALL ShapeContextHandler::setDrawPage\n(const css::uno::Reference< css::drawing::XDrawPage > & the_value)\n throw (css::uno::RuntimeException)\n{\n mxDrawPage = the_value;\n}\n\ncss::uno::Reference< css::frame::XModel > SAL_CALL\nShapeContextHandler::getModel() throw (css::uno::RuntimeException)\n{\n if( !mxFilterBase.is() )\n throw uno::RuntimeException();\n return mxFilterBase->getModel();\n}\n\nvoid SAL_CALL ShapeContextHandler::setModel\n(const css::uno::Reference< css::frame::XModel > & the_value)\n throw (css::uno::RuntimeException)\n{\n if( !mxFilterBase.is() )\n throw uno::RuntimeException();\n uno::Reference xComp(the_value, uno::UNO_QUERY_THROW);\n mxFilterBase->setTargetDocument(xComp);\n}\n\nuno::Reference< io::XInputStream > SAL_CALL\nShapeContextHandler::getInputStream() throw (uno::RuntimeException)\n{\n return mxInputStream;\n}\n\nvoid SAL_CALL ShapeContextHandler::setInputStream\n(const uno::Reference< io::XInputStream > & the_value)\n throw (uno::RuntimeException)\n{\n mxInputStream = the_value;\n}\n\n::rtl::OUString SAL_CALL ShapeContextHandler::getRelationFragmentPath()\n throw (uno::RuntimeException)\n{\n return msRelationFragmentPath;\n}\n\nvoid SAL_CALL ShapeContextHandler::setRelationFragmentPath\n(const ::rtl::OUString & the_value)\n throw (uno::RuntimeException)\n{\n msRelationFragmentPath = the_value;\n}\n\n::sal_Int32 SAL_CALL ShapeContextHandler::getStartToken() throw (::com::sun::star::uno::RuntimeException)\n{\n return mnStartToken;\n}\n\nvoid SAL_CALL ShapeContextHandler::setStartToken( ::sal_Int32 _starttoken ) throw (::com::sun::star::uno::RuntimeException)\n{\n mnStartToken = _starttoken;\n\n\n}\n\n::rtl::OUString ShapeContextHandler::getImplementationName()\n throw (css::uno::RuntimeException)\n{\n return ShapeContextHandler_getImplementationName();\n}\n\nuno::Sequence< ::rtl::OUString > ShapeContextHandler::getSupportedServiceNames()\n throw (css::uno::RuntimeException)\n{\n return ShapeContextHandler_getSupportedServiceNames();\n}\n\n::sal_Bool SAL_CALL ShapeContextHandler::supportsService\n(const ::rtl::OUString & ServiceName) throw (css::uno::RuntimeException)\n{\n uno::Sequence< ::rtl::OUString > aSeq = getSupportedServiceNames();\n\n if (aSeq[0].equals(ServiceName))\n return sal_True;\n\n return sal_False;\n}\n\n}}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\navoid deleting before a use (bnc#693200)\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"ShapeContextHandler.hxx\"\n#include \"oox\/vml\/vmldrawingfragment.hxx\"\n#include \"oox\/vml\/vmlshape.hxx\"\n#include \"oox\/vml\/vmlshapecontainer.hxx\"\n\nnamespace oox { namespace shape {\n\nusing namespace ::com::sun::star;\nusing namespace core;\nusing namespace drawingml;\n\n::rtl::OUString SAL_CALL ShapeContextHandler_getImplementationName()\n{\n return CREATE_OUSTRING( \"com.sun.star.comp.oox.ShapeContextHandler\" );\n}\n\nuno::Sequence< ::rtl::OUString > SAL_CALL\nShapeContextHandler_getSupportedServiceNames()\n{\n uno::Sequence< ::rtl::OUString > s(1);\n s[0] = CREATE_OUSTRING( \"com.sun.star.xml.sax.FastShapeContextHandler\" );\n return s;\n}\n\nuno::Reference< uno::XInterface > SAL_CALL\nShapeContextHandler_createInstance( const uno::Reference< uno::XComponentContext > & context)\n SAL_THROW((uno::Exception))\n{\n return static_cast< ::cppu::OWeakObject* >( new ShapeContextHandler(context) );\n}\n\n\nShapeContextHandler::ShapeContextHandler\n(uno::Reference< uno::XComponentContext > const & context) :\nmnStartToken(0), m_xContext(context)\n{\n try\n {\n mxFilterBase.set( new ShapeFilterBase(context) );\n }\n catch( uno::Exception& )\n {\n }\n}\n\nShapeContextHandler::~ShapeContextHandler()\n{\n}\n\nuno::Reference\nShapeContextHandler::getGraphicShapeContext(::sal_Int32 Element )\n{\n if (! mxGraphicShapeContext.is())\n {\n FragmentHandlerRef rFragmentHandler\n (new ShapeFragmentHandler(*mxFilterBase, msRelationFragmentPath));\n ShapePtr pMasterShape;\n\n switch (Element & 0xffff)\n {\n case XML_graphic:\n mpShape.reset(new Shape(\"com.sun.star.drawing.GraphicObjectShape\" ));\n mxGraphicShapeContext.set\n (new GraphicalObjectFrameContext(*rFragmentHandler, pMasterShape, mpShape, true));\n break;\n case XML_pic:\n mpShape.reset(new Shape(\"com.sun.star.drawing.GraphicObjectShape\" ));\n mxGraphicShapeContext.set\n (new GraphicShapeContext(*rFragmentHandler, pMasterShape, mpShape));\n break;\n default:\n break;\n }\n }\n\n return mxGraphicShapeContext;\n}\n\nuno::Reference\nShapeContextHandler::getDrawingShapeContext()\n{\n if (!mxDrawingFragmentHandler.is())\n {\n mpDrawing.reset( new oox::vml::Drawing( *mxFilterBase, mxDrawPage, oox::vml::VMLDRAWING_WORD ) );\n mxDrawingFragmentHandler.set\n (dynamic_cast\n (new oox::vml::DrawingFragment\n ( *mxFilterBase, msRelationFragmentPath, *mpDrawing )));\n }\n\n return mxDrawingFragmentHandler;\n}\n\nuno::Reference\nShapeContextHandler::getContextHandler()\n{\n uno::Reference xResult;\n\n switch (getNamespace( mnStartToken ))\n {\n case NMSP_doc:\n case NMSP_vml:\n xResult.set(getDrawingShapeContext());\n break;\n default:\n xResult.set(getGraphicShapeContext(mnStartToken));\n break;\n }\n\n return xResult;\n}\n\n\/\/ ::com::sun::star::xml::sax::XFastContextHandler:\nvoid SAL_CALL ShapeContextHandler::startFastElement\n(::sal_Int32 Element,\n const uno::Reference< xml::sax::XFastAttributeList > & Attribs)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n static const ::rtl::OUString sInputStream\n (RTL_CONSTASCII_USTRINGPARAM (\"InputStream\"));\n\n uno::Sequence aSeq(1);\n aSeq[0].Name = sInputStream;\n aSeq[0].Value <<= mxInputStream;\n mxFilterBase->filter(aSeq);\n\n mpThemePtr.reset(new Theme());\n\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xContextHandler->startFastElement(Element, Attribs);\n}\n\nvoid SAL_CALL ShapeContextHandler::startUnknownElement\n(const ::rtl::OUString & Namespace, const ::rtl::OUString & Name,\n const uno::Reference< xml::sax::XFastAttributeList > & Attribs)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xContextHandler->startUnknownElement(Namespace, Name, Attribs);\n}\n\nvoid SAL_CALL ShapeContextHandler::endFastElement(::sal_Int32 Element)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xContextHandler->endFastElement(Element);\n}\n\nvoid SAL_CALL ShapeContextHandler::endUnknownElement\n(const ::rtl::OUString & Namespace,\n const ::rtl::OUString & Name)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xContextHandler->endUnknownElement(Namespace, Name);\n}\n\nuno::Reference< xml::sax::XFastContextHandler > SAL_CALL\nShapeContextHandler::createFastChildContext\n(::sal_Int32 Element,\n const uno::Reference< xml::sax::XFastAttributeList > & Attribs)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference< xml::sax::XFastContextHandler > xResult;\n uno::Reference< xml::sax::XFastContextHandler > xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xResult.set(xContextHandler->createFastChildContext\n (Element, Attribs));\n\n return xResult;\n}\n\nuno::Reference< xml::sax::XFastContextHandler > SAL_CALL\nShapeContextHandler::createUnknownChildContext\n(const ::rtl::OUString & Namespace,\n const ::rtl::OUString & Name,\n const uno::Reference< xml::sax::XFastAttributeList > & Attribs)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n return xContextHandler->createUnknownChildContext\n (Namespace, Name, Attribs);\n\n return uno::Reference< xml::sax::XFastContextHandler >();\n}\n\nvoid SAL_CALL ShapeContextHandler::characters(const ::rtl::OUString & aChars)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n uno::Reference xContextHandler(getContextHandler());\n\n if (xContextHandler.is())\n xContextHandler->characters(aChars);\n}\n\n\/\/ ::com::sun::star::xml::sax::XFastShapeContextHandler:\nuno::Reference< drawing::XShape > SAL_CALL\nShapeContextHandler::getShape() throw (uno::RuntimeException)\n{\n uno::Reference< drawing::XShape > xResult;\n uno::Reference< drawing::XShapes > xShapes( mxDrawPage, uno::UNO_QUERY );\n\n if (mxFilterBase.is() && xShapes.is())\n {\n if ( getContextHandler() == getDrawingShapeContext() )\n {\n mpDrawing->finalizeFragmentImport();\n if( const ::oox::vml::ShapeBase* pShape = mpDrawing->getShapes().getFirstShape() )\n {\n xResult = pShape->convertAndInsert( xShapes );\n mpDrawing->getShapes( ).clearShapes( );\n }\n }\n else if (mpShape.get() != NULL)\n {\n basegfx::B2DHomMatrix aTransformation;\n mpShape->addShape(*mxFilterBase, mpThemePtr.get(), xShapes, aTransformation);\n xResult.set(mpShape->getXShape());\n mxGraphicShapeContext.clear( );\n }\n }\n\n return xResult;\n}\n\ncss::uno::Reference< css::drawing::XDrawPage > SAL_CALL\nShapeContextHandler::getDrawPage() throw (css::uno::RuntimeException)\n{\n return mxDrawPage;\n}\n\nvoid SAL_CALL ShapeContextHandler::setDrawPage\n(const css::uno::Reference< css::drawing::XDrawPage > & the_value)\n throw (css::uno::RuntimeException)\n{\n mxDrawPage = the_value;\n}\n\ncss::uno::Reference< css::frame::XModel > SAL_CALL\nShapeContextHandler::getModel() throw (css::uno::RuntimeException)\n{\n if( !mxFilterBase.is() )\n throw uno::RuntimeException();\n return mxFilterBase->getModel();\n}\n\nvoid SAL_CALL ShapeContextHandler::setModel\n(const css::uno::Reference< css::frame::XModel > & the_value)\n throw (css::uno::RuntimeException)\n{\n if( !mxFilterBase.is() )\n throw uno::RuntimeException();\n uno::Reference xComp(the_value, uno::UNO_QUERY_THROW);\n mxFilterBase->setTargetDocument(xComp);\n}\n\nuno::Reference< io::XInputStream > SAL_CALL\nShapeContextHandler::getInputStream() throw (uno::RuntimeException)\n{\n return mxInputStream;\n}\n\nvoid SAL_CALL ShapeContextHandler::setInputStream\n(const uno::Reference< io::XInputStream > & the_value)\n throw (uno::RuntimeException)\n{\n mxInputStream = the_value;\n}\n\n::rtl::OUString SAL_CALL ShapeContextHandler::getRelationFragmentPath()\n throw (uno::RuntimeException)\n{\n return msRelationFragmentPath;\n}\n\nvoid SAL_CALL ShapeContextHandler::setRelationFragmentPath\n(const ::rtl::OUString & the_value)\n throw (uno::RuntimeException)\n{\n msRelationFragmentPath = the_value;\n}\n\n::sal_Int32 SAL_CALL ShapeContextHandler::getStartToken() throw (::com::sun::star::uno::RuntimeException)\n{\n return mnStartToken;\n}\n\nvoid SAL_CALL ShapeContextHandler::setStartToken( ::sal_Int32 _starttoken ) throw (::com::sun::star::uno::RuntimeException)\n{\n mnStartToken = _starttoken;\n\n\n}\n\n::rtl::OUString ShapeContextHandler::getImplementationName()\n throw (css::uno::RuntimeException)\n{\n return ShapeContextHandler_getImplementationName();\n}\n\nuno::Sequence< ::rtl::OUString > ShapeContextHandler::getSupportedServiceNames()\n throw (css::uno::RuntimeException)\n{\n return ShapeContextHandler_getSupportedServiceNames();\n}\n\n::sal_Bool SAL_CALL ShapeContextHandler::supportsService\n(const ::rtl::OUString & ServiceName) throw (css::uno::RuntimeException)\n{\n uno::Sequence< ::rtl::OUString > aSeq = getSupportedServiceNames();\n\n if (aSeq[0].equals(ServiceName))\n return sal_True;\n\n return sal_False;\n}\n\n}}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*\n * Licensed under the MIT License (MIT)\n *\n * Copyright (c) 2013 AudioScience Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * avdecc_cmd_line_main.cpp\n *\n * AVDECC command line main implementation used for testing command line interface.\n *\/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \"cmd_line.h\"\n#if defined(__MACH__)\n#include \n#include \n#elif defined(__linux__)\n#include \n#include \n#endif\n\n#if defined(__MACH__) || defined(__linux__)\n#include \n#else\n#include \"getopt.h\"\n#endif\n\nusing namespace std;\n\nextern \"C\" void notification_callback(void *user_obj, int32_t notification_type, uint64_t guid, uint16_t cmd_type,\n uint16_t desc_type, uint16_t desc_index, uint32_t cmd_status,\n void *notification_id)\n{\n if(notification_type == avdecc_lib::COMMAND_TIMEOUT || notification_type == avdecc_lib::RESPONSE_RECEIVED)\n {\n const char *cmd_name;\n const char *desc_name;\n const char *cmd_status_name;\n\n if(cmd_type < avdecc_lib::CMD_LOOKUP)\n {\n cmd_name = cmd_line::utility->aem_cmd_value_to_name(cmd_type);\n desc_name = cmd_line::utility->aem_desc_value_to_name(desc_type);\n cmd_status_name = cmd_line::utility->aem_cmd_status_value_to_name(cmd_status);\n }\n else\n {\n cmd_name = cmd_line::utility->acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP);\n desc_name = \"NULL\";\n cmd_status_name = cmd_line::utility->acmp_cmd_status_value_to_name(cmd_status);\n }\n\n printf(\"\\n[NOTIFICATION] (%s, 0x%llx, %s, %s, %d, %s, %p)\\n\",\n cmd_line::utility->notification_value_to_name(notification_type),\n guid,\n cmd_name,\n desc_name,\n desc_index,\n cmd_status_name,\n notification_id);\n }\n else\n {\n printf(\"\\n[NOTIFICATION] (%s, 0x%llx, %d, %d, %d, %d, %p)\\n\",\n cmd_line::utility->notification_value_to_name(notification_type),\n guid,\n cmd_type,\n desc_type,\n desc_index,\n cmd_status,\n notification_id);\n }\n}\n\nextern \"C\" void log_callback(void *user_obj, int32_t log_level, const char *log_msg, int32_t time_stamp_ms)\n{\n printf(\"\\n[LOG] %s (%s)\\n\", cmd_line::utility->logging_level_value_to_name(log_level), log_msg);\n}\n\nstatic void usage(char *argv[])\n{\n std::cerr << \"Usage: \" << argv[0] << \" [-d] [-i interface]\" << std::endl;\n std::cerr << \" -t : Sets test mode which disables checks\" << std::endl;\n std::cerr << \" -i interface : Sets the name of the interface to use\" << std::endl;\n exit(1);\n}\n\nint main(int argc, char *argv[])\n{\n bool test_mode = false;\n int error = 0;\n char *interface = NULL;\n int c = 0;\n while ((c = getopt(argc, argv, \"ti:\")) != -1) {\n switch (c) {\n case 't':\n test_mode = true;\n break;\n case 'i':\n interface = optarg;\n break;\n case ':':\n fprintf(stderr, \"Option -%c requires an operand\\n\", optopt);\n error++;\n break;\n case '?':\n fprintf(stderr, \"Unrecognized option: '-%c'\\n\", optopt);\n error++;\n break;\n }\n }\n\n for ( ; optind < argc; optind++) {\n error++; \/\/ Unused arguments\n }\n\n if (error)\n {\n usage(argv);\n }\n\n if (test_mode)\n {\n \/\/ Ensure that stdout is not buffered\n setvbuf(stdout, NULL, _IOLBF, 0);\n }\n\n cmd_line *avdecc_cmd_line_ref = new cmd_line(notification_callback, log_callback, test_mode, interface);\n\n std::vector input_argv;\n size_t pos = 0;\n bool done = false;\n bool is_input_valid = false;\n std::string cmd_input_orig;\n#if defined(__MACH__) || defined(__linux__)\n char* input, shell_prompt[100];\n#endif\n\n\n std::cout << \"\\nEnter \\\"help\\\" for a list of valid commands.\" << std::endl;\n\n while(!done)\n {\n#if defined(__MACH__) || defined(__linux__)\n snprintf(shell_prompt, sizeof(shell_prompt), \"$ \");\n input = readline(shell_prompt);\n\n if (!input)\n break;\n if (strlen(input) == 0)\n continue;\n std::string cmd_input(input);\n cmd_input_orig = cmd_input;\n add_history(input);\n#else \n std::string cmd_input;\n printf(\"\\n>\");\n std::getline(std::cin, cmd_input);\n cmd_input_orig = cmd_input;\n#endif\n\n while((pos = cmd_input.find(\" \")) != std::string::npos)\n {\n if (pos)\n input_argv.push_back(cmd_input.substr(0, pos));\n\n cmd_input.erase(0, pos + 1);\n }\n\n if(cmd_input != \" \")\n {\n input_argv.push_back(cmd_input);\n }\n\n if(avdecc_cmd_line_ref->is_output_redirected())\n {\n std::cout << \"\\n> \" << cmd_input_orig << std::endl;\n }\n\n done = avdecc_cmd_line_ref->handle(input_argv);\n\n is_input_valid = false;\n input_argv.clear();\n#if defined(__MACH__) || defined(__linux__)\n free(input);\n#endif\n }\n\n delete avdecc_cmd_line_ref;\n return 0;\n}\nUse the stack rather than heap for variable that doesn't go out of scope.\/*\n * Licensed under the MIT License (MIT)\n *\n * Copyright (c) 2013 AudioScience Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * avdecc_cmd_line_main.cpp\n *\n * AVDECC command line main implementation used for testing command line interface.\n *\/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \"cmd_line.h\"\n#if defined(__MACH__)\n#include \n#include \n#elif defined(__linux__)\n#include \n#include \n#endif\n\n#if defined(__MACH__) || defined(__linux__)\n#include \n#else\n#include \"getopt.h\"\n#endif\n\nusing namespace std;\n\nextern \"C\" void notification_callback(void *user_obj, int32_t notification_type, uint64_t guid, uint16_t cmd_type,\n uint16_t desc_type, uint16_t desc_index, uint32_t cmd_status,\n void *notification_id)\n{\n if(notification_type == avdecc_lib::COMMAND_TIMEOUT || notification_type == avdecc_lib::RESPONSE_RECEIVED)\n {\n const char *cmd_name;\n const char *desc_name;\n const char *cmd_status_name;\n\n if(cmd_type < avdecc_lib::CMD_LOOKUP)\n {\n cmd_name = cmd_line::utility->aem_cmd_value_to_name(cmd_type);\n desc_name = cmd_line::utility->aem_desc_value_to_name(desc_type);\n cmd_status_name = cmd_line::utility->aem_cmd_status_value_to_name(cmd_status);\n }\n else\n {\n cmd_name = cmd_line::utility->acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP);\n desc_name = \"NULL\";\n cmd_status_name = cmd_line::utility->acmp_cmd_status_value_to_name(cmd_status);\n }\n\n printf(\"\\n[NOTIFICATION] (%s, 0x%llx, %s, %s, %d, %s, %p)\\n\",\n cmd_line::utility->notification_value_to_name(notification_type),\n guid,\n cmd_name,\n desc_name,\n desc_index,\n cmd_status_name,\n notification_id);\n }\n else\n {\n printf(\"\\n[NOTIFICATION] (%s, 0x%llx, %d, %d, %d, %d, %p)\\n\",\n cmd_line::utility->notification_value_to_name(notification_type),\n guid,\n cmd_type,\n desc_type,\n desc_index,\n cmd_status,\n notification_id);\n }\n}\n\nextern \"C\" void log_callback(void *user_obj, int32_t log_level, const char *log_msg, int32_t time_stamp_ms)\n{\n printf(\"\\n[LOG] %s (%s)\\n\", cmd_line::utility->logging_level_value_to_name(log_level), log_msg);\n}\n\nstatic void usage(char *argv[])\n{\n std::cerr << \"Usage: \" << argv[0] << \" [-d] [-i interface]\" << std::endl;\n std::cerr << \" -t : Sets test mode which disables checks\" << std::endl;\n std::cerr << \" -i interface : Sets the name of the interface to use\" << std::endl;\n exit(1);\n}\n\nint main(int argc, char *argv[])\n{\n bool test_mode = false;\n int error = 0;\n char *interface = NULL;\n int c = 0;\n while ((c = getopt(argc, argv, \"ti:\")) != -1) {\n switch (c) {\n case 't':\n test_mode = true;\n break;\n case 'i':\n interface = optarg;\n break;\n case ':':\n fprintf(stderr, \"Option -%c requires an operand\\n\", optopt);\n error++;\n break;\n case '?':\n fprintf(stderr, \"Unrecognized option: '-%c'\\n\", optopt);\n error++;\n break;\n }\n }\n\n for ( ; optind < argc; optind++) {\n error++; \/\/ Unused arguments\n }\n\n if (error)\n {\n usage(argv);\n }\n\n if (test_mode)\n {\n \/\/ Ensure that stdout is not buffered\n setvbuf(stdout, NULL, _IOLBF, 0);\n }\n\n cmd_line avdecc_cmd_line_ref(notification_callback, log_callback, test_mode, interface);\n\n std::vector input_argv;\n size_t pos = 0;\n bool done = false;\n bool is_input_valid = false;\n std::string cmd_input_orig;\n#if defined(__MACH__) || defined(__linux__)\n char* input, shell_prompt[100];\n#endif\n\n\n std::cout << \"\\nEnter \\\"help\\\" for a list of valid commands.\" << std::endl;\n\n while(!done)\n {\n#if defined(__MACH__) || defined(__linux__)\n snprintf(shell_prompt, sizeof(shell_prompt), \"$ \");\n input = readline(shell_prompt);\n\n if (!input)\n break;\n if (strlen(input) == 0)\n continue;\n std::string cmd_input(input);\n cmd_input_orig = cmd_input;\n add_history(input);\n#else \n std::string cmd_input;\n printf(\"\\n>\");\n std::getline(std::cin, cmd_input);\n cmd_input_orig = cmd_input;\n#endif\n\n while((pos = cmd_input.find(\" \")) != std::string::npos)\n {\n if (pos)\n input_argv.push_back(cmd_input.substr(0, pos));\n\n cmd_input.erase(0, pos + 1);\n }\n\n if(cmd_input != \" \")\n {\n input_argv.push_back(cmd_input);\n }\n\n if(avdecc_cmd_line_ref.is_output_redirected())\n {\n std::cout << \"\\n> \" << cmd_input_orig << std::endl;\n }\n\n done = avdecc_cmd_line_ref.handle(input_argv);\n\n is_input_valid = false;\n input_argv.clear();\n#if defined(__MACH__) || defined(__linux__)\n free(input);\n#endif\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"palabos3D.h\"\n#include \"palabos3D.hh\"\n#include \n#include \n\nusing namespace plb;\nusing namespace plb::descriptors;\nusing namespace std;\n\n\ntypedef double T;\ntypedef Array Velocity;\n\/\/#define DESCRIPTOR descriptors::D3Q27Descriptor\n#define DESCRIPTOR MRTD3Q19Descriptor\n typedef MRTdynamics BackgroundDynamics;\n typedef AnechoicMRTdynamics AnechoicBackgroundDynamics;\n\n\/\/ ---------------------------------------------\n\/\/ Includes of acoustics resources\n#include \"acoustics\/acoustics3D.h\"\nusing namespace plb_acoustics_3D;\n\/\/ ---------------------------------------------\n\nconst T rho0 = 1;\nconst T drho = rho0\/10;\n\nvoid writeGifs(MultiBlockLattice3D& lattice, plint iter){\n const plint nx = lattice.getNx();\n const plint ny = lattice.getNy();\n const plint nz = lattice.getNz();\n\n const plint imSize = 600;\n ImageWriter imageWriter(\"leeloo\");\n \n Box3D slice(0, nx-1, 0, ny-1, nz\/2, nz\/2);\n \/\/imageWriter.writeGif(createFileName(\"u\", iT, 6),\n \/\/*computeDensity(lattice), );\n\n imageWriter.writeGif( createFileName(\"rho\", iter, 6),\n *computeDensity(lattice, slice), \n (T) rho0 - drho\/1000000, (T) rho0 + drho\/1000000, imSize, imSize);\n}\n\nvoid writeVTK(MultiBlockLattice3D& lattice, plint iter){\n VtkImageOutput3D vtkOut(createFileName(\"vtk\", iter, 6), 1.);\n vtkOut.writeData(*computeDensity(lattice), \"density\", 1.);\n vtkOut.writeData<3,float>(*computeVelocity(lattice), \"velocity\", 1.);\n}\n\nint main(int argc, char **argv){\n plbInit(&argc, &argv);\n std::string fNameOut = \"tmp\";\n\n const plint nx = 200;\n const plint ny = 200;\n const plint nz = 200;\n const T lattice_speed_sound = 1\/sqrt(3);\n\n const T omega = 1.985;\n const plint maxT = 120000;\n\n Array u0(0, 0, 0);\n\n global::directories().setOutputDir(fNameOut+\"\/\");\n\n \/\/Build geometry\n Array centerLB(nx\/2, ny\/2, nz\/2);\n \/\/TriangleSet triangleSet(\"Duto_Fechado.STL\");\n \/\/Array center(param.cx, param.cy, param.cz);\n TriangleSet triangleSet;\n pcout << \"construindo o duto\" << std::endl;\n \/*\n (Array const& inletCenter, T externRadius, T internRadius,\n T length, plint nAxial, plint nCirc)\n *\/\n triangleSet = constructDuct(centerLB, (T) 30, (T) 26, (T) 50, (plint) 10, (plint) 50);\n\n \/\/triangleSet = constructSphere(centerLB, (T) 10, (plint)40);\n \/*TriangleSet triangleSet(\"duto_fechado.STL\");\n triangleSet.translate(centerLB);*\/\n \/\/ rotate: Z, X, Y in radians\n \/\/triangleSet.rotate((T) 0, (T) 0, (T) 0); \n \/\/triangleSet.scale((T) 3.95253e+2);\n\n \/\/ tube to more efficient data structures that are internally used by palabos.\n \/\/ The TriangleBoundary3D structure will be later used to assign proper boundary conditions.\n plint borderWidth = 1; \/\/ Because the Guo boundary condition acts in a one-cell layer.\n \/\/ Requirement: margin>=borderWidth.\n plint margin = 1; \/\/ Extra margin of allocated cells around the obstacle.\n plint extraLayer = 0; \/\/ Make the bounding box larger; for visualization purposes\n \/\/ only. For the simulation, it is OK to have extraLayer=0.\n plint xDirection = 0;\n DEFscaledMesh defMesh(triangleSet, 0, xDirection, margin, Dot3D(0, 0, 0));\n defMesh.setDx((T) 1.);\n\n pcout << \"Valor do Dx: \" << defMesh.getDx() << std::endl;\n Array physical_position = defMesh.getPhysicalLocation();\n pcout << \"posicao fisica em x: \" << physical_position[0] << std::endl;\n pcout << \"posicao fisica em y: \" << physical_position[1] << std::endl;\n pcout << \"posicao fisica em z: \" << physical_position[2] << std::endl;\n \/\/Array< T, 3 > position_lattice(50, ny\/2, nz\/2);\n \/\/defMesh.setPhysicalLocation(position_lattice);\n Array physical_position_c = defMesh.getPhysicalLocation();\n pcout << \"posicao fisica em x_c: \" << physical_position_c[0] << std::endl;\n pcout << \"posicao fisica em y_c: \" << physical_position_c[1] << std::endl;\n pcout << \"posicao fisica em z_c: \" << physical_position_c[2] << std::endl;\n defMesh.getMesh().inflate();\n TriangleBoundary3D boundary(defMesh);\n\n boundary.getMesh().writeBinarySTL(\"duct.stl\");\n pcout << \"Number of triangles: \" << boundary.getMesh().getNumTriangles() << std::endl;\n \/\/ handled by the following voxelization process.\n pcout << std::endl << \"Voxelizing the domain.\" << std::endl;\n const int flowType = voxelFlag::outside;\n const plint extendedEnvelopeWidth = 2;\n const plint blockSize = 0; \/\/ Zero means: no sparse representation.\n \/\/ Because the Guo boundary condition needs 2-cell neighbor access.\n Box3D full_domain(0, nx-1, 0, ny-1, 0, nz-1);\n VoxelizedDomain3D voxelizedDomain (\n boundary, flowType, full_domain, borderWidth, extendedEnvelopeWidth, blockSize);\n pcout << getMultiBlockInfo(voxelizedDomain.getVoxelMatrix()) << std::endl;\n\n \/\/ Build lattice and set default dynamics\n \/\/-------------------------------------\n MultiBlockLattice3D *lattice = \n new MultiBlockLattice3D(voxelizedDomain.getVoxelMatrix());\n\n \/\/ Setting anechoic dynamics like this way\n defineDynamics(*lattice, lattice->getBoundingBox(),\n new AnechoicBackgroundDynamics(omega));\n defineDynamics(*lattice, lattice->getBoundingBox(),\n new BackgroundDynamics(omega));\n \/\/-------------------------------------\n\n \/\/Set geometry in lattice\n \/\/ The Guo off *lattice boundary condition is set up.\n pcout << \"Creating boundary condition.\" << std::endl;\n \/*BoundaryProfiles3D profiles;\n \n bool useAllDirections = true; \/\/ Extrapolation scheme for the off *lattice boundary condition.\n GuoOffLatticeModel3D* model =\n new GuoOffLatticeModel3D (\n new TriangleFlowShape3D > (\n voxelizedDomain.getBoundary(), profiles),\n flowType, useAllDirections );\n bool useRegularized = true;\n \/\/ Use an off *lattice boundary condition which is closer in spirit to\n \/\/ regularized boundary conditions.\n model->selectUseRegularizedModel(useRegularized);*\/\n\n \/* BoundaryProfiles3D profiles;\n bool useAllDirections=true;\n OffLatticeModel3D* offLatticeModel=0;\n profiles.setWallProfile(new NoSlipProfile3D);\n offLatticeModel =\n new GuoOffLatticeModel3D (\n new TriangleFlowShape3D >(voxelizedDomain.getBoundary(), profiles),\n flowType, useAllDirections );\n offLatticeModel->setVelIsJ(false);\n OffLatticeBoundaryCondition3D *boundaryCondition;\n boundaryCondition = new OffLatticeBoundaryCondition3D(\n offLatticeModel, voxelizedDomain, *lattice);\n boundaryCondition->insert();*\/\n\n\n\n\n\n\n \/\/Set geometry in lattice\n \/\/ The Guo off *lattice boundary condition is set up.\n pcout << \"Creating boundary condition.\" << std::endl;\n BoundaryProfiles3D profiles;\n \/\/profiles.setWallProfile(new NoSlipProfile3D);\n \n bool useAllDirections = true; \/\/ Extrapolation scheme for the off *lattice boundary condition.\n GuoOffLatticeModel3D* model =\n new GuoOffLatticeModel3D (\n new TriangleFlowShape3D > (\n voxelizedDomain.getBoundary(), profiles),\n flowType, useAllDirections );\n bool useRegularized = true;\n \/\/ Use an off *lattice boundary condition which is closer in spirit to\n \/\/ regularized boundary conditions.\n model->selectUseRegularizedModel(useRegularized);\n \/\/ ---\n OffLatticeBoundaryCondition3D boundaryCondition (\n model, voxelizedDomain, *lattice);\n boundaryCondition.insert();\n defineDynamics(*lattice, voxelizedDomain.getVoxelMatrix(),\n lattice->getBoundingBox(), new NoDynamics(-999), voxelFlag::inside);\n\n pcout << \"Creation of the lattice.\" << endl;\n\n \/\/ Switch off periodicity.\n lattice->periodicity().toggleAll(false);\n\n pcout << \"Initilization of rho and u.\" << endl;\n initializeAtEquilibrium( *lattice, lattice->getBoundingBox(), rho0 , u0 );\n \n T rhoBar_target = 0;\n const T mach_number = 0.2;\n const T velocity_flow = mach_number*lattice_speed_sound;\n Array j_target(velocity_flow, 0, 0);\n T size_anechoic_buffer = 20;\n \/*defineAnechoicMRTBoards(nx, ny, nz, lattice, size_anechoic_buffer,\n omega, j_target, j_target, j_target, j_target, j_target, j_target,\n rhoBar_target);*\/\n\n lattice->initialize();\n\n pcout << std::endl << \"Voxelizing the domain.\" << std::endl;\n\n pcout << \"Simulation begins\" << endl;\n\n plb_ofstream history_pressures(\"tmp\/history_pressures.dat\");\n plb_ofstream history_velocities_x(\"tmp\/history_velocities_x.dat\");\n plb_ofstream history_velocities_y(\"tmp\/history_velocities_y.dat\");\n plb_ofstream history_velocities_z(\"tmp\/history_velocities_z.dat\");\n for (plint iT=0; iT0) {\n pcout << \"Iteration \" << iT << endl;\n \/\/writeGifs(lattice,iT);\n writeVTK(*lattice, iT);\n }\n\n history_pressures << setprecision(10) << lattice->get(nx\/2+30, ny\/2+30, nz\/2+30).computeDensity() - rho0 << endl;\n Array velocities;\n lattice->get(nx\/2+30, ny\/2+30, nz\/2+30).computeVelocity(velocities);\n history_velocities_x << setprecision(10) << velocities[0]\/lattice_speed_sound << endl;\n history_velocities_y << setprecision(10) << velocities[1]\/lattice_speed_sound << endl;\n history_velocities_z << setprecision(10) << velocities[2]\/lattice_speed_sound << endl;\n lattice->collideAndStream();\n\n }\n\n pcout << \"End of simulation at iteration \" << endl;\n}\nDuct with big size#include \"palabos3D.h\"\n#include \"palabos3D.hh\"\n#include \n#include \n\nusing namespace plb;\nusing namespace plb::descriptors;\nusing namespace std;\n\n\ntypedef double T;\ntypedef Array Velocity;\n\/\/#define DESCRIPTOR descriptors::D3Q27Descriptor\n#define DESCRIPTOR MRTD3Q19Descriptor\n typedef MRTdynamics BackgroundDynamics;\n typedef AnechoicMRTdynamics AnechoicBackgroundDynamics;\n\n\/\/ ---------------------------------------------\n\/\/ Includes of acoustics resources\n#include \"acoustics\/acoustics3D.h\"\nusing namespace plb_acoustics_3D;\n\/\/ ---------------------------------------------\n\nconst T rho0 = 1;\nconst T drho = rho0\/10;\n\nvoid writeGifs(MultiBlockLattice3D& lattice, plint iter){\n const plint nx = lattice.getNx();\n const plint ny = lattice.getNy();\n const plint nz = lattice.getNz();\n\n const plint imSize = 600;\n ImageWriter imageWriter(\"leeloo\");\n \n Box3D slice(0, nx-1, 0, ny-1, nz\/2, nz\/2);\n \/\/imageWriter.writeGif(createFileName(\"u\", iT, 6),\n \/\/*computeDensity(lattice), );\n\n imageWriter.writeGif( createFileName(\"rho\", iter, 6),\n *computeDensity(lattice, slice), \n (T) rho0 - drho\/1000000, (T) rho0 + drho\/1000000, imSize, imSize);\n}\n\nvoid writeVTK(MultiBlockLattice3D& lattice, plint iter){\n VtkImageOutput3D vtkOut(createFileName(\"vtk\", iter, 6), 1.);\n vtkOut.writeData(*computeDensity(lattice), \"density\", 1.);\n vtkOut.writeData<3,float>(*computeVelocity(lattice), \"velocity\", 1.);\n}\n\nint main(int argc, char **argv){\n plbInit(&argc, &argv);\n std::string fNameOut = \"tmp\";\n\n const plint nx = 300;\n const plint ny = 200;\n const plint nz = 200;\n const T lattice_speed_sound = 1\/sqrt(3);\n\n const T omega = 1.985;\n const plint maxT = 120000;\n\n Array u0(0, 0, 0);\n\n global::directories().setOutputDir(fNameOut+\"\/\");\n\n \/\/Build geometry\n Array centerLB(10, ny\/2, nz\/2);\n \/\/TriangleSet triangleSet(\"Duto_Fechado.STL\");\n \/\/Array center(param.cx, param.cy, param.cz);\n TriangleSet triangleSet;\n pcout << \"construindo o duto\" << std::endl;\n \/*\n (Array const& inletCenter, T externRadius, T internRadius,\n T length, plint nAxial, plint nCirc)\n *\/\n T thickness_duct = 4;\n T radius = 20;\n triangleSet = constructDuct(centerLB, radius + thickness_duct, radius\n , (T) 250, (plint) 10, (plint) 50);\n\n \/\/triangleSet = constructSphere(centerLB, (T) 10, (plint)40);\n \/*TriangleSet triangleSet(\"duto_fechado.STL\");\n triangleSet.translate(centerLB);*\/\n \/\/ rotate: Z, X, Y in radians\n \/\/triangleSet.rotate((T) 0, (T) 0, (T) 0); \n \/\/triangleSet.scale((T) 3.95253e+2);\n\n \/\/ tube to more efficient data structures that are internally used by palabos.\n \/\/ The TriangleBoundary3D structure will be later used to assign proper boundary conditions.\n plint borderWidth = 1; \/\/ Because the Guo boundary condition acts in a one-cell layer.\n \/\/ Requirement: margin>=borderWidth.\n plint margin = 1; \/\/ Extra margin of allocated cells around the obstacle.\n plint extraLayer = 0; \/\/ Make the bounding box larger; for visualization purposes\n \/\/ only. For the simulation, it is OK to have extraLayer=0.\n plint xDirection = 0;\n DEFscaledMesh defMesh(triangleSet, 0, xDirection, margin, Dot3D(0, 0, 0));\n defMesh.setDx((T) 1.);\n\n pcout << \"Valor do Dx: \" << defMesh.getDx() << std::endl;\n Array physical_position = defMesh.getPhysicalLocation();\n pcout << \"posicao fisica em x: \" << physical_position[0] << std::endl;\n pcout << \"posicao fisica em y: \" << physical_position[1] << std::endl;\n pcout << \"posicao fisica em z: \" << physical_position[2] << std::endl;\n \/\/Array< T, 3 > position_lattice(50, ny\/2, nz\/2);\n \/\/defMesh.setPhysicalLocation(position_lattice);\n Array physical_position_c = defMesh.getPhysicalLocation();\n pcout << \"posicao fisica em x_c: \" << physical_position_c[0] << std::endl;\n pcout << \"posicao fisica em y_c: \" << physical_position_c[1] << std::endl;\n pcout << \"posicao fisica em z_c: \" << physical_position_c[2] << std::endl;\n defMesh.getMesh().inflate();\n TriangleBoundary3D boundary(defMesh);\n\n boundary.getMesh().writeBinarySTL(\"duct.stl\");\n pcout << \"Number of triangles: \" << boundary.getMesh().getNumTriangles() << std::endl;\n \/\/ handled by the following voxelization process.\n pcout << std::endl << \"Voxelizing the domain.\" << std::endl;\n const int flowType = voxelFlag::outside;\n const plint extendedEnvelopeWidth = 2;\n const plint blockSize = 0; \/\/ Zero means: no sparse representation.\n \/\/ Because the Guo boundary condition needs 2-cell neighbor access.\n Box3D full_domain(0, nx-1, 0, ny-1, 0, nz-1);\n VoxelizedDomain3D voxelizedDomain (\n boundary, flowType, full_domain, borderWidth, extendedEnvelopeWidth, blockSize);\n pcout << getMultiBlockInfo(voxelizedDomain.getVoxelMatrix()) << std::endl;\n\n \/\/ Build lattice and set default dynamics\n \/\/-------------------------------------\n MultiBlockLattice3D *lattice = \n new MultiBlockLattice3D(voxelizedDomain.getVoxelMatrix());\n\n \/\/ Setting anechoic dynamics like this way\n defineDynamics(*lattice, lattice->getBoundingBox(),\n new AnechoicBackgroundDynamics(omega));\n defineDynamics(*lattice, lattice->getBoundingBox(),\n new BackgroundDynamics(omega));\n \/\/-------------------------------------\n\n \/\/Set geometry in lattice\n \/\/ The Guo off *lattice boundary condition is set up.\n pcout << \"Creating boundary condition.\" << std::endl;\n \/*BoundaryProfiles3D profiles;\n \n bool useAllDirections = true; \/\/ Extrapolation scheme for the off *lattice boundary condition.\n GuoOffLatticeModel3D* model =\n new GuoOffLatticeModel3D (\n new TriangleFlowShape3D > (\n voxelizedDomain.getBoundary(), profiles),\n flowType, useAllDirections );\n bool useRegularized = true;\n \/\/ Use an off *lattice boundary condition which is closer in spirit to\n \/\/ regularized boundary conditions.\n model->selectUseRegularizedModel(useRegularized);*\/\n\n \/* BoundaryProfiles3D profiles;\n bool useAllDirections=true;\n OffLatticeModel3D* offLatticeModel=0;\n profiles.setWallProfile(new NoSlipProfile3D);\n offLatticeModel =\n new GuoOffLatticeModel3D (\n new TriangleFlowShape3D >(voxelizedDomain.getBoundary(), profiles),\n flowType, useAllDirections );\n offLatticeModel->setVelIsJ(false);\n OffLatticeBoundaryCondition3D *boundaryCondition;\n boundaryCondition = new OffLatticeBoundaryCondition3D(\n offLatticeModel, voxelizedDomain, *lattice);\n boundaryCondition->insert();*\/\n\n\n\n\n\n\n \/\/Set geometry in lattice\n \/\/ The Guo off *lattice boundary condition is set up.\n pcout << \"Creating boundary condition.\" << std::endl;\n BoundaryProfiles3D profiles;\n \/\/profiles.setWallProfile(new NoSlipProfile3D);\n \n bool useAllDirections = true; \/\/ Extrapolation scheme for the off *lattice boundary condition.\n GuoOffLatticeModel3D* model =\n new GuoOffLatticeModel3D (\n new TriangleFlowShape3D > (\n voxelizedDomain.getBoundary(), profiles),\n flowType, useAllDirections );\n bool useRegularized = true;\n \/\/ Use an off *lattice boundary condition which is closer in spirit to\n \/\/ regularized boundary conditions.\n model->selectUseRegularizedModel(useRegularized);\n \/\/ ---\n OffLatticeBoundaryCondition3D boundaryCondition (\n model, voxelizedDomain, *lattice);\n boundaryCondition.insert();\n defineDynamics(*lattice, voxelizedDomain.getVoxelMatrix(),\n lattice->getBoundingBox(), new NoDynamics(-999), voxelFlag::inside);\n\n pcout << \"Creation of the lattice.\" << endl;\n\n \/\/ Switch off periodicity.\n lattice->periodicity().toggleAll(false);\n\n pcout << \"Initilization of rho and u.\" << endl;\n initializeAtEquilibrium( *lattice, lattice->getBoundingBox(), rho0 , u0 );\n \n T rhoBar_target = 0;\n const T mach_number = 0.2;\n const T velocity_flow = mach_number*lattice_speed_sound;\n Array j_target(velocity_flow, 0, 0);\n T size_anechoic_buffer = 20;\n \/*defineAnechoicMRTBoards(nx, ny, nz, lattice, size_anechoic_buffer,\n omega, j_target, j_target, j_target, j_target, j_target, j_target,\n rhoBar_target);*\/\n\n lattice->initialize();\n\n pcout << std::endl << \"Voxelizing the domain.\" << std::endl;\n\n pcout << \"Simulation begins\" << endl;\n\n plb_ofstream history_pressures(\"tmp\/history_pressures.dat\");\n plb_ofstream history_velocities_x(\"tmp\/history_velocities_x.dat\");\n plb_ofstream history_velocities_y(\"tmp\/history_velocities_y.dat\");\n plb_ofstream history_velocities_z(\"tmp\/history_velocities_z.dat\");\n for (plint iT=0; iT0) {\n pcout << \"Iteration \" << iT << endl;\n \/\/writeGifs(lattice,iT);\n writeVTK(*lattice, iT);\n }\n\n history_pressures << setprecision(10) << lattice->get(nx\/2+30, ny\/2+30, nz\/2+30).computeDensity() - rho0 << endl;\n Array velocities;\n lattice->get(nx\/2+30, ny\/2+30, nz\/2+30).computeVelocity(velocities);\n history_velocities_x << setprecision(10) << velocities[0]\/lattice_speed_sound << endl;\n history_velocities_y << setprecision(10) << velocities[1]\/lattice_speed_sound << endl;\n history_velocities_z << setprecision(10) << velocities[2]\/lattice_speed_sound << endl;\n lattice->collideAndStream();\n\n }\n\n pcout << \"End of simulation at iteration \" << endl;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 Pelagicore AB\n * All rights reserved.\n *\/\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \n\n#include \"abstractcontroller.h\"\n#include \"ipcmessage.h\"\n\nclass MockAbstractController :\n public AbstractController\n{\npublic:\n MOCK_METHOD0(runApp, int());\n MOCK_METHOD0(killApp, void());\n MOCK_METHOD2(setEnvironmentVariable, void(const std::string &, const std::string &));\n MOCK_METHOD1(systemCall, void(const std::string &));\n};\n\nusing ::testing::InSequence;\nusing ::testing::Return;\nusing ::testing::NiceMock;\n\nTEST(IPCMessageTest, TestShouldCallRunAppAndKillApp) {\n MockAbstractController controller;\n IPCMessage message(controller);\n\n std::string runAppCmd(\"1\");\n std::string killAppCmd(\"2\");\n\n \/\/ The calls should be made in the specific order as below:\n {\n InSequence sequence;\n EXPECT_CALL(controller, runApp()).Times(1);\n EXPECT_CALL(controller, killApp()).Times(1);\n }\n\n int status;\n message.handleMessage(runAppCmd, &status);\n message.handleMessage(killAppCmd, &status);\n}\n\nTEST(IPCMessageTest, TestShouldCallSystemCallWithExpectedArg) {\n MockAbstractController controller;\n IPCMessage message(controller);\n\n std::string systemCallCmd(\"4 this is a system call\");\n\n std::string expectedArgument(\"this is a system call\");\n EXPECT_CALL(controller, systemCall(expectedArgument)).Times(1);\n\n int status;\n message.handleMessage(systemCallCmd, &status);\n}\n\nTEST(IPCMessageTest, TestShouldCallSetEnvironmentVariableWithExpectedArgs) {\n MockAbstractController controller;\n IPCMessage message(controller);\n\n std::string setEnvironmentVariableCmd(\"3 THE_VARIABLE this is the value\");\n\n std::string expectedVariable(\"THE_VARIABLE\");\n std::string expectedValue(\"this is the value\");\n EXPECT_CALL(controller, setEnvironmentVariable(expectedVariable, expectedValue)).Times(1);\n\n int status;\n message.handleMessage(setEnvironmentVariableCmd, &status);\n}\n\nTEST(IPCMessageTest, TestShouldSetErrorFlagAsExpected) {\n NiceMock controller;\n IPCMessage message(controller);\n\n int status = 123;\n message.handleMessage(std::string(\"4 valid message\"), &status);\n EXPECT_EQ(status, 0);\n\n status = 123;\n message.handleMessage(std::string(\"invalid message\"), &status);\n EXPECT_EQ(status, -1);\n}\n\nTEST(IPCMessageTest, TestSendShouldReturnExpectedValue) {\n NiceMock controller;\n IPCMessage message(controller);\n\n std::string validMessage(\"4 valid message\");\n std::string invalidMessage(\"invalid message\");\n std::string killAppMessage(\"2\");\n\n int status;\n bool returnVal;\n\n returnVal = message.handleMessage(validMessage, &status);\n EXPECT_EQ(returnVal, true);\n\n returnVal = message.handleMessage(invalidMessage, &status);\n EXPECT_EQ(returnVal, true);\n\n returnVal = message.handleMessage(killAppMessage, &status);\n EXPECT_EQ(returnVal, false);\n}\nipcmessage_unittest.cpp: Added comments explaining the test cases.\/*\n * Copyright (C) 2014 Pelagicore AB\n * All rights reserved.\n *\/\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \n\n#include \"abstractcontroller.h\"\n#include \"ipcmessage.h\"\n\nclass MockAbstractController :\n public AbstractController\n{\npublic:\n MOCK_METHOD0(runApp, int());\n MOCK_METHOD0(killApp, void());\n MOCK_METHOD2(setEnvironmentVariable, void(const std::string &, const std::string &));\n MOCK_METHOD1(systemCall, void(const std::string &));\n};\n\nusing ::testing::InSequence;\nusing ::testing::Return;\nusing ::testing::NiceMock;\n\n\/*! Test that Controller::runApp and Controller::killApp are called by IPCMessage\n * when the corresponding messages are passed to IPCMessage\n *\/\nTEST(IPCMessageTest, TestShouldCallRunAppAndKillApp) {\n MockAbstractController controller;\n IPCMessage message(controller);\n\n std::string runAppCmd(\"1\");\n std::string killAppCmd(\"2\");\n\n \/\/ The calls should be made in the specific order as below:\n {\n InSequence sequence;\n EXPECT_CALL(controller, runApp()).Times(1);\n EXPECT_CALL(controller, killApp()).Times(1);\n }\n\n int status;\n message.handleMessage(runAppCmd, &status);\n message.handleMessage(killAppCmd, &status);\n}\n\n\/*! Test that Controller::systemCall is called with the expected argument\n * by IPCMessage.\n *\/\nTEST(IPCMessageTest, TestShouldCallSystemCallWithExpectedArg) {\n MockAbstractController controller;\n IPCMessage message(controller);\n\n std::string systemCallCmd(\"4 this is a system call\");\n\n std::string expectedArgument(\"this is a system call\");\n EXPECT_CALL(controller, systemCall(expectedArgument)).Times(1);\n\n int status;\n message.handleMessage(systemCallCmd, &status);\n}\n\n\/*! Test that Controller::setEnvironmentVariable is called with the expected\n * arguments by IPCMessage.\n *\/\nTEST(IPCMessageTest, TestShouldCallSetEnvironmentVariableWithExpectedArgs) {\n MockAbstractController controller;\n IPCMessage message(controller);\n\n std::string setEnvironmentVariableCmd(\"3 THE_VARIABLE this is the value\");\n\n std::string expectedVariable(\"THE_VARIABLE\");\n std::string expectedValue(\"this is the value\");\n EXPECT_CALL(controller, setEnvironmentVariable(expectedVariable, expectedValue)).Times(1);\n\n int status;\n message.handleMessage(setEnvironmentVariableCmd, &status);\n}\n\n\/*! Test that IPCMessage sets status flag as expeced on a valid message and\n * an invalid message.\n *\/\nTEST(IPCMessageTest, TestShouldSetErrorFlagAsExpected) {\n NiceMock controller;\n IPCMessage message(controller);\n\n int status = 123;\n message.handleMessage(std::string(\"4 valid message\"), &status);\n EXPECT_EQ(status, 0);\n\n status = 123;\n message.handleMessage(std::string(\"invalid message\"), &status);\n EXPECT_EQ(status, -1);\n}\n\n\/*! Test that IPCMessage returns the expected value. Valid and invalid messages\n * should get 'true' as a response, while a call to Controller::killApp should\n * result in 'false' as it means the IPC should stop sending more messages.\n *\/\nTEST(IPCMessageTest, TestSendShouldReturnExpectedValue) {\n NiceMock controller;\n IPCMessage message(controller);\n\n std::string validMessage(\"4 valid message\");\n std::string invalidMessage(\"invalid message\");\n std::string killAppMessage(\"2\");\n\n int status;\n bool returnVal;\n\n returnVal = message.handleMessage(validMessage, &status);\n EXPECT_EQ(returnVal, true);\n\n returnVal = message.handleMessage(invalidMessage, &status);\n EXPECT_EQ(returnVal, true);\n\n returnVal = message.handleMessage(killAppMessage, &status);\n EXPECT_EQ(returnVal, false);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace {\n bool\n verifyUser(void)\n {\n uid_t consoleUID;\n CFStringRef result = SCDynamicStoreCopyConsoleUser(NULL, &consoleUID, NULL);\n \/\/ TRUE if no user is logged in\n if (result == NULL) return true;\n CFRelease(result);\n\n return (getuid() == consoleUID);\n }\n\n void\n set(const char *name, int value)\n {\n char entry[512];\n snprintf(entry, sizeof(entry), \"keyremap4macbook.%s\", name);\n\n size_t oldlen = 0;\n size_t newlen = sizeof(value);\n if (sysctlbyname(entry, NULL, &oldlen, &value, newlen) == -1) {\n perror(\"sysctl\");\n }\n }\n}\n\n\nint\nmain(int argc, char **argv)\n{\n if (! verifyUser()) {\n fprintf(stderr, \"Permission denied\\n\");\n return 1;\n }\n\n std::ifstream ifs(\"\/Library\/org.pqrs\/KeyRemap4MacBook\/share\/reset\");\n if (! ifs) return 1;\n\n while (! ifs.eof()) {\n char line[512];\n\n ifs.getline(line, sizeof(line));\n\n char *p = strchr(line, ' ');\n if (! p) continue;\n *p = '\\0';\n\n set(line, atoi(p + 1));\n }\n\n if (argc == 2 && strcmp(argv[1]) == \"terminate\") {\n set(\"initialized\", 0);\n }\n\n return 0;\n}\nfix sysctl_reset#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace {\n bool\n verifyUser(void)\n {\n uid_t consoleUID;\n CFStringRef result = SCDynamicStoreCopyConsoleUser(NULL, &consoleUID, NULL);\n \/\/ TRUE if no user is logged in\n if (result == NULL) return true;\n CFRelease(result);\n\n return (getuid() == consoleUID);\n }\n\n void\n set(const char *name, int value)\n {\n char entry[512];\n snprintf(entry, sizeof(entry), \"keyremap4macbook.%s\", name);\n\n size_t oldlen = 0;\n size_t newlen = sizeof(value);\n if (sysctlbyname(entry, NULL, &oldlen, &value, newlen) == -1) {\n perror(\"sysctl\");\n }\n }\n}\n\n\nint\nmain(int argc, char **argv)\n{\n if (! verifyUser()) {\n fprintf(stderr, \"Permission denied\\n\");\n return 1;\n }\n\n std::ifstream ifs(\"\/Library\/org.pqrs\/KeyRemap4MacBook\/share\/reset\");\n if (! ifs) return 1;\n\n while (! ifs.eof()) {\n char line[512];\n\n ifs.getline(line, sizeof(line));\n\n char *p = strchr(line, ' ');\n if (! p) continue;\n *p = '\\0';\n\n set(line, atoi(p + 1));\n }\n\n if (argc == 2 && strcmp(argv[1], \"terminate\") == 0) {\n set(\"initialized\", 0);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/===--- SemaDecl.cpp - Swift Semantic Analysis for Declarations ----------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements semantic analysis for Swift declarations.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Sema\/SemaDecl.h\"\n#include \"swift\/Sema\/Sema.h\"\n#include \"swift\/Sema\/Scope.h\"\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/Decl.h\"\n#include \"swift\/AST\/Expr.h\"\n#include \"swift\/AST\/Type.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"llvm\/Support\/SMLoc.h\"\nusing namespace swift;\n\nSemaDecl::SemaDecl(Sema &S)\n : SemaBase(S),\n ScopeHT(new ScopeHTType()),\n CurScope(0) {\n}\n\nSemaDecl::~SemaDecl() {\n delete ScopeHT;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Name lookup.\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ AddToScope - Register the specified decl as being in the current lexical\n\/\/\/ scope.\nvoid SemaDecl::AddToScope(NamedDecl *D) {\n \/\/ If we have a shadowed variable definition, check to see if we have a\n \/\/ redefinition: two definitions in the same scope with the same name.\n std::pair Entry = ScopeHT->lookup(D->Name);\n if (Entry.second && Entry.first == CurScope->getDepth()) {\n Error(D->getLocStart(),\n \"variable declaration conflicts with previous declaration\");\n Note(ScopeHT->lookup(D->Name).second->getLocStart(),\n \"previous declaration here\");\n return;\n }\n \n ScopeHT->insert(D->Name, std::make_pair(CurScope->getDepth(), D));\n}\n\n\/\/\/ LookupName - Perform a lexical scope lookup for the specified name,\n\/\/\/ returning the active decl if found or null if not.\nNamedDecl *SemaDecl::LookupName(Identifier Name) {\n return ScopeHT->lookup(Name).second;\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Declaration handling.\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ ValidateAttributes - Check that the func\/var declaration attributes are ok.\nstatic void ValidateAttributes(DeclAttributes &Attrs, Type *Ty, SemaDecl &SD) {\n \/\/ If the decl has an infix precedence specified, then it must be a function\n \/\/ whose input is a two element tuple.\n if (Attrs.InfixPrecedence != -1) {\n bool IsError = true;\n if (FunctionType *FT = llvm::dyn_cast(Ty))\n if (TupleType *TT = llvm::dyn_cast(FT->Input))\n IsError = TT->NumFields != 2;\n if (IsError) {\n SD.Error(Attrs.LSquareLoc, \"function with 'infix' specified must take \"\n \"a two element tuple as input\");\n Attrs.InfixPrecedence = -1;\n }\n }\n}\n\nVarDecl *SemaDecl::ActOnVarDecl(llvm::SMLoc VarLoc, llvm::StringRef Name,\n Type *Ty, Expr *Init, DeclAttributes &Attrs) {\n \n \/\/ Diagnose when we don't have a type or an expression.\n if (Ty == 0 && Init == 0) {\n Error(VarLoc, \"var declaration must specify a type if no \"\n \"initializer is specified\");\n \/\/ TODO: Recover better by still creating var, but making it have 'invalid'\n \/\/ type.\n return 0;\n }\n \n \/\/ If both a type and an initializer are specified, make sure the\n \/\/ initializer's type agrees with the (redundant) type.\n if (Ty && Init) {\n if (Expr *InitE = S.expr.HandleConversionToType(Init, Ty))\n Init = InitE;\n else {\n \/\/ FIXME: Improve this to include the actual types!\n Error(VarLoc, \"variable initializer's type ('TODO') does not match \"\n \"specified type 'TODO'\");\n Ty = Init->Ty;\n }\n }\n \n if (Ty == 0)\n Ty = Init->Ty;\n \n \/\/ Validate attributes.\n ValidateAttributes(Attrs, Ty, *this);\n \n return new (S.Context) VarDecl(VarLoc, S.Context.getIdentifier(Name),\n Ty, Init, Attrs);\n}\n\nFuncDecl *SemaDecl::\nActOnFuncDecl(llvm::SMLoc FuncLoc, llvm::StringRef Name,\n Type *Ty, Expr *Body, DeclAttributes &Attrs) {\n assert(Ty && \"Type not specified?\");\n\n \/\/ Validate that the body's type matches the function's type.\n if (Expr *BodyE = S.expr.HandleConversionToType(Body, Ty))\n Body = BodyE;\n else {\n \/\/ FIXME: Improve this to include the actual types!\n Error(FuncLoc, \"func body's's type ('TODO') does not match \"\n \"specified type 'TODO'\");\n return 0;\n }\n \n \/\/ Validate attributes.\n ValidateAttributes(Attrs, Ty, *this);\n\n return new (S.Context) FuncDecl(FuncLoc, S.Context.getIdentifier(Name),\n Ty, Body, Attrs);\n}\n\nunbreak function prototypes\/\/===--- SemaDecl.cpp - Swift Semantic Analysis for Declarations ----------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements semantic analysis for Swift declarations.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Sema\/SemaDecl.h\"\n#include \"swift\/Sema\/Sema.h\"\n#include \"swift\/Sema\/Scope.h\"\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/Decl.h\"\n#include \"swift\/AST\/Expr.h\"\n#include \"swift\/AST\/Type.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"llvm\/Support\/SMLoc.h\"\nusing namespace swift;\n\nSemaDecl::SemaDecl(Sema &S)\n : SemaBase(S),\n ScopeHT(new ScopeHTType()),\n CurScope(0) {\n}\n\nSemaDecl::~SemaDecl() {\n delete ScopeHT;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Name lookup.\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ AddToScope - Register the specified decl as being in the current lexical\n\/\/\/ scope.\nvoid SemaDecl::AddToScope(NamedDecl *D) {\n \/\/ If we have a shadowed variable definition, check to see if we have a\n \/\/ redefinition: two definitions in the same scope with the same name.\n std::pair Entry = ScopeHT->lookup(D->Name);\n if (Entry.second && Entry.first == CurScope->getDepth()) {\n Error(D->getLocStart(),\n \"variable declaration conflicts with previous declaration\");\n Note(ScopeHT->lookup(D->Name).second->getLocStart(),\n \"previous declaration here\");\n return;\n }\n \n ScopeHT->insert(D->Name, std::make_pair(CurScope->getDepth(), D));\n}\n\n\/\/\/ LookupName - Perform a lexical scope lookup for the specified name,\n\/\/\/ returning the active decl if found or null if not.\nNamedDecl *SemaDecl::LookupName(Identifier Name) {\n return ScopeHT->lookup(Name).second;\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Declaration handling.\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ ValidateAttributes - Check that the func\/var declaration attributes are ok.\nstatic void ValidateAttributes(DeclAttributes &Attrs, Type *Ty, SemaDecl &SD) {\n \/\/ If the decl has an infix precedence specified, then it must be a function\n \/\/ whose input is a two element tuple.\n if (Attrs.InfixPrecedence != -1) {\n bool IsError = true;\n if (FunctionType *FT = llvm::dyn_cast(Ty))\n if (TupleType *TT = llvm::dyn_cast(FT->Input))\n IsError = TT->NumFields != 2;\n if (IsError) {\n SD.Error(Attrs.LSquareLoc, \"function with 'infix' specified must take \"\n \"a two element tuple as input\");\n Attrs.InfixPrecedence = -1;\n }\n }\n}\n\nVarDecl *SemaDecl::ActOnVarDecl(llvm::SMLoc VarLoc, llvm::StringRef Name,\n Type *Ty, Expr *Init, DeclAttributes &Attrs) {\n \n \/\/ Diagnose when we don't have a type or an expression.\n if (Ty == 0 && Init == 0) {\n Error(VarLoc, \"var declaration must specify a type if no \"\n \"initializer is specified\");\n \/\/ TODO: Recover better by still creating var, but making it have 'invalid'\n \/\/ type.\n return 0;\n }\n \n \/\/ If both a type and an initializer are specified, make sure the\n \/\/ initializer's type agrees with the (redundant) type.\n if (Ty && Init) {\n if (Expr *InitE = S.expr.HandleConversionToType(Init, Ty))\n Init = InitE;\n else {\n \/\/ FIXME: Improve this to include the actual types!\n Error(VarLoc, \"variable initializer's type ('TODO') does not match \"\n \"specified type 'TODO'\");\n Ty = Init->Ty;\n }\n }\n \n if (Ty == 0)\n Ty = Init->Ty;\n \n \/\/ Validate attributes.\n ValidateAttributes(Attrs, Ty, *this);\n \n return new (S.Context) VarDecl(VarLoc, S.Context.getIdentifier(Name),\n Ty, Init, Attrs);\n}\n\nFuncDecl *SemaDecl::\nActOnFuncDecl(llvm::SMLoc FuncLoc, llvm::StringRef Name,\n Type *Ty, Expr *Body, DeclAttributes &Attrs) {\n assert(Ty && \"Type not specified?\");\n\n \/\/ Validate that the body's type matches the function's type if this isn't a\n \/\/ external function.\n if (Body) {\n if (Expr *BodyE = S.expr.HandleConversionToType(Body, Ty))\n Body = BodyE;\n else {\n \/\/ FIXME: Improve this to include the actual types!\n Error(FuncLoc, \"func body's's type ('TODO') does not match \"\n \"specified type 'TODO'\");\n return 0;\n }\n }\n \n \/\/ Validate attributes.\n ValidateAttributes(Attrs, Ty, *this);\n\n return new (S.Context) FuncDecl(FuncLoc, S.Context.getIdentifier(Name),\n Ty, Body, Attrs);\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2010-2011 Google\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \"base\/commandlineflags.h\"\n#include \"base\/logging.h\"\n#include \"linear_solver\/linear_solver.h\"\n#include \"linear_solver\/linear_solver.pb.h\"\n\nnamespace operations_research {\nvoid BuildLinearProgrammingMaxExample(MPSolver::OptimizationProblemType type) {\n const double kObjCoef[] = {10.0, 6.0, 4.0};\n const string kVarName[] = {\"x1\", \"x2\", \"x3\"};\n const int numVars = 3;\n const int kNumConstraints = 3;\n const string kConstraintName[] = {\"c1\", \"c2\", \"c3\"};\n const double kConstraintCoef1[] = {1.0, 1.0, 1.0};\n const double kConstraintCoef2[] = {10.0, 4.0, 5.0};\n const double kConstraintCoef3[] = {2.0, 2.0, 6.0};\n const double* kConstraintCoef[] = {kConstraintCoef1,\n kConstraintCoef2,\n kConstraintCoef3};\n const double kConstraintUb[] = {100.0, 600.0, 300.0};\n\n MPSolver solver(\"Max_Example\", type);\n const double infinity = solver.infinity();\n MPModelProto model_proto;\n\n \/\/ Create variables and objective function\n for (int j = 0; j < numVars; ++j) {\n MPVariableProto* x = model_proto.add_variables();\n x->set_id(kVarName[j]);\n x->set_lb(0.0);\n x->set_ub(infinity);\n x->set_integer(false);\n MPTermProto* obj_term = model_proto.add_objective_terms();\n obj_term->set_variable_id(kVarName[j]);\n obj_term->set_coefficient(kObjCoef[j]);\n }\n model_proto.set_maximize(true);\n\n \/\/ Create constraints\n for (int i = 0; i < kNumConstraints; ++i) {\n MPConstraintProto* constraint_proto = model_proto.add_constraints();\n constraint_proto->set_id(kConstraintName[i]);\n constraint_proto->set_lb(-infinity);\n constraint_proto->set_ub(kConstraintUb[i]);\n for (int j = 0; j < numVars; ++j) {\n MPTermProto* term = constraint_proto->add_terms();\n term->set_variable_id(kVarName[j]);\n term->set_coefficient(kConstraintCoef[i][j]);\n }\n }\n\n MPModelRequest model_request;\n model_request.mutable_model()->CopyFrom(model_proto);\n if (type == MPSolver::GLPK_LINEAR_PROGRAMMING) {\n model_request.set_problem_type(MPModelRequest::GLPK_LINEAR_PROGRAMMING);\n } else {\n model_request.set_problem_type(MPModelRequest::CLP_LINEAR_PROGRAMMING);\n }\n\n MPSolutionResponse solution_response;\n solver.SolveWithProtocolBuffers(model_request, &solution_response);\n\n \/\/ The problem has an optimal solution.\n CHECK_EQ(MPSolver::OPTIMAL, solution_response.result_status());\n\n LOG(INFO) << \"objective = \" << solution_response.objective_value();\n for (int j = 0; j < numVars; ++j) {\n MPSolutionValue solution_value = solution_response.solution_values(j);\n LOG(INFO) << solution_value.variable_id() << \" = \"\n << solution_value.value();\n }\n}\n\nvoid RunAllExamples() {\n LOG(INFO) << \"----- Running Max Example with GLPK -----\";\n BuildLinearProgrammingMaxExample(MPSolver::GLPK_LINEAR_PROGRAMMING);\n LOG(INFO) << \"----- Running Max Example with Coin LP -----\";\n BuildLinearProgrammingMaxExample(MPSolver::CLP_LINEAR_PROGRAMMING);\n}\n} \/\/ namespace operations_research\n\nint main(int argc, char **argv) {\n google::ParseCommandLineFlags(&argc, &argv, true);\n operations_research::RunAllExamples();\n return 0;\n}\nfix example\/\/ Copyright 2010-2011 Google\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \"base\/commandlineflags.h\"\n#include \"base\/logging.h\"\n#include \"linear_solver\/linear_solver.h\"\n#include \"linear_solver\/linear_solver.pb.h\"\n\nnamespace operations_research {\nvoid BuildLinearProgrammingMaxExample(MPSolver::OptimizationProblemType type) {\n const double kObjCoef[] = {10.0, 6.0, 4.0};\n const string kVarName[] = {\"x1\", \"x2\", \"x3\"};\n const int numVars = 3;\n const int kNumConstraints = 3;\n const string kConstraintName[] = {\"c1\", \"c2\", \"c3\"};\n const double kConstraintCoef1[] = {1.0, 1.0, 1.0};\n const double kConstraintCoef2[] = {10.0, 4.0, 5.0};\n const double kConstraintCoef3[] = {2.0, 2.0, 6.0};\n const double* kConstraintCoef[] = {kConstraintCoef1,\n kConstraintCoef2,\n kConstraintCoef3};\n const double kConstraintUb[] = {100.0, 600.0, 300.0};\n\n MPSolver solver(\"Max_Example\", type);\n const double infinity = solver.infinity();\n MPModelProto model_proto;\n\n \/\/ Create variables and objective function\n for (int j = 0; j < numVars; ++j) {\n MPVariableProto* x = model_proto.add_variables();\n x->set_id(kVarName[j]);\n x->set_lb(0.0);\n x->set_ub(infinity);\n x->set_integer(false);\n MPTermProto* obj_term = model_proto.add_objective_terms();\n obj_term->set_variable_id(kVarName[j]);\n obj_term->set_coefficient(kObjCoef[j]);\n }\n model_proto.set_maximize(true);\n\n \/\/ Create constraints\n for (int i = 0; i < kNumConstraints; ++i) {\n MPConstraintProto* constraint_proto = model_proto.add_constraints();\n constraint_proto->set_id(kConstraintName[i]);\n constraint_proto->set_lb(-infinity);\n constraint_proto->set_ub(kConstraintUb[i]);\n for (int j = 0; j < numVars; ++j) {\n MPTermProto* term = constraint_proto->add_terms();\n term->set_variable_id(kVarName[j]);\n term->set_coefficient(kConstraintCoef[i][j]);\n }\n }\n\n MPModelRequest model_request;\n model_request.mutable_model()->CopyFrom(model_proto);\n if (type == MPSolver::GLPK_LINEAR_PROGRAMMING) {\n model_request.set_problem_type(MPModelRequest::GLPK_LINEAR_PROGRAMMING);\n } else {\n model_request.set_problem_type(MPModelRequest::CLP_LINEAR_PROGRAMMING);\n }\n\n MPSolutionResponse solution_response;\n solver.SolveWithProtocolBuffers(model_request, &solution_response);\n\n \/\/ The problem has an optimal solution.\n CHECK_EQ(MPSolver::OPTIMAL, solution_response.result_status());\n\n LOG(INFO) << \"objective = \" << solution_response.objective_value();\n const int num_non_zeros = solution_response.solution_values_size();\n for (int j = 0; j < num_non_zeros; ++j) {\n MPSolutionValue solution_value = solution_response.solution_values(j);\n LOG(INFO) << solution_value.variable_id() << \" = \"\n << solution_value.value();\n }\n}\n\nvoid RunAllExamples() {\n LOG(INFO) << \"----- Running Max Example with GLPK -----\";\n BuildLinearProgrammingMaxExample(MPSolver::GLPK_LINEAR_PROGRAMMING);\n LOG(INFO) << \"----- Running Max Example with Coin LP -----\";\n BuildLinearProgrammingMaxExample(MPSolver::CLP_LINEAR_PROGRAMMING);\n}\n} \/\/ namespace operations_research\n\nint main(int argc, char **argv) {\n google::ParseCommandLineFlags(&argc, &argv, true);\n operations_research::RunAllExamples();\n return 0;\n}\n<|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#include \"raptor_api.h\"\n#include \"raptor.h\"\n#include \"georef\/street_network.h\"\n#include \"type\/data.h\"\n#include \"utils\/timer.h\"\n#include \n#include \n#include \n#include \n#include \"utils\/init.h\"\n#include \"utils\/csv.h\"\n#include \n#ifdef __BENCH_WITH_CALGRIND__\n#include \"valgrind\/callgrind.h\"\n#endif\n\nusing namespace navitia;\nusing namespace routing;\nnamespace po = boost::program_options;\nnamespace ba = boost::algorithm;\n\nstruct PathDemand {\n std::string start;\n std::string target;\n\n unsigned int date;\n unsigned int hour;\n\n type::Mode_e start_mode = type::Mode_e::Walking;\n type::Mode_e target_mode = type::Mode_e::Walking;\n};\n\nstruct Result {\n int duration;\n int time;\n int arrival;\n int nb_changes;\n\n Result(pbnavitia::Journey journey) : duration(journey.duration()), time(-1), arrival(journey.arrival_date_time()), nb_changes(journey.nb_transfers()) {}\n};\n\nstatic type::GeographicalCoord coord_of_entry_point(const type::EntryPoint& entry_point,\n const navitia::type::Data& data) {\n type::GeographicalCoord result;\n switch (entry_point.type) {\n case type::Type_e::Address: {\n auto way = data.geo_ref->way_map.find(entry_point.uri);\n if (way != data.geo_ref->way_map.end()){\n const auto geo_way = data.geo_ref->ways[way->second];\n return geo_way->nearest_coord(entry_point.house_number, data.geo_ref->graph);\n }\n }\n break;\n case type::Type_e::StopPoint: {\n auto sp_it = data.pt_data->stop_points_map.find(entry_point.uri);\n if(sp_it != data.pt_data->stop_points_map.end()) {\n return sp_it->second->coord;\n }\n }\n break;\n case type::Type_e::StopArea: {\n auto sa_it = data.pt_data->stop_areas_map.find(entry_point.uri);\n if(sa_it != data.pt_data->stop_areas_map.end()) {\n return sa_it->second->coord;\n }\n }\n break;\n case type::Type_e::Coord:\n return entry_point.coordinates;\n case type::Type_e::Admin: {\n auto it_admin = data.geo_ref->admin_map.find(entry_point.uri);\n if (it_admin != data.geo_ref->admin_map.end()) {\n const auto admin = data.geo_ref->admins[it_admin->second];\n return admin->coord;\n }\n }\n break;\n case type::Type_e::POI: {\n auto poi = data.geo_ref->poi_map.find(entry_point.uri);\n if (poi != data.geo_ref->poi_map.end()){\n const auto geo_poi = data.geo_ref->pois[poi->second];\n return geo_poi->coord;\n }\n }\n break;\n default:\n break;\n }\n std::cout << \"coord not found for \" << entry_point.uri << std::endl;\n return {};\n}\n\nstatic type::EntryPoint make_entry_point(const std::string& entry_id, const type::Data& data) {\n type::EntryPoint entry;\n try {\n type::idx_t idx = boost::lexical_cast(entry_id);\n\n \/\/if it is a idx, we consider it to be a stop area idx\n entry = type::EntryPoint(type::Type_e::StopArea, data.pt_data->stop_areas.at(idx)->uri, 0);\n } catch (boost::bad_lexical_cast) {\n \/\/ else we use the same way to identify an entry point as the api\n entry = type::EntryPoint(data.get_type_of_id(entry_id), entry_id);\n }\n\n entry.coordinates = coord_of_entry_point(entry, data);\n return entry;\n}\n\nint main(int argc, char** argv){\n navitia::init_app();\n po::options_description desc(\"Options de l'outil de benchmark\");\n std::string file, output, stop_input_file, start, target;\n int iterations, date, hour, nb_second_pass;\n\n auto logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT(\"logger\"));\n logger.setLogLevel(log4cplus::WARN_LOG_LEVEL);\n\n desc.add_options()\n (\"help\", \"Show this message\")\n (\"iterations,i\", po::value(&iterations)->default_value(100),\n \"Number of iterations (10 requests by iteration)\")\n (\"file,f\", po::value(&file)->default_value(\"data.nav.lz4\"),\n \"Path to data.nav.lz4\")\n (\"start,s\", po::value(&start),\n \"Start of a particular journey\")\n (\"target,t\", po::value(&target),\n \"Target of a particular journey\")\n (\"date,d\", po::value(&date)->default_value(-1),\n \"Beginning date of a particular journey\")\n (\"hour,h\", po::value(&hour)->default_value(-1),\n \"Beginning hour of a particular journey\")\n (\"verbose,v\", \"Verbose debugging output\")\n (\"nb_second_pass\", po::value(&nb_second_pass)->default_value(0), \"nb second pass\")\n (\"stop_files\", po::value(&stop_input_file), \"File with list of start and target\")\n (\"output,o\", po::value(&output)->default_value(\"benchmark.csv\"),\n \"Output file\");\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n bool verbose = vm.count(\"verbose\");\n\n if (vm.count(\"help\")) {\n std::cout << \"This is used to benchmark journey computation\" << std::endl;\n std::cout << desc << std::endl;\n return 1;\n }\n\n type::Data data;\n {\n Timer t(\"Chargement des données : \" + file);\n data.load(file);\n }\n std::vector demands;\n\n if (! stop_input_file.empty()) {\n \/\/csv file should be the same as the output one\n CsvReader csv(stop_input_file, ',');\n csv.next();\n size_t cpt_not_found = 0;\n for (auto it = csv.next(); ! csv.eof(); it = csv.next()) {\n PathDemand demand;\n demand.start = it[0];\n demand.target = it[1];\n demand.hour = boost::lexical_cast(it[5]);\n demand.date = boost::lexical_cast(it[4]);\n demands.push_back(demand);\n }\n std::cout << \"nb start not found \" << cpt_not_found << std::endl;\n }\n else if(start != \"\" && target != \"\" && date != -1 && hour != -1) {\n PathDemand demand;\n demand.start = start;\n demand.target = target;\n demand.hour = hour;\n demand.date = date;\n std::cout << \"we use the entry param \" << start << \" -> \" << target << std::endl;\n demands.push_back(demand);\n } else {\n \/\/ Génération des instances\n std::random_device rd;\n std::mt19937 rng(31442);\n std::uniform_int_distribution<> gen(0,data.pt_data->stop_areas.size()-1);\n std::vector hours{0, 28800, 36000, 72000, 86000};\n std::vector days({date != -1 ? unsigned(date) : 7});\n if(data.pt_data->validity_patterns.front()->beginning_date.day_of_week().as_number() == 6)\n days.push_back(days.front() + 1);\n else\n days.push_back(days.front() + 6);\n\n for(int i = 0; i < iterations; ++i) {\n PathDemand demand;\n const type::StopArea* sa_start;\n const type::StopArea* sa_dest;\n do {\n sa_start = data.pt_data->stop_areas[gen(rng)];\n sa_dest = data.pt_data->stop_areas[gen(rng)];\n demand.start = sa_start->uri;\n demand.target = sa_dest->uri;\n }\n while(sa_start == sa_dest\n || ba::starts_with(sa_dest->uri, \"stop_area:SNC:\")\n || ba::starts_with(sa_start->uri, \"stop_area:SNC:\"));\n\n for(auto day : days) {\n for(auto hour : hours) {\n demand.date = day;\n demand.hour = hour;\n demands.push_back(demand);\n }\n }\n }\n }\n\n \/\/ Calculs des itinéraires\n std::vector results;\n data.build_raptor();\n RAPTOR router(data);\n auto georef_worker = georef::StreetNetwork(*data.geo_ref);\n\n std::cout << \"On lance le benchmark de l'algo \" << std::endl;\n boost::progress_display show_progress(demands.size());\n Timer t(\"Calcul avec l'algorithme \");\n \/\/ProfilerStart(\"bench.prof\");\n int nb_reponses = 0, nb_journeys = 0;\n#ifdef __BENCH_WITH_CALGRIND__\n CALLGRIND_START_INSTRUMENTATION;\n#endif\n for (auto demand: demands) {\n ++show_progress;\n Timer t2;\n auto date = data.pt_data->validity_patterns.front()->beginning_date + boost::gregorian::days(demand.date + 1) - boost::gregorian::date(1970, 1, 1);\n if (verbose) {\n std::cout << demand.start\n << \", \" << demand.start\n << \", \" << demand.target\n << \", \" << demand.target\n << \", \" << date\n << \", \" << demand.hour\n << \"\\n\";\n }\n\n type::EntryPoint origin = make_entry_point(demand.start, data);\n type::EntryPoint destination = make_entry_point(demand.target, data);\n\n origin.streetnetwork_params.mode = demand.start_mode;\n origin.streetnetwork_params.offset = data.geo_ref->offsets[demand.start_mode];\n origin.streetnetwork_params.max_duration = navitia::seconds(15*60);\n origin.streetnetwork_params.speed_factor = 1;\n destination.streetnetwork_params.mode = demand.target_mode;\n destination.streetnetwork_params.offset = data.geo_ref->offsets[demand.target_mode];\n destination.streetnetwork_params.max_duration = navitia::seconds(15*60);\n destination.streetnetwork_params.speed_factor = 1;\n type::AccessibiliteParams accessibilite_params;\n auto resp = make_response(router, origin, destination,\n {DateTimeUtils::set(date.days(), demand.hour)}, true,\n accessibilite_params,\n {},\n georef_worker,\n type::RTLevel::Base,\n std::numeric_limits::max(),\n 10,\n false,\n nb_second_pass);\n\n if (resp.journeys_size() > 0) {\n ++ nb_reponses;\n nb_journeys += resp.journeys_size();\n\n Result result(resp.journeys(0));\n result.time = t2.ms();\n results.push_back(result);\n }\n }\n \/\/ProfilerStop();\n#ifdef __BENCH_WITH_CALGRIND__\n CALLGRIND_STOP_INSTRUMENTATION;\n#endif\n\n std::cout << \"Number of requests: \" << demands.size() << std::endl;\n std::cout << \"Number of results with solution: \" << nb_reponses << std::endl;\n std::cout << \"Number of journey found: \" << nb_journeys << std::endl;\n}\nbenchmark_full: use 30 min of street network\/* 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#include \"raptor_api.h\"\n#include \"raptor.h\"\n#include \"georef\/street_network.h\"\n#include \"type\/data.h\"\n#include \"utils\/timer.h\"\n#include \n#include \n#include \n#include \n#include \"utils\/init.h\"\n#include \"utils\/csv.h\"\n#include \n#ifdef __BENCH_WITH_CALGRIND__\n#include \"valgrind\/callgrind.h\"\n#endif\n\nusing namespace navitia;\nusing namespace routing;\nnamespace po = boost::program_options;\nnamespace ba = boost::algorithm;\n\nstruct PathDemand {\n std::string start;\n std::string target;\n\n unsigned int date;\n unsigned int hour;\n\n type::Mode_e start_mode = type::Mode_e::Walking;\n type::Mode_e target_mode = type::Mode_e::Walking;\n};\n\nstruct Result {\n int duration;\n int time;\n int arrival;\n int nb_changes;\n\n Result(pbnavitia::Journey journey) : duration(journey.duration()), time(-1), arrival(journey.arrival_date_time()), nb_changes(journey.nb_transfers()) {}\n};\n\nstatic type::GeographicalCoord coord_of_entry_point(const type::EntryPoint& entry_point,\n const navitia::type::Data& data) {\n type::GeographicalCoord result;\n switch (entry_point.type) {\n case type::Type_e::Address: {\n auto way = data.geo_ref->way_map.find(entry_point.uri);\n if (way != data.geo_ref->way_map.end()){\n const auto geo_way = data.geo_ref->ways[way->second];\n return geo_way->nearest_coord(entry_point.house_number, data.geo_ref->graph);\n }\n }\n break;\n case type::Type_e::StopPoint: {\n auto sp_it = data.pt_data->stop_points_map.find(entry_point.uri);\n if(sp_it != data.pt_data->stop_points_map.end()) {\n return sp_it->second->coord;\n }\n }\n break;\n case type::Type_e::StopArea: {\n auto sa_it = data.pt_data->stop_areas_map.find(entry_point.uri);\n if(sa_it != data.pt_data->stop_areas_map.end()) {\n return sa_it->second->coord;\n }\n }\n break;\n case type::Type_e::Coord:\n return entry_point.coordinates;\n case type::Type_e::Admin: {\n auto it_admin = data.geo_ref->admin_map.find(entry_point.uri);\n if (it_admin != data.geo_ref->admin_map.end()) {\n const auto admin = data.geo_ref->admins[it_admin->second];\n return admin->coord;\n }\n }\n break;\n case type::Type_e::POI: {\n auto poi = data.geo_ref->poi_map.find(entry_point.uri);\n if (poi != data.geo_ref->poi_map.end()){\n const auto geo_poi = data.geo_ref->pois[poi->second];\n return geo_poi->coord;\n }\n }\n break;\n default:\n break;\n }\n std::cout << \"coord not found for \" << entry_point.uri << std::endl;\n return {};\n}\n\nstatic type::EntryPoint make_entry_point(const std::string& entry_id, const type::Data& data) {\n type::EntryPoint entry;\n try {\n type::idx_t idx = boost::lexical_cast(entry_id);\n\n \/\/if it is a idx, we consider it to be a stop area idx\n entry = type::EntryPoint(type::Type_e::StopArea, data.pt_data->stop_areas.at(idx)->uri, 0);\n } catch (boost::bad_lexical_cast) {\n \/\/ else we use the same way to identify an entry point as the api\n entry = type::EntryPoint(data.get_type_of_id(entry_id), entry_id);\n }\n\n entry.coordinates = coord_of_entry_point(entry, data);\n return entry;\n}\n\nint main(int argc, char** argv){\n navitia::init_app();\n po::options_description desc(\"Options de l'outil de benchmark\");\n std::string file, output, stop_input_file, start, target;\n int iterations, date, hour, nb_second_pass;\n\n auto logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT(\"logger\"));\n logger.setLogLevel(log4cplus::WARN_LOG_LEVEL);\n\n desc.add_options()\n (\"help\", \"Show this message\")\n (\"iterations,i\", po::value(&iterations)->default_value(100),\n \"Number of iterations (10 requests by iteration)\")\n (\"file,f\", po::value(&file)->default_value(\"data.nav.lz4\"),\n \"Path to data.nav.lz4\")\n (\"start,s\", po::value(&start),\n \"Start of a particular journey\")\n (\"target,t\", po::value(&target),\n \"Target of a particular journey\")\n (\"date,d\", po::value(&date)->default_value(-1),\n \"Beginning date of a particular journey\")\n (\"hour,h\", po::value(&hour)->default_value(-1),\n \"Beginning hour of a particular journey\")\n (\"verbose,v\", \"Verbose debugging output\")\n (\"nb_second_pass\", po::value(&nb_second_pass)->default_value(0), \"nb second pass\")\n (\"stop_files\", po::value(&stop_input_file), \"File with list of start and target\")\n (\"output,o\", po::value(&output)->default_value(\"benchmark.csv\"),\n \"Output file\");\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n bool verbose = vm.count(\"verbose\");\n\n if (vm.count(\"help\")) {\n std::cout << \"This is used to benchmark journey computation\" << std::endl;\n std::cout << desc << std::endl;\n return 1;\n }\n\n type::Data data;\n {\n Timer t(\"Chargement des données : \" + file);\n data.load(file);\n }\n std::vector demands;\n\n if (! stop_input_file.empty()) {\n \/\/csv file should be the same as the output one\n CsvReader csv(stop_input_file, ',');\n csv.next();\n size_t cpt_not_found = 0;\n for (auto it = csv.next(); ! csv.eof(); it = csv.next()) {\n PathDemand demand;\n demand.start = it[0];\n demand.target = it[1];\n demand.hour = boost::lexical_cast(it[5]);\n demand.date = boost::lexical_cast(it[4]);\n demands.push_back(demand);\n }\n std::cout << \"nb start not found \" << cpt_not_found << std::endl;\n }\n else if(start != \"\" && target != \"\" && date != -1 && hour != -1) {\n PathDemand demand;\n demand.start = start;\n demand.target = target;\n demand.hour = hour;\n demand.date = date;\n std::cout << \"we use the entry param \" << start << \" -> \" << target << std::endl;\n demands.push_back(demand);\n } else {\n \/\/ Génération des instances\n std::random_device rd;\n std::mt19937 rng(31442);\n std::uniform_int_distribution<> gen(0,data.pt_data->stop_areas.size()-1);\n std::vector hours{0, 28800, 36000, 72000, 86000};\n std::vector days({date != -1 ? unsigned(date) : 7});\n if(data.pt_data->validity_patterns.front()->beginning_date.day_of_week().as_number() == 6)\n days.push_back(days.front() + 1);\n else\n days.push_back(days.front() + 6);\n\n for(int i = 0; i < iterations; ++i) {\n PathDemand demand;\n const type::StopArea* sa_start;\n const type::StopArea* sa_dest;\n do {\n sa_start = data.pt_data->stop_areas[gen(rng)];\n sa_dest = data.pt_data->stop_areas[gen(rng)];\n demand.start = sa_start->uri;\n demand.target = sa_dest->uri;\n }\n while(sa_start == sa_dest\n || ba::starts_with(sa_dest->uri, \"stop_area:SNC:\")\n || ba::starts_with(sa_start->uri, \"stop_area:SNC:\"));\n\n for(auto day : days) {\n for(auto hour : hours) {\n demand.date = day;\n demand.hour = hour;\n demands.push_back(demand);\n }\n }\n }\n }\n\n \/\/ Calculs des itinéraires\n std::vector results;\n data.build_raptor();\n RAPTOR router(data);\n auto georef_worker = georef::StreetNetwork(*data.geo_ref);\n\n std::cout << \"On lance le benchmark de l'algo \" << std::endl;\n boost::progress_display show_progress(demands.size());\n Timer t(\"Calcul avec l'algorithme \");\n \/\/ProfilerStart(\"bench.prof\");\n int nb_reponses = 0, nb_journeys = 0;\n#ifdef __BENCH_WITH_CALGRIND__\n CALLGRIND_START_INSTRUMENTATION;\n#endif\n for (auto demand: demands) {\n ++show_progress;\n Timer t2;\n auto date = data.pt_data->validity_patterns.front()->beginning_date + boost::gregorian::days(demand.date + 1) - boost::gregorian::date(1970, 1, 1);\n if (verbose) {\n std::cout << demand.start\n << \", \" << demand.start\n << \", \" << demand.target\n << \", \" << demand.target\n << \", \" << date\n << \", \" << demand.hour\n << \"\\n\";\n }\n\n type::EntryPoint origin = make_entry_point(demand.start, data);\n type::EntryPoint destination = make_entry_point(demand.target, data);\n\n origin.streetnetwork_params.mode = demand.start_mode;\n origin.streetnetwork_params.offset = data.geo_ref->offsets[demand.start_mode];\n origin.streetnetwork_params.max_duration = navitia::seconds(30*60);\n origin.streetnetwork_params.speed_factor = 1;\n destination.streetnetwork_params.mode = demand.target_mode;\n destination.streetnetwork_params.offset = data.geo_ref->offsets[demand.target_mode];\n destination.streetnetwork_params.max_duration = navitia::seconds(30*60);\n destination.streetnetwork_params.speed_factor = 1;\n type::AccessibiliteParams accessibilite_params;\n auto resp = make_response(router, origin, destination,\n {DateTimeUtils::set(date.days(), demand.hour)}, true,\n accessibilite_params,\n {},\n georef_worker,\n type::RTLevel::Base,\n std::numeric_limits::max(),\n 10,\n false,\n nb_second_pass);\n\n if (resp.journeys_size() > 0) {\n ++ nb_reponses;\n nb_journeys += resp.journeys_size();\n\n Result result(resp.journeys(0));\n result.time = t2.ms();\n results.push_back(result);\n }\n }\n \/\/ProfilerStop();\n#ifdef __BENCH_WITH_CALGRIND__\n CALLGRIND_STOP_INSTRUMENTATION;\n#endif\n\n std::cout << \"Number of requests: \" << demands.size() << std::endl;\n std::cout << \"Number of results with solution: \" << nb_reponses << std::endl;\n std::cout << \"Number of journey found: \" << nb_journeys << std::endl;\n}\n<|endoftext|>"} {"text":"\/**\n * @file CSRFile_test.cpp\n * @brief Test for reading and writing CSR formatted csrs.\n * @author Dominique LaSalle \n * Copyright 2015-2017\n * @version 1\n *\n *\/\n\n\n\n\n#include \n#include \n#include \n\n#include \"CSRFile.hpp\"\n#include \"DomTest.hpp\"\n\n\n\n\nusing namespace WildRiver;\n\n\n\n\nnamespace DomTest\n{\n\n\nstatic void writeTest(\n std::string const & testFile)\n{\n CSRFile csr(testFile);\n\n csr.setInfo(6,6,14);\n\n wildriver_ind_t rowptr[] = {0,2,4,7,10,12,14};\n wildriver_dim_t rowind[] = {1,2,0,2,0,1,3,2,4,5,3,5,3,4};\n wildriver_val_t rowval[] = {1,2,3,4,5,6,7,8,9,1,2,3,4,5};\n\n csr.write(rowptr,rowind,rowval);\n}\n\n\nstatic void readTest(\n std::string const & testFile)\n{\n CSRFile csr(testFile);\n\n wildriver_dim_t nrows, ncols;\n wildriver_ind_t nnz;\n\n csr.getInfo(nrows,ncols,nnz);\n\n testEquals(nrows,6);\n testEquals(ncols,6);\n testEquals(nnz,14);\n\n std::unique_ptr rowptr(new wildriver_ind_t[nrows+1]);\n std::unique_ptr rowind(new wildriver_dim_t[nnz]);\n std::unique_ptr rowval(new wildriver_val_t[nnz]);\n\n csr.read(rowptr.get(),rowind.get(),rowval.get(),nullptr);\n\n \/\/ test rowptr\n testEquals(rowptr[0],0);\n testEquals(rowptr[1],2);\n testEquals(rowptr[2],4);\n testEquals(rowptr[3],7);\n testEquals(rowptr[4],10);\n testEquals(rowptr[5],12);\n testEquals(rowptr[6],14);\n\n \/\/ test rowind\n testEquals(rowind[0],1);\n testEquals(rowind[1],2);\n testEquals(rowval[0],1);\n testEquals(rowval[1],2);\n\n testEquals(rowind[2],0);\n testEquals(rowind[3],2);\n testEquals(rowval[2],3);\n testEquals(rowval[3],4);\n\n testEquals(rowind[4],0);\n testEquals(rowind[5],1);\n testEquals(rowind[6],3);\n testEquals(rowval[4],5);\n testEquals(rowval[5],6);\n testEquals(rowval[6],7);\n\n testEquals(rowind[7],2);\n testEquals(rowind[8],4);\n testEquals(rowind[9],5);\n testEquals(rowval[7],8);\n testEquals(rowval[8],9);\n testEquals(rowval[9],1);\n\n testEquals(rowind[10],3);\n testEquals(rowind[11],5);\n testEquals(rowval[10],2);\n testEquals(rowval[11],3);\n\n testEquals(rowind[12],3);\n testEquals(rowind[13],4);\n testEquals(rowval[12],4);\n testEquals(rowval[13],5);\n}\n\n\nvoid Test::run()\n{\n std::string testFile(\".\/CSRFile_test.csr\");\n\n writeTest(testFile);\n readTest(testFile);\n\n}\n\n\n\n\n}\nUpdate unit test for CSRFile base one\/**\n * @file CSRFile_test.cpp\n * @brief Test for reading and writing CSR formatted csrs.\n * @author Dominique LaSalle \n * Copyright 2015-2017\n * @version 1\n *\n *\/\n\n\n\n\n#include \n#include \n#include \n\n#include \"CSRFile.hpp\"\n#include \"DomTest.hpp\"\n\n\n\n\nusing namespace WildRiver;\n\n\n\n\nnamespace DomTest\n{\n\n\nstatic void writeTest(\n std::string const & testFile)\n{\n CSRFile csr(testFile);\n\n csr.setInfo(6,6,14);\n\n wildriver_ind_t rowptr[] = {0,2,4,7,10,12,14};\n wildriver_dim_t rowind[] = {1,2,0,2,0,1,3,2,4,5,3,5,3,4};\n wildriver_val_t rowval[] = {1,2,3,4,5,6,7,8,9,1,2,3,4,5};\n\n csr.write(rowptr,rowind,rowval);\n}\n\n\nstatic void readTestBaseZero(\n std::string const & testFile)\n{\n std::ofstream fout(testFile, std::ofstream::trunc);\n fout << \"1 1.0 2 2.0\" << std::endl;\n fout << \"0 3.0 2 4.0\" << std::endl;\n fout << \"0 5.0 1 6.0 3 7.0\" << std::endl;\n fout << \"2 8.0 4 9.0 5 1.0\" << std::endl;\n fout << \"3 2.0 5 3.0\" << std::endl;\n fout << \"3 4.0 4 5.0\" << std::endl;\n\n fout.close();\n\n CSRFile csr(testFile);\n\n wildriver_dim_t nrows, ncols;\n wildriver_ind_t nnz;\n\n csr.getInfo(nrows,ncols,nnz);\n\n testEquals(nrows,6);\n testEquals(ncols,6);\n testEquals(nnz,14);\n\n std::unique_ptr rowptr(new wildriver_ind_t[nrows+1]);\n std::unique_ptr rowind(new wildriver_dim_t[nnz]);\n std::unique_ptr rowval(new wildriver_val_t[nnz]);\n\n csr.read(rowptr.get(),rowind.get(),rowval.get(),nullptr);\n\n \/\/ test rowptr\n testEquals(rowptr[0],0);\n testEquals(rowptr[1],2);\n testEquals(rowptr[2],4);\n testEquals(rowptr[3],7);\n testEquals(rowptr[4],10);\n testEquals(rowptr[5],12);\n testEquals(rowptr[6],14);\n\n \/\/ test rowind\n testEquals(rowind[0],1);\n testEquals(rowind[1],2);\n testEquals(rowval[0],1);\n testEquals(rowval[1],2);\n\n testEquals(rowind[2],0);\n testEquals(rowind[3],2);\n testEquals(rowval[2],3);\n testEquals(rowval[3],4);\n\n testEquals(rowind[4],0);\n testEquals(rowind[5],1);\n testEquals(rowind[6],3);\n testEquals(rowval[4],5);\n testEquals(rowval[5],6);\n testEquals(rowval[6],7);\n\n testEquals(rowind[7],2);\n testEquals(rowind[8],4);\n testEquals(rowind[9],5);\n testEquals(rowval[7],8);\n testEquals(rowval[8],9);\n testEquals(rowval[9],1);\n\n testEquals(rowind[10],3);\n testEquals(rowind[11],5);\n testEquals(rowval[10],2);\n testEquals(rowval[11],3);\n\n testEquals(rowind[12],3);\n testEquals(rowind[13],4);\n testEquals(rowval[12],4);\n testEquals(rowval[13],5);\n}\n\n\nstatic void readTestBaseOne(\n std::string const & testFile)\n{\n std::ofstream fout(testFile, std::ofstream::trunc);\n fout << \"2 1.0 3 2.0\" << std::endl;\n fout << \"1 3.0 3 4.0\" << std::endl;\n fout << \"1 5.0 2 6.0 4 7.0\" << std::endl;\n fout << \"3 8.0 5 9.0 6 1.0\" << std::endl;\n fout << \"4 2.0 6 3.0\" << std::endl;\n fout << \"4 4.0 5 5.0\" << std::endl;\n\n fout.close();\n\n CSRFile csr(testFile);\n\n wildriver_dim_t nrows, ncols;\n wildriver_ind_t nnz;\n\n csr.getInfo(nrows,ncols,nnz);\n\n testEquals(nrows,6);\n testEquals(ncols,6);\n testEquals(nnz,14);\n\n std::unique_ptr rowptr(new wildriver_ind_t[nrows+1]);\n std::unique_ptr rowind(new wildriver_dim_t[nnz]);\n std::unique_ptr rowval(new wildriver_val_t[nnz]);\n\n csr.read(rowptr.get(),rowind.get(),rowval.get(),nullptr);\n\n \/\/ test rowptr\n testEquals(rowptr[0],0);\n testEquals(rowptr[1],2);\n testEquals(rowptr[2],4);\n testEquals(rowptr[3],7);\n testEquals(rowptr[4],10);\n testEquals(rowptr[5],12);\n testEquals(rowptr[6],14);\n\n \/\/ test rowind\n testEquals(rowind[0],1);\n testEquals(rowind[1],2);\n testEquals(rowval[0],1);\n testEquals(rowval[1],2);\n\n testEquals(rowind[2],0);\n testEquals(rowind[3],2);\n testEquals(rowval[2],3);\n testEquals(rowval[3],4);\n\n testEquals(rowind[4],0);\n testEquals(rowind[5],1);\n testEquals(rowind[6],3);\n testEquals(rowval[4],5);\n testEquals(rowval[5],6);\n testEquals(rowval[6],7);\n\n testEquals(rowind[7],2);\n testEquals(rowind[8],4);\n testEquals(rowind[9],5);\n testEquals(rowval[7],8);\n testEquals(rowval[8],9);\n testEquals(rowval[9],1);\n\n testEquals(rowind[10],3);\n testEquals(rowind[11],5);\n testEquals(rowval[10],2);\n testEquals(rowval[11],3);\n\n testEquals(rowind[12],3);\n testEquals(rowind[13],4);\n testEquals(rowval[12],4);\n testEquals(rowval[13],5);\n}\n\n\n\nvoid Test::run()\n{\n std::string testFile(\".\/CSRFile_test.csr\");\n\n writeTest(testFile);\n\n remove(testFile.c_str());\n\n readTestBaseZero(testFile);\n\n remove(testFile.c_str());\n\n readTestBaseOne(testFile);\n\n remove(testFile.c_str());\n\n}\n\n\n\n\n}\n<|endoftext|>"} {"text":"#include \"swissknife_lease.h\"\n\n#include \"curl\/curl.h\"\n\nstatic bool CheckParams(const swissknife::CommandLease::Parameters& p) {\n if (p.action != \"acquire\" && p.action != \"drop\") {\n return false;\n }\n\n return true;\n}\n\nnamespace swissknife {\n\nCommandLease::~CommandLease() {\n}\n\nParameterList CommandLease::GetParams() const {\n ParameterList r;\n r.push_back(Parameter::Mandatory('u', \"repo service url\"));\n r.push_back(Parameter::Mandatory('a', \"action (acquire or drop)\"));\n r.push_back(Parameter::Mandatory('n', \"user name\"));\n r.push_back(Parameter::Mandatory('p', \"lease path\"));\n return r;\n}\n\nint CommandLease::Main(const ArgumentList& args) {\n Parameters params;\n\n params.repo_service_url = *(args.find('u')->second);\n params.action = *(args.find('a')->second);\n params.user_name = *(args.find('n')->second);\n params.lease_path = *(args.find('p')->second);\n\n if (!CheckParams(params)) return 2;\n\n \/\/ Initialize curl\n if (curl_global_init(CURL_GLOBAL_ALL)) {\n return 1;\n }\n\n if (params.action == \"acquire\") {\n \/\/ Acquire lease from repo services\n } else if (params.action == \"drop\") {\n \/\/ Drop the current lease\n }\n\n return 0;\n}\n\n}\nWIP: Implementing lease acquisition in swissknife_lease#include \"swissknife_lease.h\"\n\n#include \"util\/pointer.h\"\n#include \"json_document.h\"\n#include \"json.h\"\n#include \"logging.h\"\n\n#include \"curl\/curl.h\"\n\nnamespace {\n\nbool CheckParams(const swissknife::CommandLease::Parameters& p) {\n if (p.action != \"acquire\" && p.action != \"drop\") {\n return false;\n }\n\n return true;\n}\n\n\/*size_t SendCB(void *buffer, size_t size, size_t nmemb, void *userp) {\n}*\/\n\nstruct CurlBuffer {\n std::string data;\n};\n\nsize_t RecvCB(void *buffer, size_t size, size_t nmemb, void *userp) {\n CurlBuffer* my_buffer = (CurlBuffer*)userp;\n\n if (size * nmemb < 1) {\n return 0;\n }\n\n my_buffer->data = static_cast(buffer);\n\n return my_buffer->data.size();\n}\n\n}\n\nnamespace swissknife {\n\nCommandLease::~CommandLease() {\n}\n\nParameterList CommandLease::GetParams() const {\n ParameterList r;\n r.push_back(Parameter::Mandatory('u', \"repo service url\"));\n r.push_back(Parameter::Mandatory('a', \"action (acquire or drop)\"));\n r.push_back(Parameter::Mandatory('n', \"user name\"));\n r.push_back(Parameter::Mandatory('p', \"lease path\"));\n return r;\n}\n\nint CommandLease::Main(const ArgumentList& args) {\n Parameters params;\n\n params.repo_service_url = *(args.find('u')->second);\n params.action = *(args.find('a')->second);\n params.user_name = *(args.find('n')->second);\n params.lease_path = *(args.find('p')->second);\n\n if (!CheckParams(params)) return 2;\n\n \/\/ Initialize curl\n if (curl_global_init(CURL_GLOBAL_ALL)) {\n return 1;\n }\n\n CURL* h_curl = curl_easy_init();\n CURLcode ret = static_cast(0);\n if (h_curl) {\n if (params.action == \"acquire\") {\n \/\/ Prepare payload\n std::string payload = \"{\\\"user\\\" : \\\"\" + params.user_name + \"\\\", \\\"path\\\" : \\\"\" + params.lease_path + \"\\\"}\";\n\n \/\/ Make request to acquire lease from repo services\n curl_easy_setopt(h_curl, CURLOPT_URL, (params.repo_service_url + \"\/api\/leases\").c_str());\n curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L);\n curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, payload.c_str());\n curl_easy_setopt(h_curl,\n CURLOPT_POSTFIELDSIZE_LARGE,\n static_cast(payload.length()));\n curl_easy_setopt(h_curl, CURLOPT_USERAGENT, \"curl\/7.47.0\");\n curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L);\n curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, \"POST\");\n curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L);\n\n CurlBuffer buffer;\n\n curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);\n curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, &buffer);\n\n ret = curl_easy_perform(h_curl);\n\n curl_easy_cleanup(h_curl);\n h_curl = NULL;\n\n \/\/Parse reply\n UniquePtr reply(JsonDocument::Create(buffer.data));\n if (reply->IsValid()) {\n JSON* result = JsonDocument::SearchInObject(reply->root(), \"status\", JSON_STRING);\n if (result != NULL) {\n std::string status = result->string_value;\n if (status == \"ok\") {\n LogCvmfs(kLogCvmfs, kLogStderr, \"Status: ok\");\n JSON* token = JsonDocument::SearchInObject(reply->root(), \"session_token\", JSON_STRING);\n if (token != NULL) {\n LogCvmfs(kLogCvmfs, kLogStderr, \"Session token: %s\", token->string_value);\n std::string session_token = token->string_value;\n \/\/ Save session token to \/var\/spool\/cvmfs\/\n \/\/ TODO: Is there a special way to access the scratch directory?\n std::string token_file_name = \"\/var\/spool\/cvmfs\/\" + params.lease_path + \"\/session_token\";\n FILE* token_file = std::fopen(token_file_name.c_str(), \"w\");\n if (token_file != NULL) {\n std::fprintf(token_file, \"%s\", session_token.c_str());\n std::fclose(token_file);\n } else {\n LogCvmfs(kLogCvmfs, kLogStderr, \"Error opening file: %s\", std::strerror(errno));\n }\n }\n } else if (status == \"path_busy\") {\n JSON* time_remaining = JsonDocument::SearchInObject(reply->root(), \"time_remaining\", JSON_INT);\n if (time_remaining != NULL) {\n LogCvmfs(kLogCvmfs, kLogStderr, \"Path busy. Time remaining = %d\", time_remaining->int_value);\n }\n } else if (status == \"error\") {\n JSON* reason = JsonDocument::SearchInObject(reply->root(), \"reason\", JSON_STRING);\n if (reason != NULL) {\n LogCvmfs(kLogCvmfs, kLogStderr, \"Error: %s\", reason->string_value);\n }\n } else {\n LogCvmfs(kLogCvmfs, kLogStderr, \"Unknown reply. Status: %s\", status.c_str());\n }\n }\n }\n\n } else if (params.action == \"drop\") {\n \/\/ Drop the current lease\n }\n } else {\n return 1;\n }\n\n return ret;\n}\n\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"functors.hpp\"\n\n#include \n#include \n#include \n#include \n\nnamespace cu\n{\n\ntemplate \nclass Visitor;\n\ntemplate <>\nclass Visitor<>\n{\nprotected:\n void visit() = delete;\n};\n\ntemplate \nclass Visitor : public Visitor\n{\npublic:\n virtual ~Visitor() = default;\n\n using Visitor::visit;\n virtual void visit( T& ) = 0;\n};\n\ntemplate \nusing ConstVisitor = Visitor;\n\n\ntemplate \nclass VisitableBase\n{\npublic:\n using Visitor = Visitor;\n using ConstVisitor = ConstVisitor;\n\n virtual ~VisitableBase() = default;\n\n virtual void accept( Visitor & visitor ) = 0;\n virtual void accept( ConstVisitor & visitor ) const = 0;\n};\n\n\n\/\/\/ Base should derive from @c VisitableBase<...,Derived,...>.\ntemplate \nclass VisitableImpl\n : public Base\n{\npublic:\n using Visitor = typename Base::Visitor;\n using ConstVisitor = typename Base::ConstVisitor;\n\n using Base::Base;\n\n virtual void accept( Visitor & visitor ) override\n {\n assert( dynamic_cast(this) &&\n \"The dynamic type of this object must be 'Derived' \"\n \"or inherit from it.\" );\n visitor.visit( static_cast(*this) );\n }\n\n virtual void accept( ConstVisitor & visitor ) const override\n {\n assert( dynamic_cast(this) &&\n \"The dynamic type of this object must be 'Derived' \"\n \"or inherit from it.\" );\n visitor.visit( static_cast(*this) );\n }\n};\n\n\nnamespace detail\n{\n\n template \n class VisitorImpl;\n\n template \n class VisitorImpl\n : public VisitorBase\n {\n public:\n VisitorImpl( F && f_ )\n : f(std::forward(f_))\n {}\n\n Result && getResult()\n {\n return std::move(result);\n }\n\n protected:\n template \n void doVisit( T && arg )\n {\n result = std::forward(f)( std::forward(arg) );\n }\n\n private:\n Result result{};\n F && f;\n };\n\n template \n class VisitorImpl\n : public VisitorBase\n {\n public:\n VisitorImpl( F && f_ )\n : f(std::forward(f_))\n {}\n\n void getResult()\n {}\n\n protected:\n template \n void doVisit( T && arg )\n {\n std::forward(f)( std::forward(arg) );\n }\n\n private:\n F && f;\n };\n\n template \n class VisitorImpl\n : public VisitorImpl\n {\n using DirectBase = VisitorImpl;\n public:\n using DirectBase::DirectBase;\n using VisitorBase::visit;\n virtual void visit( T & x ) override\n {\n this->doVisit( x );\n }\n };\n\n} \/\/ namespace detail\n\ntemplate \nauto visit( VisitableBase & visitable, F && f )\n{\n using Result = std::common_type_t...>;\n detail::VisitorImpl, Ts...> visitor{\n std::forward(f) };\n visitable.accept( visitor );\n return visitor.getResult();\n}\n\ntemplate \nauto visit( const VisitableBase & visitable, F && f )\n{\n using Result = std::common_type_t...>;\n detail::VisitorImpl, const Ts...> visitor{\n std::forward(f) };\n visitable.accept( visitor );\n return visitor.getResult();\n}\n\ntemplate \ndecltype(auto) visit( VisitableBase & visitable, Fs &&... fs )\n{\n return visit( visitable, makeOverloadedFunctor( fs... ) );\n}\n\ntemplate \ndecltype(auto) visit( const VisitableBase & visitable, Fs &&... fs )\n{\n return visit( visitable, makeOverloadedFunctor( fs... ) );\n}\n\n\nnamespace detail\n{\n\n template \n decltype(auto) makeGenericCloner()\n {\n return []( const auto & item )\n {\n return std::unique_ptr(\n std::make_unique>( item ) );\n };\n }\n\n} \/\/ namespace detail\n\ntemplate \nauto clone( const VisitableTemplate & item )\n -> decltype( visit( item, detail::makeGenericCloner() ) )\n{\n return visit( item, detail::makeGenericCloner() );\n}\n\ntemplate \nauto clone( const std::vector > & v )\n -> decltype( (void)clone( *v[0] ),\n std::unique_ptr > >() )\n{\n auto result = std::make_unique > >();\n for ( const auto & x : v )\n result->push_back( clone( *x ) );\n\n return result;\n}\n\n} \/\/ namespace cu\nAdded isEqual() function for visitable classes.#pragma once\n\n#include \"functors.hpp\"\n\n#include \n#include \n#include \n#include \n\nnamespace cu\n{\n\ntemplate \nclass Visitor;\n\ntemplate <>\nclass Visitor<>\n{\nprotected:\n void visit() = delete;\n};\n\ntemplate \nclass Visitor : public Visitor\n{\npublic:\n virtual ~Visitor() = default;\n\n using Visitor::visit;\n virtual void visit( T& ) = 0;\n};\n\ntemplate \nusing ConstVisitor = Visitor;\n\n\ntemplate \nclass VisitableBase\n{\npublic:\n using Visitor = Visitor;\n using ConstVisitor = ConstVisitor;\n\n virtual ~VisitableBase() = default;\n\n virtual void accept( Visitor & visitor ) = 0;\n virtual void accept( ConstVisitor & visitor ) const = 0;\n};\n\n\n\/\/\/ Base should derive from @c VisitableBase<...,Derived,...>.\ntemplate \nclass VisitableImpl\n : public Base\n{\npublic:\n using Visitor = typename Base::Visitor;\n using ConstVisitor = typename Base::ConstVisitor;\n\n using Base::Base;\n\n virtual void accept( Visitor & visitor ) override\n {\n assert( dynamic_cast(this) &&\n \"The dynamic type of this object must be 'Derived' \"\n \"or inherit from it.\" );\n visitor.visit( static_cast(*this) );\n }\n\n virtual void accept( ConstVisitor & visitor ) const override\n {\n assert( dynamic_cast(this) &&\n \"The dynamic type of this object must be 'Derived' \"\n \"or inherit from it.\" );\n visitor.visit( static_cast(*this) );\n }\n};\n\n\nnamespace detail\n{\n\n template \n class VisitorImpl;\n\n template \n class VisitorImpl\n : public VisitorBase\n {\n public:\n VisitorImpl( F && f_ )\n : f(std::forward(f_))\n {}\n\n Result && getResult()\n {\n return std::move(result);\n }\n\n protected:\n template \n void doVisit( T && arg )\n {\n result = std::forward(f)( std::forward(arg) );\n }\n\n private:\n Result result{};\n F && f;\n };\n\n template \n class VisitorImpl\n : public VisitorBase\n {\n public:\n VisitorImpl( F && f_ )\n : f(std::forward(f_))\n {}\n\n void getResult()\n {}\n\n protected:\n template \n void doVisit( T && arg )\n {\n std::forward(f)( std::forward(arg) );\n }\n\n private:\n F && f;\n };\n\n template \n class VisitorImpl\n : public VisitorImpl\n {\n using DirectBase = VisitorImpl;\n public:\n using DirectBase::DirectBase;\n using VisitorBase::visit;\n virtual void visit( T & x ) override\n {\n this->doVisit( x );\n }\n };\n\n} \/\/ namespace detail\n\ntemplate \nauto visit( VisitableBase & visitable, F && f )\n{\n using Result = std::common_type_t...>;\n detail::VisitorImpl, Ts...> visitor{\n std::forward(f) };\n visitable.accept( visitor );\n return visitor.getResult();\n}\n\ntemplate \nauto visit( const VisitableBase & visitable, F && f )\n{\n using Result = std::common_type_t...>;\n detail::VisitorImpl, const Ts...> visitor{\n std::forward(f) };\n visitable.accept( visitor );\n return visitor.getResult();\n}\n\ntemplate \ndecltype(auto) visit( VisitableBase & visitable, Fs &&... fs )\n{\n return visit( visitable, makeOverloadedFunctor( fs... ) );\n}\n\ntemplate \ndecltype(auto) visit( const VisitableBase & visitable, Fs &&... fs )\n{\n return visit( visitable, makeOverloadedFunctor( fs... ) );\n}\n\n\nnamespace detail\n{\n\n template \n decltype(auto) makeGenericCloner()\n {\n return []( const auto & item )\n {\n return std::unique_ptr(\n std::make_unique>( item ) );\n };\n }\n\n} \/\/ namespace detail\n\ntemplate \nauto clone( const VisitableTemplate & item )\n -> decltype( visit( item, detail::makeGenericCloner() ) )\n{\n return visit( item, detail::makeGenericCloner() );\n}\n\ntemplate \nauto clone( const std::vector > & v )\n -> decltype( (void)clone( *v[0] ),\n std::unique_ptr > >() )\n{\n auto result = std::make_unique > >();\n for ( const auto & x : v )\n result->push_back( clone( *x ) );\n\n return result;\n}\n\n\nnamespace detail\n{\n\n struct IsEqualFunctor\n {\n template \n bool operator()( const T & lhs, const T & rhs ) const\n {\n return lhs == rhs;\n }\n\n template \n bool operator()( const T1 &, const T2 & ) const\n {\n return false;\n }\n };\n\n} \/\/ namespace detail\n\ntemplate \nbool isEqual( const VisitableTemplate & lhs, const VisitableTemplate & rhs )\n{\n return visit( lhs, [&rhs]( const auto & lhs )\n {\n return visit( rhs, [&lhs]( const auto & rhs )\n {\n return detail::IsEqualFunctor()( lhs, rhs );\n });\n });\n}\n\n} \/\/ namespace cu\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"raster.h\"\n#include \"pixeliterator.h\"\n\n\nusing namespace Ilwis;\n\nbool PixelIterator::isValid() const {\n return _isValid;\n}\n\nPixelIterator::PixelIterator() : _localOffset(0), _currentBlock(0), _step(0), _flow(fXYZ),_isValid(false),_positionid(0) {\n\n}\n\nPixelIterator::PixelIterator(IGridCoverage raster, const Box3D<>& box, double step) :\n _raster(raster),\n _box(box),\n _localOffset(0),\n _currentBlock(0),\n _step(step),\n _flow(fXYZ),\n _isValid(false)\n{\n init();\n}\n\nPixelIterator::PixelIterator(const PixelIterator& iter) {\n copy(iter);\n}\n\ninline PixelIterator::PixelIterator(quint64 posid ) :\n _localOffset(0),\n _currentBlock(0),\n _step(0),\n _flow(fXYZ),\n _isValid(false),\n _positionid(posid)\n{\n}\n\n\nvoid PixelIterator::copy(const PixelIterator &iter) {\n _raster = iter._raster;\n if ( _raster.isValid()) \/\/ TODO beyond end marker(end()) dont have a valid raster, no problem just yet but it maybe needed in the future\n _grid = _raster->_grid.data();\n _box = iter._box;\n _step = iter._step;\n _isValid = iter._isValid;\n _flow = iter._flow;\n _positionid = iter._positionid;\n _x = iter._x;\n _y = iter._y;\n _z = iter._z;\n _endx = iter._endx;\n _endy = iter._endy;\n _endz = iter._endz;\n _positionid = iter._positionid;\n _endpositionid = iter._endpositionid;\n _localOffset = iter._localOffset;\n _currentBlock = iter._currentBlock;\n\n}\n\nvoid PixelIterator::init() {\n const Size& sz = _raster->size();\n if ( _box.isNull()) {\n _box = Box3D<>(sz);\n }\n _box.ensure(sz);\n\n _x = _box.min_corner().x();\n _y = _box.min_corner().y();\n _z = _box.min_corner().z();\n\n _endx = _box.max_corner().x();\n _endy = _box.max_corner().y();\n _endz = _box.max_corner().z();\n\n bool inside = contains(Pixel(_x,_y));\n if ( inside) {\n _raster->pix2value(Voxel(_x,_y,0));\n _grid = _raster->_grid.data();\n }\n\n initPosition();\n quint64 shift = _x + _y * 1e5 + (_z + 1) *1e10;\n _endpositionid = _positionid + shift;\n \/\/_endpositionid = _endx + _endy * 1e5 + _endz*1e10 + _raster->id() * 1e13;\n _isValid = inside;\n _xChanged = _yChanged = _zChanged = false;\n}\n\ninline bool PixelIterator::moveXYZ(int n) {\n _x += n * _step;\n _localOffset += n;\n _xChanged = true;\n _yChanged = _zChanged = false;\n if ( _x > _endx) {\n ++_y;\n _x = _box.min_corner().x();\n _yChanged = true;\n _localOffset += _x;\n if ( (_y % _grid->maxLines()) == 0) {\n ++_currentBlock;\n _localOffset = 0;\n }\n if ( _y > _endy) {\n ++_z;\n ++_currentBlock;\n _zChanged = true;\n _y = _box.min_corner().y();\n _localOffset = 0;\n if ( _z >= _endz) { \/\/ done with this iteration block\n _positionid = _endpositionid;\n return false;\n }\n }\n }\n return true;\n}\n\ninline bool PixelIterator::isAtEnd() const {\n return _x == _box.max_corner().x() &&\n _y == _box.max_corner().y() &&\n _z == _box.max_corner().z();\n}\n\nVoxel PixelIterator::position() const\n{\n return Voxel(_x, _y, _z);\n}\n\ninline bool PixelIterator::move(int n) {\n if (isAtEnd()) {\n _positionid = _endpositionid;\n return false;\n }\n bool ok;\n if ( _flow == fXYZ) {\n ok = moveXYZ(n);\n }\n else if ( _flow == fYXZ){\n }\n if (ok)\n _positionid = calcPosId();\n\n return ok;\n}\n\nPixelIterator& PixelIterator::operator=(const PixelIterator& iter) {\n copy(iter);\n return *this;\n}\n\ninline PixelIterator PixelIterator::operator++(int) {\n PixelIterator temp(*this);\n if(!move(1))\n return end();\n return temp;\n}\ninline PixelIterator PixelIterator::operator--(int) {\n PixelIterator temp(*this);\n move(-1);\n return temp;\n}\n\nbool PixelIterator::operator==(const PixelIterator& iter) const{\n return _positionid == iter._positionid;\n}\n\nbool PixelIterator::operator!=(const PixelIterator& iter) const{\n return ! operator ==(iter);\n}\n\n\n\nPixelIterator PixelIterator::end() const {\n return PixelIterator(_endpositionid);\n}\n\nvoid PixelIterator::setFlow(Flow flw) {\n _flow = flw;\n}\n\nbool PixelIterator::contains(const Pixel& pix) {\n return pix.x() >= _box.min_corner().x() &&\n pix.x() < _box.max_corner().x() &&\n pix.y() >= _box.min_corner().y() &&\n pix.y() < _box.max_corner().y();\n\n}\n\nbool PixelIterator::xchanged() const {\n return _xChanged;\n}\n\nbool PixelIterator::ychanged() const {\n return _yChanged;\n}\n\nbool PixelIterator::zchanged() const {\n return _zChanged;\n}\n\nvoid PixelIterator::initPosition() {\n const Size& sz = _raster->size();\n quint64 linearPos = _y * sz.xsize() + _x;\n _currentBlock = _y \/ _grid->maxLines();\n _localOffset = linearPos - _currentBlock * _grid->maxLines() * sz.xsize();\n _currentBlock += _z * _grid->blocksPerBand();\n\n _positionid = calcPosId();\n}\n\n\ninitialization of grid now in a more logical way#include \n#include \n#include \n#include \n#include \n\n#include \"raster.h\"\n#include \"pixeliterator.h\"\n\n\nusing namespace Ilwis;\n\nbool PixelIterator::isValid() const {\n return _isValid;\n}\n\nPixelIterator::PixelIterator() : _localOffset(0), _currentBlock(0), _step(0), _flow(fXYZ),_isValid(false),_positionid(0) {\n\n}\n\nPixelIterator::PixelIterator(IGridCoverage raster, const Box3D<>& box, double step) :\n _raster(raster),\n _box(box),\n _localOffset(0),\n _currentBlock(0),\n _step(step),\n _flow(fXYZ),\n _isValid(false)\n{\n init();\n}\n\nPixelIterator::PixelIterator(const PixelIterator& iter) {\n copy(iter);\n}\n\ninline PixelIterator::PixelIterator(quint64 posid ) :\n _localOffset(0),\n _currentBlock(0),\n _step(0),\n _flow(fXYZ),\n _isValid(false),\n _positionid(posid)\n{\n}\n\n\nvoid PixelIterator::copy(const PixelIterator &iter) {\n _raster = iter._raster;\n if ( _raster.isValid()) \/\/ TODO beyond end marker(end()) dont have a valid raster, no problem just yet but it maybe needed in the future\n _grid = _raster->_grid.data();\n _box = iter._box;\n _step = iter._step;\n _isValid = iter._isValid;\n _flow = iter._flow;\n _positionid = iter._positionid;\n _x = iter._x;\n _y = iter._y;\n _z = iter._z;\n _endx = iter._endx;\n _endy = iter._endy;\n _endz = iter._endz;\n _positionid = iter._positionid;\n _endpositionid = iter._endpositionid;\n _localOffset = iter._localOffset;\n _currentBlock = iter._currentBlock;\n\n}\n\nvoid PixelIterator::init() {\n const Size& sz = _raster->size();\n if ( _box.isNull()) {\n _box = Box3D<>(sz);\n }\n _box.ensure(sz);\n\n _x = _box.min_corner().x();\n _y = _box.min_corner().y();\n _z = _box.min_corner().z();\n\n _endx = _box.max_corner().x();\n _endy = _box.max_corner().y();\n _endz = _box.max_corner().z();\n\n bool inside = contains(Pixel(_x,_y));\n if ( inside) {\n _grid = _raster->grid();\n }\n\n initPosition();\n quint64 shift = _x + _y * 1e5 + (_z + 1) *1e10;\n _endpositionid = _positionid + shift;\n \/\/_endpositionid = _endx + _endy * 1e5 + _endz*1e10 + _raster->id() * 1e13;\n _isValid = inside;\n _xChanged = _yChanged = _zChanged = false;\n}\n\ninline bool PixelIterator::moveXYZ(int n) {\n _x += n * _step;\n _localOffset += n;\n _xChanged = true;\n _yChanged = _zChanged = false;\n if ( _x > _endx) {\n ++_y;\n _x = _box.min_corner().x();\n _yChanged = true;\n _localOffset += _x;\n if ( (_y % _grid->maxLines()) == 0) {\n ++_currentBlock;\n _localOffset = 0;\n }\n if ( _y > _endy) {\n ++_z;\n ++_currentBlock;\n _zChanged = true;\n _y = _box.min_corner().y();\n _localOffset = 0;\n if ( _z >= _endz) { \/\/ done with this iteration block\n _positionid = _endpositionid;\n return false;\n }\n }\n }\n return true;\n}\n\ninline bool PixelIterator::isAtEnd() const {\n return _x == _box.max_corner().x() &&\n _y == _box.max_corner().y() &&\n _z == _box.max_corner().z();\n}\n\nVoxel PixelIterator::position() const\n{\n return Voxel(_x, _y, _z);\n}\n\ninline bool PixelIterator::move(int n) {\n if (isAtEnd()) {\n _positionid = _endpositionid;\n return false;\n }\n bool ok;\n if ( _flow == fXYZ) {\n ok = moveXYZ(n);\n }\n else if ( _flow == fYXZ){\n }\n if (ok)\n _positionid = calcPosId();\n\n return ok;\n}\n\nPixelIterator& PixelIterator::operator=(const PixelIterator& iter) {\n copy(iter);\n return *this;\n}\n\ninline PixelIterator PixelIterator::operator++(int) {\n PixelIterator temp(*this);\n if(!move(1))\n return end();\n return temp;\n}\ninline PixelIterator PixelIterator::operator--(int) {\n PixelIterator temp(*this);\n move(-1);\n return temp;\n}\n\nbool PixelIterator::operator==(const PixelIterator& iter) const{\n return _positionid == iter._positionid;\n}\n\nbool PixelIterator::operator!=(const PixelIterator& iter) const{\n return ! operator ==(iter);\n}\n\n\n\nPixelIterator PixelIterator::end() const {\n return PixelIterator(_endpositionid);\n}\n\nvoid PixelIterator::setFlow(Flow flw) {\n _flow = flw;\n}\n\nbool PixelIterator::contains(const Pixel& pix) {\n return pix.x() >= _box.min_corner().x() &&\n pix.x() < _box.max_corner().x() &&\n pix.y() >= _box.min_corner().y() &&\n pix.y() < _box.max_corner().y();\n\n}\n\nbool PixelIterator::xchanged() const {\n return _xChanged;\n}\n\nbool PixelIterator::ychanged() const {\n return _yChanged;\n}\n\nbool PixelIterator::zchanged() const {\n return _zChanged;\n}\n\nvoid PixelIterator::initPosition() {\n const Size& sz = _raster->size();\n quint64 linearPos = _y * sz.xsize() + _x;\n _currentBlock = _y \/ _grid->maxLines();\n _localOffset = linearPos - _currentBlock * _grid->maxLines() * sz.xsize();\n _currentBlock += _z * _grid->blocksPerBand();\n\n _positionid = calcPosId();\n}\n\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/*\n * This file is part of the libetonyek project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \n\n#include \"KEYObject.h\"\n#include \"KEYPath.h\"\n#include \"KEYShape.h\"\n#include \"KEYTypes.h\"\n\n#include \"KEYShapeTest.h\"\n\nnamespace test\n{\n\nnamespace m = boost::math::constants;\n\nusing libetonyek::KEYPath;\nusing libetonyek::KEYPathPtr_t;\nusing libetonyek::KEYSize;\n\nvoid KEYShapeTest::setUp()\n{\n}\n\nvoid KEYShapeTest::tearDown()\n{\n}\n\nvoid KEYShapeTest::testMakePolygonPath()\n{\n using libetonyek::makePolygonPath;\n\n const KEYSize size(100, 100);\n\n \/\/ triangle\n {\n const double d = 25 * (2 - m::root_three());\n\n \/\/ FIXME: the shape is not scaled to whole width...\n KEYPath ref;\n ref.appendMoveTo(50, 0);\n ref.appendLineTo(100 - d, 75);\n ref.appendLineTo(d, 75);\n ref.appendClose();\n\n const KEYPathPtr_t test = makePolygonPath(size, 3);\n\n CPPUNIT_ASSERT(bool(test));\n CPPUNIT_ASSERT(*test == ref);\n }\n\n \/\/ diamond\n {\n KEYPath ref;\n ref.appendMoveTo(50, 0);\n ref.appendLineTo(100, 50);\n ref.appendLineTo(50, 100);\n ref.appendLineTo(0, 50);\n ref.appendClose();\n\n const KEYPathPtr_t test = makePolygonPath(size, 4);\n\n CPPUNIT_ASSERT(bool(test));\n CPPUNIT_ASSERT(*test == ref);\n }\n\n \/\/ octagon\n {\n const double d = 25 * (2 - m::root_two());\n\n KEYPath ref;\n ref.appendMoveTo(50, 0);\n ref.appendLineTo(100 - d, d);\n ref.appendLineTo(100, 50);\n ref.appendLineTo(100 - d, 100 -d);\n ref.appendLineTo(50, 100);\n ref.appendLineTo(d, 100 - d);\n ref.appendLineTo(0, 50);\n ref.appendLineTo(d, d);\n ref.appendClose();\n\n const KEYPathPtr_t test = makePolygonPath(size, 8);\n\n CPPUNIT_ASSERT(bool(test));\n CPPUNIT_ASSERT(*test == ref);\n }\n}\n\nvoid KEYShapeTest::testMakeRoundedRectanglePath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeArrowPath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeDoubleArrowPath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeStarPath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeConnectionPath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeCalloutPath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeQuoteBubblePath()\n{\n \/\/ TODO: implement me\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(KEYShapeTest);\n\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\nsomehow this constant is not there in older boost\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/*\n * This file is part of the libetonyek project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \n\n#include \"KEYObject.h\"\n#include \"KEYPath.h\"\n#include \"KEYShape.h\"\n#include \"KEYTypes.h\"\n\n#include \"KEYShapeTest.h\"\n\nnamespace test\n{\n\nnamespace m = boost::math::constants;\n\nusing libetonyek::KEYPath;\nusing libetonyek::KEYPathPtr_t;\nusing libetonyek::KEYSize;\n\nconst double etonyek_root_three(1.73205080756887729352744634150587236694280525381038062805580697945193301690880003708114618675724857567562614142e+00);\n\nvoid KEYShapeTest::setUp()\n{\n}\n\nvoid KEYShapeTest::tearDown()\n{\n}\n\nvoid KEYShapeTest::testMakePolygonPath()\n{\n using libetonyek::makePolygonPath;\n\n const KEYSize size(100, 100);\n\n \/\/ triangle\n {\n const double d = 25 * (2 - etonyek_root_three);\n\n \/\/ FIXME: the shape is not scaled to whole width...\n KEYPath ref;\n ref.appendMoveTo(50, 0);\n ref.appendLineTo(100 - d, 75);\n ref.appendLineTo(d, 75);\n ref.appendClose();\n\n const KEYPathPtr_t test = makePolygonPath(size, 3);\n\n CPPUNIT_ASSERT(bool(test));\n CPPUNIT_ASSERT(*test == ref);\n }\n\n \/\/ diamond\n {\n KEYPath ref;\n ref.appendMoveTo(50, 0);\n ref.appendLineTo(100, 50);\n ref.appendLineTo(50, 100);\n ref.appendLineTo(0, 50);\n ref.appendClose();\n\n const KEYPathPtr_t test = makePolygonPath(size, 4);\n\n CPPUNIT_ASSERT(bool(test));\n CPPUNIT_ASSERT(*test == ref);\n }\n\n \/\/ octagon\n {\n const double d = 25 * (2 - m::root_two());\n\n KEYPath ref;\n ref.appendMoveTo(50, 0);\n ref.appendLineTo(100 - d, d);\n ref.appendLineTo(100, 50);\n ref.appendLineTo(100 - d, 100 -d);\n ref.appendLineTo(50, 100);\n ref.appendLineTo(d, 100 - d);\n ref.appendLineTo(0, 50);\n ref.appendLineTo(d, d);\n ref.appendClose();\n\n const KEYPathPtr_t test = makePolygonPath(size, 8);\n\n CPPUNIT_ASSERT(bool(test));\n CPPUNIT_ASSERT(*test == ref);\n }\n}\n\nvoid KEYShapeTest::testMakeRoundedRectanglePath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeArrowPath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeDoubleArrowPath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeStarPath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeConnectionPath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeCalloutPath()\n{\n \/\/ TODO: implement me\n}\n\nvoid KEYShapeTest::testMakeQuoteBubblePath()\n{\n \/\/ TODO: implement me\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(KEYShapeTest);\n\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: calendar_gregorian.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2005-03-15 13:41:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _I18N_CALENDAR_GREGORIAN_HXX_\n#define _I18N_CALENDAR_GREGORIAN_HXX_\n\n#include \"calendarImpl.hxx\"\n#include \"nativenumbersupplier.hxx\"\n#include \"unicode\/calendar.h\"\n\n\/\/ ----------------------------------------------------\n\/\/ class Calendar_gregorian\n\/\/ ----------------------------------------------------\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\nstruct Era {\n sal_Int32 year;\n sal_Int32 month;\n sal_Int32 day;\n};\n\nclass Calendar_gregorian : public CalendarImpl\n{\npublic:\n\n \/\/ Constructors\n Calendar_gregorian();\n Calendar_gregorian(Era *_eraArray);\n\n \/**\n * Destructor\n *\/\n ~Calendar_gregorian();\n\n \/\/ Methods\n virtual void SAL_CALL loadCalendar(const rtl::OUString& uniqueID, const com::sun::star::lang::Locale& rLocale) throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setDateTime(double nTimeInDays) throw(com::sun::star::uno::RuntimeException);\n virtual double SAL_CALL getDateTime() throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setValue( sal_Int16 nFieldIndex, sal_Int16 nValue ) throw(com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getValue(sal_Int16 nFieldIndex) throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addValue(sal_Int16 nFieldIndex, sal_Int32 nAmount) throw(com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isValid() throw (com::sun::star::uno::RuntimeException);\n virtual Calendar SAL_CALL getLoadedCalendar() throw(com::sun::star::uno::RuntimeException);\n virtual rtl::OUString SAL_CALL getUniqueID() throw(com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getFirstDayOfWeek() throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setFirstDayOfWeek(sal_Int16 nDay) throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setMinimumNumberOfDaysForFirstWeek(sal_Int16 nDays) throw(com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getMinimumNumberOfDaysForFirstWeek() throw(com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getNumberOfMonthsInYear() throw(com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getNumberOfDaysInWeek() throw(com::sun::star::uno::RuntimeException);\n virtual com::sun::star::uno::Sequence < CalendarItem > SAL_CALL getMonths() throw(com::sun::star::uno::RuntimeException);\n virtual com::sun::star::uno::Sequence < CalendarItem > SAL_CALL getDays() throw(com::sun::star::uno::RuntimeException);\n virtual rtl::OUString SAL_CALL getDisplayName(sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType) throw(com::sun::star::uno::RuntimeException);\n\n \/\/ Methods in XExtendedCalendar\n virtual rtl::OUString SAL_CALL getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode ) throw (com::sun::star::uno::RuntimeException);\n\n \/\/XServiceInfo\n virtual rtl::OUString SAL_CALL getImplementationName() throw(com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw(com::sun::star::uno::RuntimeException);\n virtual com::sun::star::uno::Sequence < rtl::OUString > SAL_CALL getSupportedServiceNames() throw(com::sun::star::uno::RuntimeException);\n\nprotected:\n Era *eraArray;\n icu::Calendar *body;\n NativeNumberSupplier aNatNum;\n const sal_Char* cCalendar;\n com::sun::star::lang::Locale aLocale;\n sal_uInt32 fieldSet;\n sal_Int16 fieldValue[CalendarFieldIndex::FIELD_COUNT];\n sal_Int16 fieldSetValue[CalendarFieldIndex::FIELD_COUNT];\n virtual void SAL_CALL mapToGregorian() throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL mapFromGregorian() throw(com::sun::star::uno::RuntimeException);\n void SAL_CALL getValue() throw(com::sun::star::uno::RuntimeException);\nprivate:\n \/\/ submit fieldValue array according to fieldSet, plus YMDhms if >=0\n void SAL_CALL submitValues( sal_Int32 nYear, sal_Int32 nMonth, sal_Int32 nDay, sal_Int32 nHour, sal_Int32 nMinute, sal_Int32 nSecond, sal_Int32 nMilliSecond) throw(com::sun::star::uno::RuntimeException);\n void SAL_CALL setValue() throw(com::sun::star::uno::RuntimeException);\n void SAL_CALL init(Era *_eraArray) throw(com::sun::star::uno::RuntimeException);\n Calendar aCalendar;\n sal_Int16 aStartOfWeek;\n};\n\n\/\/ ----------------------------------------------------\n\/\/ class Calendar_hanja\n\/\/ ----------------------------------------------------\nclass Calendar_hanja : public Calendar_gregorian\n{\npublic:\n \/\/ Constructors\n Calendar_hanja();\n virtual void SAL_CALL loadCalendar(const rtl::OUString& uniqueID, const com::sun::star::lang::Locale& rLocale) throw(com::sun::star::uno::RuntimeException);\n virtual rtl::OUString SAL_CALL getDisplayName(sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType) throw(com::sun::star::uno::RuntimeException);\n};\n\n\/\/ ----------------------------------------------------\n\/\/ class Calendar_gengou\n\/\/ ----------------------------------------------------\nclass Calendar_gengou : public Calendar_gregorian\n{\npublic:\n \/\/ Constructors\n Calendar_gengou();\n};\n\n\/\/ ----------------------------------------------------\n\/\/ class Calendar_ROC\n\/\/ ----------------------------------------------------\nclass Calendar_ROC : public Calendar_gregorian\n{\npublic:\n \/\/ Constructors\n Calendar_ROC();\n};\n\n\/\/ ----------------------------------------------------\n\/\/ class Calendar_buddhist\n\/\/ ----------------------------------------------------\nclass Calendar_buddhist : public Calendar_gregorian\n{\npublic:\n \/\/ Constructors\n Calendar_buddhist();\n\n \/\/ Methods in XExtendedCalendar\n virtual rtl::OUString SAL_CALL getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode ) throw (com::sun::star::uno::RuntimeException);\n};\n\n} } } }\n\n#endif\nINTEGRATION: CWS ooo19126 (1.9.30); FILE MERGED 2005\/09\/05 17:47:22 rt 1.9.30.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: calendar_gregorian.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 16:48:54 $\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 _I18N_CALENDAR_GREGORIAN_HXX_\n#define _I18N_CALENDAR_GREGORIAN_HXX_\n\n#include \"calendarImpl.hxx\"\n#include \"nativenumbersupplier.hxx\"\n#include \"unicode\/calendar.h\"\n\n\/\/ ----------------------------------------------------\n\/\/ class Calendar_gregorian\n\/\/ ----------------------------------------------------\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\nstruct Era {\n sal_Int32 year;\n sal_Int32 month;\n sal_Int32 day;\n};\n\nclass Calendar_gregorian : public CalendarImpl\n{\npublic:\n\n \/\/ Constructors\n Calendar_gregorian();\n Calendar_gregorian(Era *_eraArray);\n\n \/**\n * Destructor\n *\/\n ~Calendar_gregorian();\n\n \/\/ Methods\n virtual void SAL_CALL loadCalendar(const rtl::OUString& uniqueID, const com::sun::star::lang::Locale& rLocale) throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setDateTime(double nTimeInDays) throw(com::sun::star::uno::RuntimeException);\n virtual double SAL_CALL getDateTime() throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setValue( sal_Int16 nFieldIndex, sal_Int16 nValue ) throw(com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getValue(sal_Int16 nFieldIndex) throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addValue(sal_Int16 nFieldIndex, sal_Int32 nAmount) throw(com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isValid() throw (com::sun::star::uno::RuntimeException);\n virtual Calendar SAL_CALL getLoadedCalendar() throw(com::sun::star::uno::RuntimeException);\n virtual rtl::OUString SAL_CALL getUniqueID() throw(com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getFirstDayOfWeek() throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setFirstDayOfWeek(sal_Int16 nDay) throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setMinimumNumberOfDaysForFirstWeek(sal_Int16 nDays) throw(com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getMinimumNumberOfDaysForFirstWeek() throw(com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getNumberOfMonthsInYear() throw(com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL getNumberOfDaysInWeek() throw(com::sun::star::uno::RuntimeException);\n virtual com::sun::star::uno::Sequence < CalendarItem > SAL_CALL getMonths() throw(com::sun::star::uno::RuntimeException);\n virtual com::sun::star::uno::Sequence < CalendarItem > SAL_CALL getDays() throw(com::sun::star::uno::RuntimeException);\n virtual rtl::OUString SAL_CALL getDisplayName(sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType) throw(com::sun::star::uno::RuntimeException);\n\n \/\/ Methods in XExtendedCalendar\n virtual rtl::OUString SAL_CALL getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode ) throw (com::sun::star::uno::RuntimeException);\n\n \/\/XServiceInfo\n virtual rtl::OUString SAL_CALL getImplementationName() throw(com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw(com::sun::star::uno::RuntimeException);\n virtual com::sun::star::uno::Sequence < rtl::OUString > SAL_CALL getSupportedServiceNames() throw(com::sun::star::uno::RuntimeException);\n\nprotected:\n Era *eraArray;\n icu::Calendar *body;\n NativeNumberSupplier aNatNum;\n const sal_Char* cCalendar;\n com::sun::star::lang::Locale aLocale;\n sal_uInt32 fieldSet;\n sal_Int16 fieldValue[CalendarFieldIndex::FIELD_COUNT];\n sal_Int16 fieldSetValue[CalendarFieldIndex::FIELD_COUNT];\n virtual void SAL_CALL mapToGregorian() throw(com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL mapFromGregorian() throw(com::sun::star::uno::RuntimeException);\n void SAL_CALL getValue() throw(com::sun::star::uno::RuntimeException);\nprivate:\n \/\/ submit fieldValue array according to fieldSet, plus YMDhms if >=0\n void SAL_CALL submitValues( sal_Int32 nYear, sal_Int32 nMonth, sal_Int32 nDay, sal_Int32 nHour, sal_Int32 nMinute, sal_Int32 nSecond, sal_Int32 nMilliSecond) throw(com::sun::star::uno::RuntimeException);\n void SAL_CALL setValue() throw(com::sun::star::uno::RuntimeException);\n void SAL_CALL init(Era *_eraArray) throw(com::sun::star::uno::RuntimeException);\n Calendar aCalendar;\n sal_Int16 aStartOfWeek;\n};\n\n\/\/ ----------------------------------------------------\n\/\/ class Calendar_hanja\n\/\/ ----------------------------------------------------\nclass Calendar_hanja : public Calendar_gregorian\n{\npublic:\n \/\/ Constructors\n Calendar_hanja();\n virtual void SAL_CALL loadCalendar(const rtl::OUString& uniqueID, const com::sun::star::lang::Locale& rLocale) throw(com::sun::star::uno::RuntimeException);\n virtual rtl::OUString SAL_CALL getDisplayName(sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType) throw(com::sun::star::uno::RuntimeException);\n};\n\n\/\/ ----------------------------------------------------\n\/\/ class Calendar_gengou\n\/\/ ----------------------------------------------------\nclass Calendar_gengou : public Calendar_gregorian\n{\npublic:\n \/\/ Constructors\n Calendar_gengou();\n};\n\n\/\/ ----------------------------------------------------\n\/\/ class Calendar_ROC\n\/\/ ----------------------------------------------------\nclass Calendar_ROC : public Calendar_gregorian\n{\npublic:\n \/\/ Constructors\n Calendar_ROC();\n};\n\n\/\/ ----------------------------------------------------\n\/\/ class Calendar_buddhist\n\/\/ ----------------------------------------------------\nclass Calendar_buddhist : public Calendar_gregorian\n{\npublic:\n \/\/ Constructors\n Calendar_buddhist();\n\n \/\/ Methods in XExtendedCalendar\n virtual rtl::OUString SAL_CALL getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode ) throw (com::sun::star::uno::RuntimeException);\n};\n\n} } } }\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n\n#define PI 3.14159265359\n\nusing namespace std;\n\nint deg = 0;\n\nvoid radioactive();\nvoid rotate();\nvoid init();\n\nint main(int argc, char **argv)\n{\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);\n\tglutInitWindowSize(500,500);\n\tglutInitWindowPosition(0,0);\n\tglutCreateWindow(\"radioactive\");\n\tglutIdleFunc(rotate);\n\tglutDisplayFunc(radioactive);\n\tinit();\n\tglutMainLoop();\n}\n\nvoid init()\n{\n\tglClearColor(1.0 ,1.0 ,0.0 ,0.0);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n}\n\nvoid radioactive()\n{\n\tglClear(GL_COLOR_BUFFER_BIT);\n\tglColor3f(0.0, 0.0, 0.0);\n\tglRotated(deg, 0.0, 0.0, 1.0);\n\tglPolygonMode(GL_FRONT, GL_FILL);\n\tfor (double d = PI\/2.0; d < 2.0*PI; d += 2*PI\/3.0)\n\t{\n\t\tglBegin(GL_TRIANGLE_FAN);\n\t\t\tglVertex2d(0.0,0.0);\n\t\t\tfor (double dis = -PI\/6; dis < PI\/6; dis += 0.1)\n\t\t\t{\n\t\t\t\tglColor3f(0.0, 0.0, 0.0);\n\t\t\t\tglVertex2d(cos(d + dis), sin(d + dis));\n\t\t\t}\n\t\tglEnd();\n\t}\n\tglLoadIdentity();\n\tglutSwapBuffers();\n}\n\nvoid rotate()\n{\n\tdeg = (deg < 360) ? deg + 1 : 0;\n\t glutPostRedisplay();\n}\nrgba -> rgb#include \n#include \n\n#define PI 3.14159265359\n\nusing namespace std;\n\nint deg = 0;\n\nvoid radioactive();\nvoid rotate();\nvoid init();\n\nint main(int argc, char **argv)\n{\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);\n\tglutInitWindowSize(500,500);\n\tglutInitWindowPosition(0,0);\n\tglutCreateWindow(\"Radioactive\");\n\tglutIdleFunc(rotate);\n\tglutDisplayFunc(radioactive);\n\tinit();\n\tglutMainLoop();\n}\n\nvoid init()\n{\n\tglClearColor(1.0 ,1.0 ,0.0 ,0.0);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n}\n\nvoid radioactive()\n{\n\tglClear(GL_COLOR_BUFFER_BIT);\n\tglColor3f(0.0, 0.0, 0.0);\n\tglRotated(deg, 0.0, 0.0, 1.0);\n\tglPolygonMode(GL_FRONT, GL_FILL);\n\tfor (double d = PI\/2.0; d < 2.0*PI; d += 2*PI\/3.0)\n\t{\n\t\tglBegin(GL_TRIANGLE_FAN);\n\t\t\tglVertex2d(0.0,0.0);\n\t\t\tfor (double dis = -PI\/6; dis < PI\/6; dis += 0.1)\n\t\t\t{\n\t\t\t\tglColor3f(0.0, 0.0, 0.0);\n\t\t\t\tglVertex2d(cos(d + dis), sin(d + dis));\n\t\t\t}\n\t\tglEnd();\n\t}\n\tglLoadIdentity();\n\tglutSwapBuffers();\n}\n\nvoid rotate()\n{\n\tdeg = (deg < 360) ? deg + 1 : 0;\n\t glutPostRedisplay();\n}\n<|endoftext|>"} {"text":"#ifndef VEXCL_FFT_HPP\n#define VEXCL_FFT_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012 Denis Demidov \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file stencil.hpp\n * \\author Pascal Germroth \n * \\brief Fast Fourier Transformation.\n *\/\n\n\/\/ TODO: multivector (AMD FFT supports batch transforms!)\n#include \n\n#ifdef USE_AMD_FFT\n# include \n#else\n# include \n#endif\n\nnamespace vex {\n\n\/\/\/ \\cond INTERNAL\n\ntemplate \nstruct fft_expr\n : vector_expression< boost::proto::terminal< additive_vector_transform >::type >\n{\n F &f;\n vector &input;\n\n fft_expr(F &f, vector &x) : f(f), input(x) {}\n\n template \n void apply(vector &output) const\n {\n f.template execute(input, output);\n }\n};\n\n\n#ifdef USE_AMD_FFT\nenum fft_direction {\n forward = CLFFT_FORWARD,\n inverse = CLFFT_BACKWARD\n};\n\n\/\/ AMD FFT needs Setup\/Teardown calls for the whole library.\n\/\/ Sequential Setup\/Teardowns are OK, but overlapping is not.\nsize_t fft_ref_count = 0;\n\/\/ TODO: breaks when two objects, both using FFT, are linked.\n\n\n\/**\n * An FFT functor. Assumes the vector is in row major format and densely packed.\n * Only supports a single device, only 2^a 3^b 5^c sizes, only single precision.\n * 1-3 dimensions.\n * Usage:\n * \\code\n * FFT fft(ctx.queue(), {width, height});\n * output = fft(input); \/\/ out-of-place transform\n * data = fft(data); \/\/ in-place transform\n * \\endcode\n *\/\ntemplate \nstruct FFT {\n static_assert(std::is_same::value &&\n std::is_same::value,\n \"Only single precision Complex-to-Complex transformations implemented.\");\n\n typedef FFT this_t;\n typedef T0 input_t;\n typedef T1 output_t;\n\n const std::vector &queues;\n clAmdFftPlanHandle plan;\n fft_direction dir;\n\n void check_error(clAmdFftStatus status) const {\n if(status != CL_SUCCESS)\n throw cl::Error(status, \"AMD FFT\");\n }\n\n template \n FFT(const std::vector &queues,\n const Array &lengths, fft_direction dir = forward)\n : queues(queues), plan(0), dir(dir) {\n init(lengths);\n }\n\n FFT(const std::vector &queues,\n size_t length, fft_direction dir = forward)\n : queues(queues), plan(0), dir(dir) {\n std::array lengths = {{length}};\n init(lengths);\n }\n \n#ifndef BOOST_NO_INITIALIZER_LISTS\n FFT(const std::vector &queues,\n std::initializer_list lengths, fft_direction dir = forward)\n : queues(queues), plan(0), dir(dir) {\n init(lengths);\n }\n#endif\n\n template \n void init(const Array &lengths) {\n assert(lengths.size() >= 1 && lengths.size() <= 3);\n size_t _lengths[lengths.size()];\n std::copy(std::begin(lengths), std::end(lengths), _lengths);\n \/\/ TODO: all queues must be in same context\n cl::Context context = static_cast(queues[0]).getInfo();\n if(fft_ref_count++ == 0)\n check_error(clAmdFftSetup(NULL));\n check_error(clAmdFftCreateDefaultPlan(&plan, context(),\n static_cast(lengths.size()), _lengths));\n check_error(clAmdFftSetPlanPrecision(plan, CLFFT_SINGLE)); \n check_error(clAmdFftSetLayout(plan, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED));\n }\n\n ~FFT() {\n if(plan)\n check_error(clAmdFftDestroyPlan(&plan));\n if(--fft_ref_count == 0)\n check_error(clAmdFftTeardown());\n }\n \n\n template \n void execute(const vector &input, vector &output) const {\n assert(!append); \/\/ TODO: that should be static.\n static_assert(!negate, \"Negation not implemented yet.\");\n \/\/ Doesn't support split buffers.\n assert(queues.size() == 1);\n cl_mem input_buf = input(0)();\n cl_mem output_buf = output(0)();\n check_error(clAmdFftSetResultLocation(plan,\n input_buf == output_buf ? CLFFT_INPLACE : CLFFT_OUTOFPLACE));\n cl_command_queue _queues[queues.size()];\n for(size_t i = 0 ; i < queues.size() ; i++)\n _queues[i] = queues[i]();\n check_error(clAmdFftEnqueueTransform(plan, static_cast(dir),\n queues.size(), _queues,\n \/* wait events *\/0, NULL, \/* out events *\/NULL,\n &input_buf, &output_buf, NULL));\n }\n\n\n \/\/ User call\n fft_expr operator()(vector &x) {\n return {*this, x};\n }\n};\n#else \/\/ USE_AMD_FFT\n\nenum direction {\n forward, inverse\n};\n\ntemplate \nstruct FFT {\n typedef FFT this_t;\n typedef T0 input_t;\n typedef T1 output_t;\n typedef typename cl::scalar_of::type T0s;\n typedef typename cl::scalar_of::type T1s;\n static_assert(std::is_same::value, \"Input and output must have same precision.\");\n typedef T0s T;\n\n fft::plan plan;\n\n \/\/\/ 1D constructor\n FFT(const std::vector &queues,\n size_t length, direction dir = forward)\n : plan(queues, {length}, dir == inverse) {}\n\n \/\/\/ N-D constructors\n FFT(const std::vector &queues,\n const std::vector &lengths, direction dir = forward)\n : plan(queues, lengths, dir == inverse) {}\n\n#ifndef BOOST_NO_INITIALIZER_LISTS\n FFT(const std::vector &queues,\n const std::initializer_list &lengths, direction dir = forward)\n : plan(queues, lengths, dir == inverse) {}\n#endif\n\n template \n void execute(vector &input, vector &output) {\n assert(!append);\n static_assert(!negate, \"Not implemented\");\n plan(input, output);\n }\n\n\n \/\/ User call\n fft_expr operator()(vector &x) {\n return {*this, x};\n }\n};\n\n#endif\n\n\n}\n\n#endif\nReview suggestions#ifndef VEXCL_FFT_HPP\n#define VEXCL_FFT_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012 Denis Demidov \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file stencil.hpp\n * \\author Pascal Germroth \n * \\brief Fast Fourier Transformation.\n *\/\n\n\/\/ TODO: multivector (AMD FFT supports batch transforms!)\n#include \n\n#ifdef USE_AMD_FFT\n# include \n#else\n# include \n#endif\n\nnamespace vex {\n\n\/\/\/ \\cond INTERNAL\n\ntemplate \nstruct fft_expr\n : vector_expression< boost::proto::terminal< additive_vector_transform >::type >\n{\n F &f;\n vector &input;\n\n fft_expr(F &f, vector &x) : f(f), input(x) {}\n\n template \n void apply(vector &output) const\n {\n f.template execute(input, output);\n }\n};\n\n\n#ifdef USE_AMD_FFT\nenum fft_direction {\n forward = CLFFT_FORWARD,\n inverse = CLFFT_BACKWARD\n};\n\nvoid fft_check_error(clAmdFftStatus status) const {\n if(status != CL_SUCCESS)\n throw cl::Error(status, \"AMD FFT\");\n}\n\n\/\/ AMD FFT needs Setup\/Teardown calls for the whole library.\n\/\/ Sequential Setup\/Teardowns are OK, but overlapping is not.\nstruct amd_context_t {\n amd_context_t() { fft_check_error(clAmdFftSetup(NULL)); }\n ~amd_context_t() { fft_check_error(clAmdFftTeardown()); }\n};\nstatic std::unique_ptr amd_context;\n\n\n\/**\n * An FFT functor. Assumes the vector is in row major format and densely packed.\n * Only supports a single device, only 2^a 3^b 5^c sizes, only single precision.\n * 1-3 dimensions.\n * Usage:\n * \\code\n * FFT fft(ctx.queue(), {width, height});\n * output = fft(input); \/\/ out-of-place transform\n * data = fft(data); \/\/ in-place transform\n * \\endcode\n *\/\ntemplate \nstruct FFT {\n static_assert(std::is_same::value &&\n std::is_same::value,\n \"Only single precision Complex-to-Complex transformations implemented.\");\n\n typedef FFT this_t;\n typedef T0 input_t;\n typedef T1 output_t;\n\n const std::vector &queues;\n clAmdFftPlanHandle plan;\n fft_direction dir;\n\n template \n FFT(const std::vector &queues,\n const Array &lengths, fft_direction dir = forward)\n : queues(queues), plan(0), dir(dir) {\n init(lengths);\n }\n\n FFT(const std::vector &queues,\n size_t length, fft_direction dir = forward)\n : queues(queues), plan(0), dir(dir) {\n std::array lengths = {{length}};\n init(lengths);\n }\n \n#ifndef BOOST_NO_INITIALIZER_LISTS\n FFT(const std::vector &queues,\n std::initializer_list lengths, fft_direction dir = forward)\n : queues(queues), plan(0), dir(dir) {\n init(lengths);\n }\n#endif\n\n template \n void init(const Array &lengths) {\n assert(lengths.size() >= 1 && lengths.size() <= 3);\n assert(queues.size() == 1);\n if(!amd_context) amd_context.reset(new amd_context_t());\n size_t _lengths[3];\n std::copy(std::begin(lengths), std::end(lengths), _lengths);\n cl::Context context = qctx(queues[0]);\n if(fft_ref_count++ == 0)\n check_error(clAmdFftSetup(NULL));\n check_error(clAmdFftCreateDefaultPlan(&plan, context(),\n static_cast(lengths.size()), _lengths));\n check_error(clAmdFftSetPlanPrecision(plan, CLFFT_SINGLE)); \n check_error(clAmdFftSetLayout(plan, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED));\n }\n\n ~FFT() {\n if(plan)\n check_error(clAmdFftDestroyPlan(&plan));\n if(--fft_ref_count == 0)\n check_error(clAmdFftTeardown());\n }\n \n\n template \n void execute(const vector &input, vector &output) const {\n static_assert(!append, \"Appending not implemented yet.\");\n static_assert(!negate, \"Negation not implemented yet.\");\n cl_mem input_buf = input(0)();\n cl_mem output_buf = output(0)();\n fft_check_error(clAmdFftSetResultLocation(plan,\n input_buf == output_buf ? CLFFT_INPLACE : CLFFT_OUTOFPLACE));\n cl_command_queue queue = queues[0]();\n fft_check_error(clAmdFftEnqueueTransform(plan,\n static_cast(dir),\n 1, &queue, \/* wait events *\/0, NULL, \/* out events *\/NULL,\n &input_buf, &output_buf, NULL));\n }\n\n\n \/\/ User call\n fft_expr operator()(vector &x) {\n return {*this, x};\n }\n};\n#else \/\/ USE_AMD_FFT\n\nenum direction {\n forward, inverse\n};\n\ntemplate \nstruct FFT {\n typedef FFT this_t;\n typedef T0 input_t;\n typedef T1 output_t;\n typedef typename cl::scalar_of::type T0s;\n typedef typename cl::scalar_of::type T1s;\n static_assert(std::is_same::value, \"Input and output must have same precision.\");\n typedef T0s T;\n\n fft::plan plan;\n\n \/\/\/ 1D constructor\n FFT(const std::vector &queues,\n size_t length, direction dir = forward)\n : plan(queues, {length}, dir == inverse) {}\n\n \/\/\/ N-D constructors\n FFT(const std::vector &queues,\n const std::vector &lengths, direction dir = forward)\n : plan(queues, lengths, dir == inverse) {}\n\n#ifndef BOOST_NO_INITIALIZER_LISTS\n FFT(const std::vector &queues,\n const std::initializer_list &lengths, direction dir = forward)\n : plan(queues, lengths, dir == inverse) {}\n#endif\n\n template \n void execute(vector &input, vector &output) {\n assert(!append);\n static_assert(!negate, \"Not implemented\");\n plan(input, output);\n }\n\n\n \/\/ User call\n fft_expr operator()(vector &x) {\n return {*this, x};\n }\n};\n\n#endif\n\n\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \"scatter-vm\/sslang_vm.h\"\n\nScript g_Script;start vm test#include \n#include \n#include \n\n#include \"scatter-asm\/ssasm_pre.h\"\n#include \"scatter-vm\/ssvm_pre.h\"\n#include \"scatter-vm\/sslang_vm.h\"\n#include \"scatter-vm\/ssvm.h\"\n\nScript g_Script;\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 2)\n\t{\n\t\tprintf(\"Wrong usage !\\n\");\n\t\treturn 0;\n\t}\n\n\tchar* exeFilename = (char*) malloc(strlen(argv[1]) + 1);\n\tstrcpy(exeFilename, argv[1]);\n\n\tInit();\n\n\tint errorCode = LoadScript(exeFilename);\n\n\tif (errorCode != LOAD_OK)\n\t{\n\t\tprintf(\"Error: \");\n\t\tswitch (errorCode)\n\t\t{\n\t\tcase LOAD_ERROR_FAIL_FILE_OPEN:\n\t\t\tprintf(\"Can not open sse file\");\n\t\t\tbreak;\n\n\t\tcase LOAD_ERROR_INVALID_SSE:\n\t\t\tprintf(\"Invalid sse file\");\n\t\t\tbreak;\n\n\t\tcase LOAD_ERROR_UNSOPPORTED_VERSION:\n\t\t\tprintf(\"Unsupported sse version\");\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tprintf(\".\\n\");\n\n\t\treturn 0;\n\t}\n}<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013, Hernan Saez\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 * * 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 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\" 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 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#include \"RenderSystem.hpp\"\n\n#include \"Rendering\/ComputePass.hpp\"\n#include \"Rendering\/FrameGraphOperation.hpp\"\n#include \"Rendering\/Operations\/OperationUtils.hpp\"\n#include \"Rendering\/Operations\/Operations.hpp\"\n#include \"Rendering\/Operations\/Operations_computeRT.hpp\"\n#include \"Rendering\/Operations\/Operations_debugLightCascades.hpp\"\n#include \"Rendering\/Operations\/Operations_debugShadowAtlas.hpp\"\n#include \"Rendering\/Operations\/Operations_softRT.hpp\"\n#include \"Rendering\/Operations\/Operations_ssao.hpp\"\n#include \"Rendering\/RenderPass.hpp\"\n#include \"Rendering\/ScenePass.hpp\"\n#include \"Simulation\/Simulation.hpp\"\n\n#include \n#include \n#include \n\nnamespace crimild {\n\n namespace utils {\n\n template< typename Fn >\n void traverse( SharedPointer< FrameGraphOperation > root, Fn fn ) noexcept\n {\n std::queue< SharedPointer< FrameGraphOperation > > frontier;\n std::unordered_set< FrameGraphOperation * > expanded;\n std::unordered_map< FrameGraphOperation *, size_t > blockCount;\n\n frontier.push( root );\n while ( !frontier.empty() ) {\n auto current = frontier.front();\n frontier.pop();\n if ( expanded.count( current.get() ) != 0 ) {\n \/\/ already expanded\n continue;\n }\n expanded.insert( current.get() );\n fn( current );\n current->eachBlockedBy(\n [ & ]( auto pass ) {\n if ( blockCount.count( pass.get() ) == 0 ) {\n blockCount[ pass.get() ] = pass->getBlockCount();\n }\n\n --blockCount[ pass.get() ];\n if ( blockCount[ pass.get() ] == 0 ) {\n frontier.push( pass );\n }\n } );\n }\n }\n\n }\n}\n\nusing namespace crimild;\n\nvoid RenderSystem::start( void ) noexcept\n{\n useDefaultRenderPath();\n}\n\n#include \n#include \n#include \n\ntemplate< typename Fn >\nvoid traverse( SharedPointer< FrameGraphOperation > root, Fn fn ) noexcept\n{\n std::queue< SharedPointer< FrameGraphOperation > > frontier;\n std::unordered_set< FrameGraphOperation * > expanded;\n std::unordered_map< FrameGraphOperation *, size_t > blockCount;\n\n frontier.push( root );\n while ( !frontier.empty() ) {\n auto current = frontier.front();\n frontier.pop();\n if ( expanded.count( get_ptr( current ) ) != 0 ) {\n \/\/ already expanded\n continue;\n }\n expanded.insert( crimild::get_ptr( current ) );\n fn( current );\n current->eachBlockedBy(\n [ & ]( auto passPtr ) {\n auto pass = get_ptr( passPtr );\n if ( blockCount.count( pass ) == 0 ) {\n \/\/ TODO: if passes are discarded because they don't really add up to the final image,\n \/\/ this number will not be correct, since it will show more blocks than actually are.\n blockCount[ pass ] = pass->getBlockCount();\n }\n\n --blockCount[ pass ];\n if ( blockCount[ pass ] == 0 ) {\n frontier.push( passPtr );\n }\n } );\n }\n}\n\nvoid RenderSystem::sort( SharedPointer< FrameGraphOperation > const &root ) noexcept\n{\n m_scenePasses.clear();\n m_renderPasses.clear();\n m_computePasses.clear();\n\n std::list< SharedPointer< FrameGraphOperation > > sorted;\n\n traverse(\n root,\n [ & ]( auto pass ) {\n if ( pass->getType() == FrameGraphOperation::Type::SCENE_PASS ) {\n m_scenePasses.add( cast_ptr< ScenePass >( pass ) );\n } else if ( pass->getType() == FrameGraphOperation::Type::RENDER_PASS ) {\n m_renderPasses.add( cast_ptr< RenderPass >( pass ) );\n } else if ( pass->getType() == FrameGraphOperation::Type::COMPUTE_PASS ) {\n m_computePasses.add( cast_ptr< ComputePass >( pass ) );\n }\n sorted.push_front( pass );\n } );\n\n FrameGraphOperation::Priority p = 0;\n for ( auto pass : sorted ) {\n pass->setPriority( p++ );\n }\n\n m_scenePasses = m_scenePasses.reversed();\n m_renderPasses = m_renderPasses.reversed();\n m_computePasses = m_computePasses.reversed();\n}\n\nvoid RenderSystem::onPreRender( void ) noexcept\n{\n System::onPreRender();\n\n if ( m_frameGraph != nullptr && m_renderPasses.empty() ) {\n sort( m_frameGraph );\n }\n\n m_scenePasses.each(\n []( auto pass ) {\n \/\/ Scene passes are executed every frame with no image index\n pass->apply( 0, true );\n } );\n}\n\nvoid RenderSystem::setFrameGraph( SharedPointer< FrameGraphOperation > const &frameGraph ) noexcept\n{\n m_frameGraph = frameGraph;\n\n m_renderPasses.clear();\n m_scenePasses.clear();\n m_computePasses.clear();\n\n m_sortedOperations.clear();\n\n m_graphicsCommands.clear();\n m_computeCommands.clear();\n\n broadcastMessage( messaging::FrameGraphDidChange {} );\n}\n\nRenderSystem::CommandBufferArray &RenderSystem::getGraphicsCommands( Size imageIndex, Bool forceAll ) noexcept\n{\n m_graphicsCommands.clear();\n m_renderPasses.each(\n [ & ]( auto pass ) {\n if ( pass->apply( imageIndex, forceAll ) ) {\n m_graphicsCommands.add( get_ptr( pass->getCommandBuffers()[ imageIndex ] ) );\n }\n } );\n\n return m_graphicsCommands;\n}\n\nRenderSystem::CommandBufferArray &RenderSystem::getComputeCommands( Size imageIndex, Bool forceAll ) noexcept\n{\n m_computeCommands.clear();\n m_computePasses.each(\n [ & ]( auto pass ) {\n if ( pass->apply( imageIndex, forceAll ) ) {\n m_computeCommands.add( get_ptr( pass->getCommandBuffers()[ imageIndex ] ) );\n }\n } );\n\n return m_computeCommands;\n}\n\nvoid RenderSystem::useDefaultRenderPath( Bool enableDebug ) noexcept\n{\n setFrameGraph(\n [ enableDebug ] {\n using namespace crimild::framegraph;\n\n auto settings = Simulation::getInstance()->getSettings();\n\n auto renderables = fetchRenderables();\n auto litRenderables = renderables->getProduct( 0 );\n auto unlitRenderables = renderables->getProduct( 1 );\n auto envRenderables = renderables->getProduct( 2 );\n\n auto gBuffer = gBufferPass( litRenderables );\n auto albedo = gBuffer->getProduct( 0 );\n auto positions = gBuffer->getProduct( 1 );\n auto normals = gBuffer->getProduct( 2 );\n auto materials = gBuffer->getProduct( 3 );\n auto depth = gBuffer->getProduct( 4 );\n\n if ( settings->get< Bool >( \"debug.show_albedo\" ) ) {\n return present( albedo );\n }\n\n if ( settings->get< Bool >( \"debug.show_metallic\" ) ) {\n return channel( \"metallic\", materials, 0 );\n }\n\n if ( settings->get< Bool >( \"debug.show_roughness\" ) ) {\n return channel( \"roughness\", materials, 1 );\n }\n\n if ( settings->get< Bool >( \"debug.show_ambient_occlusion\" ) ) {\n return channel( \"ambientOcclusion\", materials, 2 );\n }\n\n if ( settings->get< Bool >( \"debug.show_normals\" ) ) {\n return present( normals );\n }\n\n auto reflectionAtlasPass = computeReflectionMap( envRenderables );\n auto irradianceMapPass = computeIrradianceMap( useResource( reflectionAtlasPass ) );\n auto prefilterMapPass = computePrefilterMap( useResource( reflectionAtlasPass ) );\n auto brdfLutPass = computeBRDFLUT( nullptr );\n\n auto shadowAtlasPass = renderShadowAtlas( litRenderables );\n\n auto shadowAtlas = useResource( shadowAtlasPass );\n auto reflectionAtlas = useResource( reflectionAtlasPass );\n auto irradianceAtlas = useResource( irradianceMapPass );\n auto prefilterAtlas = useResource( prefilterMapPass );\n auto brdfLUT = useResource( brdfLutPass );\n\n \/\/ todo: rename to \"localLightingPass\"\n auto lit = lightingPass(\n albedo,\n positions,\n normals,\n materials,\n depth,\n shadowAtlas );\n\n \/\/ TODO: rename to \"globalLightingPass\"\n auto ibl = iblPass(\n albedo,\n positions,\n normals,\n materials,\n depth,\n reflectionAtlas,\n irradianceAtlas,\n prefilterAtlas,\n brdfLUT );\n\n auto unlit = forwardUnlitPass( unlitRenderables, nullptr, depth );\n\n \/\/ Render environment objects in HDR\n auto env = forwardUnlitPass(\n envRenderables,\n useColorAttachment( \"envObjects\/color\", Format::R32G32B32A32_SFLOAT ),\n depth );\n\n auto composed = blend(\n {\n useResource( lit ),\n useResource( ibl ),\n useResource( env ),\n } );\n\n if ( settings->get< Bool >( \"video.ssao.enabled\", false ) ) {\n auto withBlur = [ & ]( auto op ) {\n if ( settings->get< Bool >( \"video.ssao.blur\", true ) ) {\n return blur( useResource( op ) );\n } else {\n return op;\n }\n };\n\n composed = blend(\n {\n useResource( composed ),\n useResource(\n withBlur(\n ssao(\n positions,\n normals ) ) ),\n },\n \"multiply\" );\n }\n\n auto ret = composed;\n auto tonemapped = composed;\n\n if ( settings->get< Bool >( \"video.bloom.enabled\", false ) ) {\n auto bloom = brightPassFilter(\n useResource( composed ),\n Vector3f { 0.2126f, 0.7152f, 0.0722f } );\n\n bloom = gaussianBlur( useResource( bloom ) );\n\n auto tonemapped = tonemapping(\n useResource(\n composed ) );\n\n \/\/ apply bloom after tonemapping\n ret = blend(\n { useResource( tonemapped ), \/\/ forces format to RGB8\n useResource( bloom ) } );\n\n } else {\n tonemapped = tonemapping(\n useResource(\n composed ) );\n ret = tonemapped;\n }\n\n ret = blend(\n {\n useResource( unlit ),\n useResource( ret ),\n } );\n\n if ( enableDebug || settings->get< Bool >( \"debug.show_render_passes\", false ) ) {\n auto lightCascades = debugLightCascades(\n albedo,\n positions,\n normals,\n materials,\n depth,\n shadowAtlas );\n\n auto shadowAtlasDebug = debugShadowAtlas( shadowAtlas );\n\n ret = debug(\n {\n useResource( ret ),\n albedo,\n positions,\n normals,\n materials,\n depth,\n useResource( shadowAtlasDebug ),\n reflectionAtlas,\n irradianceAtlas,\n prefilterAtlas,\n brdfLUT,\n useResource( lightCascades ),\n useResource( lit ),\n useResource( ibl ),\n useResource( tonemapped ),\n useResource( unlit ),\n useResource( env ),\n } );\n }\n\n return ret;\n }() );\n}\n\nvoid RenderSystem::useRTSoftRenderPath( Bool enableDebug ) noexcept\n{\n setFrameGraph(\n [ & ] {\n using namespace crimild::framegraph;\n return present( tonemapping( useResource( softRT() ) ) );\n }() );\n}\n\nvoid RenderSystem::useRTComputeRenderPath( Bool enableDebug ) noexcept\n{\n setFrameGraph(\n [ & ] {\n using namespace crimild::framegraph;\n return present( tonemapping( useResource( computeRT() ) ) );\n }() );\n}\nAllow render system to start with different render paths\/*\n * Copyright (c) 2013, Hernan Saez\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 * * 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 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\" 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 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#include \"RenderSystem.hpp\"\n\n#include \"Rendering\/ComputePass.hpp\"\n#include \"Rendering\/FrameGraphOperation.hpp\"\n#include \"Rendering\/Operations\/OperationUtils.hpp\"\n#include \"Rendering\/Operations\/Operations.hpp\"\n#include \"Rendering\/Operations\/Operations_computeRT.hpp\"\n#include \"Rendering\/Operations\/Operations_debugLightCascades.hpp\"\n#include \"Rendering\/Operations\/Operations_debugShadowAtlas.hpp\"\n#include \"Rendering\/Operations\/Operations_softRT.hpp\"\n#include \"Rendering\/Operations\/Operations_ssao.hpp\"\n#include \"Rendering\/RenderPass.hpp\"\n#include \"Rendering\/ScenePass.hpp\"\n#include \"Simulation\/Simulation.hpp\"\n\n#include \n#include \n#include \n\nnamespace crimild {\n\n namespace utils {\n\n template< typename Fn >\n void traverse( SharedPointer< FrameGraphOperation > root, Fn fn ) noexcept\n {\n std::queue< SharedPointer< FrameGraphOperation > > frontier;\n std::unordered_set< FrameGraphOperation * > expanded;\n std::unordered_map< FrameGraphOperation *, size_t > blockCount;\n\n frontier.push( root );\n while ( !frontier.empty() ) {\n auto current = frontier.front();\n frontier.pop();\n if ( expanded.count( current.get() ) != 0 ) {\n \/\/ already expanded\n continue;\n }\n expanded.insert( current.get() );\n fn( current );\n current->eachBlockedBy(\n [ & ]( auto pass ) {\n if ( blockCount.count( pass.get() ) == 0 ) {\n blockCount[ pass.get() ] = pass->getBlockCount();\n }\n\n --blockCount[ pass.get() ];\n if ( blockCount[ pass.get() ] == 0 ) {\n frontier.push( pass );\n }\n } );\n }\n }\n\n }\n}\n\nusing namespace crimild;\n\nvoid RenderSystem::start( void ) noexcept\n{\n auto settings = Simulation::getInstance()->getSettings();\n auto renderPath = settings->get< std::string >( \"video.render_path\", \"default\" );\n if ( renderPath == \"softRT\" ) {\n useRTSoftRenderPath();\n } else if ( renderPath == \"computeRT\" ) {\n useRTComputeRenderPath();\n } else {\n useDefaultRenderPath();\n }\n}\n\n#include \n#include \n#include \n\ntemplate< typename Fn >\nvoid traverse( SharedPointer< FrameGraphOperation > root, Fn fn ) noexcept\n{\n std::queue< SharedPointer< FrameGraphOperation > > frontier;\n std::unordered_set< FrameGraphOperation * > expanded;\n std::unordered_map< FrameGraphOperation *, size_t > blockCount;\n\n frontier.push( root );\n while ( !frontier.empty() ) {\n auto current = frontier.front();\n frontier.pop();\n if ( expanded.count( get_ptr( current ) ) != 0 ) {\n \/\/ already expanded\n continue;\n }\n expanded.insert( crimild::get_ptr( current ) );\n fn( current );\n current->eachBlockedBy(\n [ & ]( auto passPtr ) {\n auto pass = get_ptr( passPtr );\n if ( blockCount.count( pass ) == 0 ) {\n \/\/ TODO: if passes are discarded because they don't really add up to the final image,\n \/\/ this number will not be correct, since it will show more blocks than actually are.\n blockCount[ pass ] = pass->getBlockCount();\n }\n\n --blockCount[ pass ];\n if ( blockCount[ pass ] == 0 ) {\n frontier.push( passPtr );\n }\n } );\n }\n}\n\nvoid RenderSystem::sort( SharedPointer< FrameGraphOperation > const &root ) noexcept\n{\n m_scenePasses.clear();\n m_renderPasses.clear();\n m_computePasses.clear();\n\n std::list< SharedPointer< FrameGraphOperation > > sorted;\n\n traverse(\n root,\n [ & ]( auto pass ) {\n if ( pass->getType() == FrameGraphOperation::Type::SCENE_PASS ) {\n m_scenePasses.add( cast_ptr< ScenePass >( pass ) );\n } else if ( pass->getType() == FrameGraphOperation::Type::RENDER_PASS ) {\n m_renderPasses.add( cast_ptr< RenderPass >( pass ) );\n } else if ( pass->getType() == FrameGraphOperation::Type::COMPUTE_PASS ) {\n m_computePasses.add( cast_ptr< ComputePass >( pass ) );\n }\n sorted.push_front( pass );\n } );\n\n FrameGraphOperation::Priority p = 0;\n for ( auto pass : sorted ) {\n pass->setPriority( p++ );\n }\n\n m_scenePasses = m_scenePasses.reversed();\n m_renderPasses = m_renderPasses.reversed();\n m_computePasses = m_computePasses.reversed();\n}\n\nvoid RenderSystem::onPreRender( void ) noexcept\n{\n System::onPreRender();\n\n if ( m_frameGraph != nullptr && m_renderPasses.empty() ) {\n sort( m_frameGraph );\n }\n\n m_scenePasses.each(\n []( auto pass ) {\n \/\/ Scene passes are executed every frame with no image index\n pass->apply( 0, true );\n } );\n}\n\nvoid RenderSystem::setFrameGraph( SharedPointer< FrameGraphOperation > const &frameGraph ) noexcept\n{\n m_frameGraph = frameGraph;\n\n m_renderPasses.clear();\n m_scenePasses.clear();\n m_computePasses.clear();\n\n m_sortedOperations.clear();\n\n m_graphicsCommands.clear();\n m_computeCommands.clear();\n\n broadcastMessage( messaging::FrameGraphDidChange {} );\n}\n\nRenderSystem::CommandBufferArray &RenderSystem::getGraphicsCommands( Size imageIndex, Bool forceAll ) noexcept\n{\n m_graphicsCommands.clear();\n m_renderPasses.each(\n [ & ]( auto pass ) {\n if ( pass->apply( imageIndex, forceAll ) ) {\n m_graphicsCommands.add( get_ptr( pass->getCommandBuffers()[ imageIndex ] ) );\n }\n } );\n\n return m_graphicsCommands;\n}\n\nRenderSystem::CommandBufferArray &RenderSystem::getComputeCommands( Size imageIndex, Bool forceAll ) noexcept\n{\n m_computeCommands.clear();\n m_computePasses.each(\n [ & ]( auto pass ) {\n if ( pass->apply( imageIndex, forceAll ) ) {\n m_computeCommands.add( get_ptr( pass->getCommandBuffers()[ imageIndex ] ) );\n }\n } );\n\n return m_computeCommands;\n}\n\nvoid RenderSystem::useDefaultRenderPath( Bool enableDebug ) noexcept\n{\n setFrameGraph(\n [ enableDebug ] {\n using namespace crimild::framegraph;\n\n auto settings = Simulation::getInstance()->getSettings();\n\n auto renderables = fetchRenderables();\n auto litRenderables = renderables->getProduct( 0 );\n auto unlitRenderables = renderables->getProduct( 1 );\n auto envRenderables = renderables->getProduct( 2 );\n\n auto gBuffer = gBufferPass( litRenderables );\n auto albedo = gBuffer->getProduct( 0 );\n auto positions = gBuffer->getProduct( 1 );\n auto normals = gBuffer->getProduct( 2 );\n auto materials = gBuffer->getProduct( 3 );\n auto depth = gBuffer->getProduct( 4 );\n\n if ( settings->get< Bool >( \"debug.show_albedo\" ) ) {\n return present( albedo );\n }\n\n if ( settings->get< Bool >( \"debug.show_metallic\" ) ) {\n return channel( \"metallic\", materials, 0 );\n }\n\n if ( settings->get< Bool >( \"debug.show_roughness\" ) ) {\n return channel( \"roughness\", materials, 1 );\n }\n\n if ( settings->get< Bool >( \"debug.show_ambient_occlusion\" ) ) {\n return channel( \"ambientOcclusion\", materials, 2 );\n }\n\n if ( settings->get< Bool >( \"debug.show_normals\" ) ) {\n return present( normals );\n }\n\n auto reflectionAtlasPass = computeReflectionMap( envRenderables );\n auto irradianceMapPass = computeIrradianceMap( useResource( reflectionAtlasPass ) );\n auto prefilterMapPass = computePrefilterMap( useResource( reflectionAtlasPass ) );\n auto brdfLutPass = computeBRDFLUT( nullptr );\n\n auto shadowAtlasPass = renderShadowAtlas( litRenderables );\n\n auto shadowAtlas = useResource( shadowAtlasPass );\n auto reflectionAtlas = useResource( reflectionAtlasPass );\n auto irradianceAtlas = useResource( irradianceMapPass );\n auto prefilterAtlas = useResource( prefilterMapPass );\n auto brdfLUT = useResource( brdfLutPass );\n\n \/\/ todo: rename to \"localLightingPass\"\n auto lit = lightingPass(\n albedo,\n positions,\n normals,\n materials,\n depth,\n shadowAtlas );\n\n \/\/ TODO: rename to \"globalLightingPass\"\n auto ibl = iblPass(\n albedo,\n positions,\n normals,\n materials,\n depth,\n reflectionAtlas,\n irradianceAtlas,\n prefilterAtlas,\n brdfLUT );\n\n auto unlit = forwardUnlitPass( unlitRenderables, nullptr, depth );\n\n \/\/ Render environment objects in HDR\n auto env = forwardUnlitPass(\n envRenderables,\n useColorAttachment( \"envObjects\/color\", Format::R32G32B32A32_SFLOAT ),\n depth );\n\n auto composed = blend(\n {\n useResource( lit ),\n useResource( ibl ),\n useResource( env ),\n } );\n\n if ( settings->get< Bool >( \"video.ssao.enabled\", false ) ) {\n auto withBlur = [ & ]( auto op ) {\n if ( settings->get< Bool >( \"video.ssao.blur\", true ) ) {\n return blur( useResource( op ) );\n } else {\n return op;\n }\n };\n\n composed = blend(\n {\n useResource( composed ),\n useResource(\n withBlur(\n ssao(\n positions,\n normals ) ) ),\n },\n \"multiply\" );\n }\n\n auto ret = composed;\n auto tonemapped = composed;\n\n if ( settings->get< Bool >( \"video.bloom.enabled\", false ) ) {\n auto bloom = brightPassFilter(\n useResource( composed ),\n Vector3f { 0.2126f, 0.7152f, 0.0722f } );\n\n bloom = gaussianBlur( useResource( bloom ) );\n\n auto tonemapped = tonemapping(\n useResource(\n composed ) );\n\n \/\/ apply bloom after tonemapping\n ret = blend(\n { useResource( tonemapped ), \/\/ forces format to RGB8\n useResource( bloom ) } );\n\n } else {\n tonemapped = tonemapping(\n useResource(\n composed ) );\n ret = tonemapped;\n }\n\n ret = blend(\n {\n useResource( unlit ),\n useResource( ret ),\n } );\n\n if ( enableDebug || settings->get< Bool >( \"debug.show_render_passes\", false ) ) {\n auto lightCascades = debugLightCascades(\n albedo,\n positions,\n normals,\n materials,\n depth,\n shadowAtlas );\n\n auto shadowAtlasDebug = debugShadowAtlas( shadowAtlas );\n\n ret = debug(\n {\n useResource( ret ),\n albedo,\n positions,\n normals,\n materials,\n depth,\n useResource( shadowAtlasDebug ),\n reflectionAtlas,\n irradianceAtlas,\n prefilterAtlas,\n brdfLUT,\n useResource( lightCascades ),\n useResource( lit ),\n useResource( ibl ),\n useResource( tonemapped ),\n useResource( unlit ),\n useResource( env ),\n } );\n }\n\n return ret;\n }() );\n}\n\nvoid RenderSystem::useRTSoftRenderPath( Bool enableDebug ) noexcept\n{\n setFrameGraph(\n [ & ] {\n using namespace crimild::framegraph;\n return present( tonemapping( useResource( softRT() ) ) );\n }() );\n}\n\nvoid RenderSystem::useRTComputeRenderPath( Bool enableDebug ) noexcept\n{\n setFrameGraph(\n [ & ] {\n using namespace crimild::framegraph;\n return present( tonemapping( useResource( computeRT() ) ) );\n }() );\n}\n<|endoftext|>"} {"text":"#include \"Cpu.hpp\"\n#include \"registerAddr.hpp\"\n#include \n\n#define CLOCKSPEED 4194304\n\n\/*\n ** ################################################################\n ** CREATE Singleton\n ** ################################################################\n *\/\n\/\/ See opcode.hpp\nstd::array\t\t_opcodeMap;\nstd::array\t\t_CBopcodeMap;\n\nCpu_z80::Cpu_z80(Memory *memory) :\n\t_memory(memory)\n{\n\t_setOpcodeMap();\n\t_setCbOpcodeMap();\n}\n\nCpu_z80::~Cpu_z80(void)\n{\n}\n\nuint32_t Cpu_z80::getClockSpeed(void)\n{\n\treturn CLOCKSPEED;\n}\n\n\/*\n ** ################################################################\n ** METHOD opcode\n ** ################################################################\n*\/\n\nt_opcode Cpu_z80::_getOpcode(uint8_t opcode)\n{\n\tif (opcode == 0xCB)\n\t{\n\/\/\t\tthis->_cpuRegister.PC += LENGTH_ADDR;\n\t\tuint8_t cbopcode = this->_memory->read_byte(this->_cpuRegister.PC);\n\t\treturn _CBopcodeMap[cbopcode];\n\t}\n\treturn _opcodeMap[opcode];\n}\n\nuint8_t\tCpu_z80::_getCycleOpcode(void)\n{\n\treturn this->_opcodeInProgress.cycleOpcodeNoFlag > this->_opcodeInProgress.cycleOpcodeFlag ?\n\t\tthis->_opcodeInProgress.cycleOpcodeNoFlag : this->_opcodeInProgress.cycleOpcodeFlag;\n}\n\n\nvoid Cpu_z80::_setDataOpcode(void)\n{\n\tif (this->_opcodeInProgress.lengthData > 1 && getStepState())\n\t{\n\t\tif (this->_opcodeInProgress.lengthData > 2)\n\t\t\tthis->_opcodeInProgress.data = this->_memory->read_byte(this->_cpuRegister.PC + LENGTH_ADDR);\n\t\telse\n\t\t\tthis->_opcodeInProgress.data = this->_memory->read_word(this->_cpuRegister.PC + LENGTH_ADDR);\n\t}\n}\n\nvoid Cpu_z80::setStepState(bool state)\n{\n\t_stepState = state;\n}\n\nbool Cpu_z80::getStepState()\n{\n\treturn (this->_stepState);\n}\n\nuint16_t Cpu_z80::_getDataOpcode(void)\n{\n\treturn this->_opcodeInProgress.data;\n}\n\nuint8_t Cpu_z80::_getLengthDataOpcode(void)\n{\n\treturn this->_opcodeInProgress.lengthData;\n}\n\nvoid Cpu_z80::_setHalt(bool state)\n{\n\tthis->_halt = state;\n}\n\nbool Cpu_z80::getHalt(void)\n{\n\treturn this->_halt;\n}\n\nvoid Cpu_z80::_setStop(bool state)\n{\n\tthis->_stop = state;\n}\n\nbool Cpu_z80::getStop(void)\n{\n\treturn this->_stop;\n}\n\nvoid Cpu_z80::_setIME(bool state)\n{\n\tthis->_IME = state;\n}\n\nvoid Cpu_z80::setHoldIME(bool state)\n{\n\tthis->_holdIME = state;\n}\n\nbool Cpu_z80::getHoldIME(void)\n{\n\treturn this->_holdIME;\n}\n\nbool Cpu_z80::getIME(void)\n{\n\treturn this->_IME;\n}\n\n#include \"interrupt.hpp\"\n\nbool Cpu_z80::isInterrupt(void)\n{\n\treturn (this->_memory->read_byte(REGISTER_IF) & INTER_MASK);\n}\n\nbool Cpu_z80::_getInterrupt(uint8_t interrupt)\n{\n\treturn ((this->_memory->read_byte(REGISTER_IF) & interrupt) >= 0x1);\n}\n\n\nvoid Cpu_z80::_loadPtr(uint16_t pc)\n{\n\tthis->_opcodeInProgress = this->_getOpcode(this->_memory->read_byte(pc));\n\tthis->_setDataOpcode();\n}\n\nvoid Cpu_z80::_nextPtr(void) {\n\tif (getStepState())\n\t\tthis->_cpuRegister.PC = this->_cpuRegister.PC + this->_opcodeInProgress.lengthData;\n\tthis->_loadPtr(this->_cpuRegister.PC);\n}\n\nuint8_t Cpu_z80::nbCycleNextOpCode(void)\n{\n\treturn this->_getCycleOpcode();\n}\n\nuint8_t Cpu_z80::executeNextOpcode(void)\n{\n\tif (this->_opcodeInProgress.functionOpcode == NULL)\n\t\tprintf(\"Function not yet implemented: opcode(%.2X), PC = 0x%02x\\n\", this->_opcodeInProgress.opcode, _cpuRegister.PC);\n\telse\n\t\tthis->_opcodeInProgress.functionOpcode();\n\tuint8_t cycle = this->_getCycleOpcode();\n\tthis->_nextPtr();\n\tsetStepState(true);\n\treturn cycle;\n}\n\n#include \"registerAddr.hpp\"\n\nvoid Cpu_z80::init(htype hardware)\n{\n\tsetStepState(true);\n\tthis->_IME = false;\n\tthis->_holdIME = false;\n\n\t\/\/init register cpu\n\tthis->_cpuRegister.A = hardware == GB ? 0x01 : 0x11;\n\tthis->_cpuRegister.F = 0xB0;\n\tthis->_cpuRegister.BC = 0x0013;\n\tthis->_cpuRegister.DE = 0x00D8;\n\tthis->_cpuRegister.HL = 0x014D;\n\n\tthis->_cpuRegister.SP = 0xFFFE;\n\n\t\/\/init register memory\n\tthis->_memory->write_byte(REGISTER_NR10, 0x80);\n\tthis->_memory->write_byte(REGISTER_NR11, 0xBF);\n\tthis->_memory->write_byte(REGISTER_NR12, 0xF3);\n\tthis->_memory->write_byte(REGISTER_NR14, 0xBF);\n\tthis->_memory->write_byte(REGISTER_NR21, 0x3F);\n\tthis->_memory->write_byte(REGISTER_NR22, 0x00);\n\tthis->_memory->write_byte(REGISTER_NR24, 0xBF);\n\tthis->_memory->write_byte(REGISTER_NR30, 0x7F);\n\tthis->_memory->write_byte(REGISTER_NR31, 0xFF);\n\tthis->_memory->write_byte(REGISTER_NR32, 0x9F);\n\tthis->_memory->write_byte(REGISTER_NR33, 0xBF);\n\tthis->_memory->write_byte(REGISTER_NR41, 0xFF);\n\tthis->_memory->write_byte(REGISTER_NR42, 0x00);\n\tthis->_memory->write_byte(REGISTER_NR43, 0x00);\n\tthis->_memory->write_byte(REGISTER_NR30_, 0xBF);\n\tthis->_memory->write_byte(REGISTER_NR50, 0x77);\n\tthis->_memory->write_byte(REGISTER_NR51, 0xF3);\n\tthis->_memory->write_byte(REGISTER_NR52, 0xF1);\n\n\t\/\/ Other register\n\tthis->_memory->write_byte(REGISTER_P1, 0xCF, true);\n\tthis->_memory->write_byte(REGISTER_SB, 0x00);\n\tthis->_memory->write_byte(REGISTER_SC, 0x7E);\n\tthis->_memory->write_byte(REGISTER_DIV, 0xA4); \/\/ bios: 0xD3 start: 0x81\n\tthis->_memory->write_byte(REGISTER_TIMA, 0x00);\n\tthis->_memory->write_byte(REGISTER_TMA, 0x00);\n\tthis->_memory->write_byte(REGISTER_TAC, 0x00);\n\tthis->_memory->write_byte(REGISTER_KEY1, 0xFF);\n\tthis->_memory->write_byte(REGISTER_VBK, 0xFF);\n\tthis->_memory->write_byte(REGISTER_HDMA1, 0xFF);\n\tthis->_memory->write_byte(REGISTER_HDMA2, 0xFF);\n\tthis->_memory->write_byte(REGISTER_HDMA3, 0xFF);\n\tthis->_memory->write_byte(REGISTER_HDMA4, 0xFF);\n\tthis->_memory->write_byte(REGISTER_HDMA5, 0xFF);\n\tthis->_memory->write_byte(REGISTER_SVBK, 0xFF);\n\tthis->_memory->write_byte(REGISTER_IF, 0xE1);\n\tthis->_memory->write_byte(REGISTER_IE, 0x00);\n\t\n\n\tthis->_memory->write_byte(REGISTER_LCDC, 0x91);\n\tthis->_memory->write_byte(REGISTER_STAT, 0x81); \/\/ bios: 0x80 start: 0x81\n\tthis->_memory->write_byte(REGISTER_SCY, 0x00);\n\tthis->_memory->write_byte(REGISTER_SCX, 0x00);\n\tthis->_memory->write_byte(REGISTER_LY, 0x00); \/\/ bios: 0x00 start: 0x81\n\tthis->_memory->write_byte(REGISTER_LYC, 0x00);\n\tthis->_memory->write_byte(REGISTER_DMA, 0xFF);\n\tthis->_memory->write_byte(REGISTER_BGP, 0xFC); \/\/ edelangh: this is bullshit !!\n\tthis->_memory->write_byte(REGISTER_OBP0, 0xFF);\n\tthis->_memory->write_byte(REGISTER_OBP1, 0xFF);\n\tthis->_memory->write_byte(REGISTER_WY, 0x00);\n\tthis->_memory->write_byte(REGISTER_WX, 0x00);\n\t\/* TODO: WTF ? I dont see then in doc *\/\n\tthis->_memory->write_byte(REGISTER_BCPS, 0xFF);\n\tthis->_memory->write_byte(REGISTER_BCPD, 0xFF);\n\tthis->_memory->write_byte(REGISTER_OCPS, 0xFF);\n\tthis->_memory->write_byte(REGISTER_OCPD, 0xFF);\n\n\tthis->_opcodeInProgress = this->_getOpcode(this->_memory->read_byte(this->_cpuRegister.PC));\n\tthis->_setDataOpcode();\n\n\t\/\/TODO: Setup loop, i think this one is up when rom memory is plugged\n\tthis->_setHightBit(REGISTER_TAC, 2);\n}\n\n\/*\n ** ################################################################\n ** METHOD Math\n ** ################################################################\n *\/\n\nvoid Cpu_z80::_setLowBit(uint16_t addr, uint8_t bit)\n{\n\tthis->_memory->write_byte(addr, (uint8_t)((0x01 << bit) ^ this->_memory->read_byte(addr)));\n}\n\nvoid Cpu_z80::_setHightBit(uint16_t addr, uint8_t bit)\n{\n\tthis->_memory->write_byte(addr, (uint8_t)((0x01 << bit) | this->_memory->read_byte(addr)));\n}\n\nvoid Cpu_z80::_resetInterrupt(void)\n{\n\tthis->_memory->write_byte(REGISTER_IF, 0x00);\n}\n\nvoid Cpu_z80::execInterrupt(void)\n{\n\t\/\/ Get interrupt here\n\tif (this->_getInterrupt(INTER_VBLANK))\n\t{\n\t\t\/\/ push PC on stack\n\t\tthis->_cpuRegister.SP -= 2;\n\t\tthis->_memory->write_word(_cpuRegister.SP, _cpuRegister.PC);\n\t\t\/\/ set low INTER_VBLANK\n\t\tthis->_memory->write_byte(REGISTER_IF,\n\t\t\t\t_memory->read_byte(REGISTER_IF) & (INTER_MASK ^ INTER_VBLANK));\n\t\t\/\/ Go to 0x40\n\t\tthis->_cpuRegister.PC = 0x40;\n\t\tthis->_loadPtr(this->_cpuRegister.PC);\n\t}\n\telse if (this->_getInterrupt(INTER_TOVERF))\n\t\tthis->_setStop(false);\n\tthis->_setHalt(false);\n\tthis->_resetInterrupt();\n}\n\nstd::array Cpu_z80::getArrayFrequency()\n{\n\treturn this->_arrayFrequency;\n}\n\nvoid Cpu_z80::_resetPtrAddr(void)\n{\n\tthis->_cpuRegister.PC = 0x100;\n}\nFix non reset PC#include \"Cpu.hpp\"\n#include \"registerAddr.hpp\"\n#include \n\n#define CLOCKSPEED 4194304\n\n\/*\n ** ################################################################\n ** CREATE Singleton\n ** ################################################################\n *\/\n\/\/ See opcode.hpp\nstd::array\t\t_opcodeMap;\nstd::array\t\t_CBopcodeMap;\n\nCpu_z80::Cpu_z80(Memory *memory) :\n\t_memory(memory)\n{\n\t_setOpcodeMap();\n\t_setCbOpcodeMap();\n}\n\nCpu_z80::~Cpu_z80(void)\n{\n}\n\nuint32_t Cpu_z80::getClockSpeed(void)\n{\n\treturn CLOCKSPEED;\n}\n\n\/*\n ** ################################################################\n ** METHOD opcode\n ** ################################################################\n*\/\n\nt_opcode Cpu_z80::_getOpcode(uint8_t opcode)\n{\n\tif (opcode == 0xCB)\n\t{\n\/\/\t\tthis->_cpuRegister.PC += LENGTH_ADDR;\n\t\tuint8_t cbopcode = this->_memory->read_byte(this->_cpuRegister.PC);\n\t\treturn _CBopcodeMap[cbopcode];\n\t}\n\treturn _opcodeMap[opcode];\n}\n\nuint8_t\tCpu_z80::_getCycleOpcode(void)\n{\n\treturn this->_opcodeInProgress.cycleOpcodeNoFlag > this->_opcodeInProgress.cycleOpcodeFlag ?\n\t\tthis->_opcodeInProgress.cycleOpcodeNoFlag : this->_opcodeInProgress.cycleOpcodeFlag;\n}\n\n\nvoid Cpu_z80::_setDataOpcode(void)\n{\n\tif (this->_opcodeInProgress.lengthData > 1 && getStepState())\n\t{\n\t\tif (this->_opcodeInProgress.lengthData > 2)\n\t\t\tthis->_opcodeInProgress.data = this->_memory->read_byte(this->_cpuRegister.PC + LENGTH_ADDR);\n\t\telse\n\t\t\tthis->_opcodeInProgress.data = this->_memory->read_word(this->_cpuRegister.PC + LENGTH_ADDR);\n\t}\n}\n\nvoid Cpu_z80::setStepState(bool state)\n{\n\t_stepState = state;\n}\n\nbool Cpu_z80::getStepState()\n{\n\treturn (this->_stepState);\n}\n\nuint16_t Cpu_z80::_getDataOpcode(void)\n{\n\treturn this->_opcodeInProgress.data;\n}\n\nuint8_t Cpu_z80::_getLengthDataOpcode(void)\n{\n\treturn this->_opcodeInProgress.lengthData;\n}\n\nvoid Cpu_z80::_setHalt(bool state)\n{\n\tthis->_halt = state;\n}\n\nbool Cpu_z80::getHalt(void)\n{\n\treturn this->_halt;\n}\n\nvoid Cpu_z80::_setStop(bool state)\n{\n\tthis->_stop = state;\n}\n\nbool Cpu_z80::getStop(void)\n{\n\treturn this->_stop;\n}\n\nvoid Cpu_z80::_setIME(bool state)\n{\n\tthis->_IME = state;\n}\n\nvoid Cpu_z80::setHoldIME(bool state)\n{\n\tthis->_holdIME = state;\n}\n\nbool Cpu_z80::getHoldIME(void)\n{\n\treturn this->_holdIME;\n}\n\nbool Cpu_z80::getIME(void)\n{\n\treturn this->_IME;\n}\n\n#include \"interrupt.hpp\"\n\nbool Cpu_z80::isInterrupt(void)\n{\n\treturn (this->_memory->read_byte(REGISTER_IF) & INTER_MASK);\n}\n\nbool Cpu_z80::_getInterrupt(uint8_t interrupt)\n{\n\treturn ((this->_memory->read_byte(REGISTER_IF) & interrupt) >= 0x1);\n}\n\n\nvoid Cpu_z80::_loadPtr(uint16_t pc)\n{\n\tthis->_opcodeInProgress = this->_getOpcode(this->_memory->read_byte(pc));\n\tthis->_setDataOpcode();\n}\n\nvoid Cpu_z80::_nextPtr(void) {\n\tif (getStepState())\n\t\tthis->_cpuRegister.PC = this->_cpuRegister.PC + this->_opcodeInProgress.lengthData;\n\tthis->_loadPtr(this->_cpuRegister.PC);\n}\n\nuint8_t Cpu_z80::nbCycleNextOpCode(void)\n{\n\treturn this->_getCycleOpcode();\n}\n\nuint8_t Cpu_z80::executeNextOpcode(void)\n{\n\tif (this->_opcodeInProgress.functionOpcode == NULL)\n\t\tprintf(\"Function not yet implemented: opcode(%.2X), PC = 0x%02x\\n\", this->_opcodeInProgress.opcode, _cpuRegister.PC);\n\telse\n\t\tthis->_opcodeInProgress.functionOpcode();\n\tuint8_t cycle = this->_getCycleOpcode();\n\tthis->_nextPtr();\n\tsetStepState(true);\n\treturn cycle;\n}\n\n#include \"registerAddr.hpp\"\n\nvoid Cpu_z80::init(htype hardware)\n{\n\tsetStepState(true);\n\tthis->_IME = false;\n\tthis->_holdIME = false;\n\n\t\/\/init register cpu\n\tthis->_cpuRegister.A = hardware == GB ? 0x01 : 0x11;\n\tthis->_cpuRegister.F = 0xB0;\n\tthis->_cpuRegister.BC = 0x0013;\n\tthis->_cpuRegister.DE = 0x00D8;\n\tthis->_cpuRegister.HL = 0x014D;\n\n\tthis->_cpuRegister.PC = 0x100;\n\tthis->_cpuRegister.SP = 0xFFFE;\n\n\t\/\/init register memory\n\tthis->_memory->write_byte(REGISTER_NR10, 0x80);\n\tthis->_memory->write_byte(REGISTER_NR11, 0xBF);\n\tthis->_memory->write_byte(REGISTER_NR12, 0xF3);\n\tthis->_memory->write_byte(REGISTER_NR14, 0xBF);\n\tthis->_memory->write_byte(REGISTER_NR21, 0x3F);\n\tthis->_memory->write_byte(REGISTER_NR22, 0x00);\n\tthis->_memory->write_byte(REGISTER_NR24, 0xBF);\n\tthis->_memory->write_byte(REGISTER_NR30, 0x7F);\n\tthis->_memory->write_byte(REGISTER_NR31, 0xFF);\n\tthis->_memory->write_byte(REGISTER_NR32, 0x9F);\n\tthis->_memory->write_byte(REGISTER_NR33, 0xBF);\n\tthis->_memory->write_byte(REGISTER_NR41, 0xFF);\n\tthis->_memory->write_byte(REGISTER_NR42, 0x00);\n\tthis->_memory->write_byte(REGISTER_NR43, 0x00);\n\tthis->_memory->write_byte(REGISTER_NR30_, 0xBF);\n\tthis->_memory->write_byte(REGISTER_NR50, 0x77);\n\tthis->_memory->write_byte(REGISTER_NR51, 0xF3);\n\tthis->_memory->write_byte(REGISTER_NR52, 0xF1);\n\n\t\/\/ Other register\n\tthis->_memory->write_byte(REGISTER_P1, 0xCF, true);\n\tthis->_memory->write_byte(REGISTER_SB, 0x00);\n\tthis->_memory->write_byte(REGISTER_SC, 0x7E);\n\tthis->_memory->write_byte(REGISTER_DIV, 0xA4); \/\/ bios: 0xD3 start: 0x81\n\tthis->_memory->write_byte(REGISTER_TIMA, 0x00);\n\tthis->_memory->write_byte(REGISTER_TMA, 0x00);\n\tthis->_memory->write_byte(REGISTER_TAC, 0x00);\n\tthis->_memory->write_byte(REGISTER_KEY1, 0xFF);\n\tthis->_memory->write_byte(REGISTER_VBK, 0xFF);\n\tthis->_memory->write_byte(REGISTER_HDMA1, 0xFF);\n\tthis->_memory->write_byte(REGISTER_HDMA2, 0xFF);\n\tthis->_memory->write_byte(REGISTER_HDMA3, 0xFF);\n\tthis->_memory->write_byte(REGISTER_HDMA4, 0xFF);\n\tthis->_memory->write_byte(REGISTER_HDMA5, 0xFF);\n\tthis->_memory->write_byte(REGISTER_SVBK, 0xFF);\n\tthis->_memory->write_byte(REGISTER_IF, 0xE1);\n\tthis->_memory->write_byte(REGISTER_IE, 0x00);\n\t\n\n\tthis->_memory->write_byte(REGISTER_LCDC, 0x91);\n\tthis->_memory->write_byte(REGISTER_STAT, 0x81); \/\/ bios: 0x80 start: 0x81\n\tthis->_memory->write_byte(REGISTER_SCY, 0x00);\n\tthis->_memory->write_byte(REGISTER_SCX, 0x00);\n\tthis->_memory->write_byte(REGISTER_LY, 0x00); \/\/ bios: 0x00 start: 0x81\n\tthis->_memory->write_byte(REGISTER_LYC, 0x00);\n\tthis->_memory->write_byte(REGISTER_DMA, 0xFF);\n\tthis->_memory->write_byte(REGISTER_BGP, 0xFC); \/\/ edelangh: this is bullshit !!\n\tthis->_memory->write_byte(REGISTER_OBP0, 0xFF);\n\tthis->_memory->write_byte(REGISTER_OBP1, 0xFF);\n\tthis->_memory->write_byte(REGISTER_WY, 0x00);\n\tthis->_memory->write_byte(REGISTER_WX, 0x00);\n\t\/* TODO: WTF ? I dont see then in doc *\/\n\tthis->_memory->write_byte(REGISTER_BCPS, 0xFF);\n\tthis->_memory->write_byte(REGISTER_BCPD, 0xFF);\n\tthis->_memory->write_byte(REGISTER_OCPS, 0xFF);\n\tthis->_memory->write_byte(REGISTER_OCPD, 0xFF);\n\n\tthis->_opcodeInProgress = this->_getOpcode(this->_memory->read_byte(this->_cpuRegister.PC));\n\tthis->_setDataOpcode();\n\n\t\/\/TODO: Setup loop, i think this one is up when rom memory is plugged\n\tthis->_setHightBit(REGISTER_TAC, 2);\n}\n\n\/*\n ** ################################################################\n ** METHOD Math\n ** ################################################################\n *\/\n\nvoid Cpu_z80::_setLowBit(uint16_t addr, uint8_t bit)\n{\n\tthis->_memory->write_byte(addr, (uint8_t)((0x01 << bit) ^ this->_memory->read_byte(addr)));\n}\n\nvoid Cpu_z80::_setHightBit(uint16_t addr, uint8_t bit)\n{\n\tthis->_memory->write_byte(addr, (uint8_t)((0x01 << bit) | this->_memory->read_byte(addr)));\n}\n\nvoid Cpu_z80::_resetInterrupt(void)\n{\n\tthis->_memory->write_byte(REGISTER_IF, 0x00);\n}\n\nvoid Cpu_z80::execInterrupt(void)\n{\n\t\/\/ Get interrupt here\n\tif (this->_getInterrupt(INTER_VBLANK))\n\t{\n\t\t\/\/ push PC on stack\n\t\tthis->_cpuRegister.SP -= 2;\n\t\tthis->_memory->write_word(_cpuRegister.SP, _cpuRegister.PC);\n\t\t\/\/ set low INTER_VBLANK\n\t\tthis->_memory->write_byte(REGISTER_IF,\n\t\t\t\t_memory->read_byte(REGISTER_IF) & (INTER_MASK ^ INTER_VBLANK));\n\t\t\/\/ Go to 0x40\n\t\tthis->_cpuRegister.PC = 0x40;\n\t\tthis->_loadPtr(this->_cpuRegister.PC);\n\t}\n\telse if (this->_getInterrupt(INTER_TOVERF))\n\t\tthis->_setStop(false);\n\tthis->_setHalt(false);\n\tthis->_resetInterrupt();\n}\n\nstd::array Cpu_z80::getArrayFrequency()\n{\n\treturn this->_arrayFrequency;\n}\n\nvoid Cpu_z80::_resetPtrAddr(void)\n{\n\tthis->_cpuRegister.PC = 0x100;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \"Rom.hpp\"\n\nRom\t\t\tRom::_instance = Rom();\n\nRom::Rom(void)\n{\n\tthis->_eram = NULL;\n\tthis->_rom = NULL;\n\tthis->_mbcPtrRead = {\n\t\tstd::bind(&Rom::_readRom, this, std::placeholders::_1),\n\t\tstd::bind(&Rom::_readMbc1, this, std::placeholders::_1),\n\t\tstd::bind(&Rom::_readMbc2, this, std::placeholders::_1),\n\t\tstd::bind(&Rom::_readMbc3, this, std::placeholders::_1),\n\t\tstd::bind(&Rom::_readMbc5, this, std::placeholders::_1)\n\t\t};\n\tthis->_mbcPtrWrite = {\n\t\tstd::bind(&Rom::_writeRom, this, std::placeholders::_1, std::placeholders::_2),\n\t\tstd::bind(&Rom::_writeMbc1, this, std::placeholders::_1, std::placeholders::_2),\n\t\tstd::bind(&Rom::_writeMbc2, this, std::placeholders::_1, std::placeholders::_2),\n\t\tstd::bind(&Rom::_writeMbc3, this, std::placeholders::_1, std::placeholders::_2),\n\t\tstd::bind(&Rom::_writeMbc5, this, std::placeholders::_1, std::placeholders::_2)\n\t\t};\n}\n\nRom::~Rom(void)\n{\n\tif (this->_rom != NULL)\n\t\tdelete[] this->_rom;\n\tif (this->_eram != NULL)\n\t\tdelete[] this->_eram;\n}\n\nRom\t\t\t&Rom::Instance(void)\n{\n\treturn Rom::_instance;\n}\n\nvoid\t\tRom::init(void)\n{\n\tuint8_t\tflag_cgb;\n\n\tflag_cgb = (this->_rom[CGBFLAG] & 0xFF);\n\tif (flag_cgb == 0x00 || flag_cgb == 0x80)\n\t\tthis->_hardware = GB;\n\telse if (flag_cgb == 0xC0)\n\t\tthis->_hardware = GBC;\n\tif (this->getBankEram(this->_rom[RAMSIZE]) > 0)\n\t\tthis->_eram = new uint8_t [this->getBankEram(this->_rom[RAMSIZE]) * 8192];\n\tthis->_bank = 0;\n\tthis->_rambank = 0;\n\tthis->_write_protect = 0;\n\tthis->_mbc = this->getMbc(this->_rom[CARTRIDGE]);\n}\n\nint\t\t\tRom::load(const char *file)\n{\n\tstd::ifstream\tromFile;\n\tuint32_t\t\trom_size;\n\n\tif (this->_rom != NULL)\n\t\tdelete[] this->_rom;\n\tif (this->_eram != NULL)\n\t\tdelete[] this->_eram;\n\tthis->_rom = NULL;\n\tthis->_eram = NULL;\n\tromFile.open(file, std::ios::in | std::ios::ate | std::ios::binary);\n\tif (romFile.is_open())\n\t{\n\t\trom_size = romFile.tellg();\n\t\tthis->_rom = new char [rom_size];\n\t\tromFile.seekg(0, std::ios::beg);\n\t\tromFile.read(this->_rom, rom_size);\n\t\tromFile.close();\n\t\tthis->init();\n\t\t\/\/ TODO check if ROM valide (nitendo logo, checksum, ...)\n\t\tif (this->_mbc == 0xFF)\n\t\t\treturn -2;\n\t\treturn 0;\n\t}\n\treturn -1;\n}\n\nhtype\t\tRom::getHardware(void)\n{\n\treturn this->_hardware;\n}\n\nuint8_t\t\tRom::read(uint16_t addr)\n{\n\tif (this->_rom == NULL || this->_mbc == 0xFF)\n\t\treturn -1;\n\treturn this->_mbcPtrRead[this->_mbc](addr);\n}\n\nvoid\t\tRom::write(uint16_t addr, uint8_t val)\n{\n\tif (this->_rom == NULL || this->_mbc == 0xFF)\n\t\treturn ;\n\tthis->_mbcPtrWrite[this->_mbc](addr, val);\n}\n\nvoid\t\tRom::reset(void)\n{\n}\n\nuint8_t\t\tRom::getBankEram(uint8_t octet)\n{\n\tif (octet == 1 || octet == 2)\n\t\treturn 1;\n\telse if (octet == 3)\n\t\treturn 4;\n\telse if (octet == 4)\n\t\treturn 16;\n\treturn 0;\n}\n\nbool\t\tRom::isLoaded(void)\n{\n\tif (this->_rom == NULL)\n\t\treturn false;\n\treturn true;\n}\n\nuint8_t\t\tRom::getMbc(uint8_t octet)\n{\n\tswitch (octet)\n\t{\n\t\tcase 0x00:\n\t\tcase 0x08:\n\t\tcase 0x09:\n\t\t\treturn ROM;\n\t\t\tbreak;\n\t\tcase 0x01:\n\t\tcase 0x02:\n\t\tcase 0x03:\n\t\t\treturn MBC1;\n\t\t\tbreak;\n\t\tcase 0x05:\n\t\tcase 0x06:\n\t\t\treturn MBC2;\n\t\t\tbreak ;\n\t\tcase 0x0F:\n\t\tcase 0x10:\n\t\tcase 0x11:\n\t\tcase 0x12:\n\t\tcase 0x13:\n\t\t\treturn MBC3;\n\t\t\tbreak ;\n\t\tcase 0x19:\n\t\tcase 0x1A:\n\t\tcase 0x1B:\n\t\tcase 0x1C:\n\t\tcase 0x1D:\n\t\tcase 0x1E:\n\t\t\treturn MBC5;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -1;\n\t\t\tbreak;\n\t}\n\treturn -1;\n}\n\nuint8_t\t\tRom::_readRom(uint16_t addr)\n{\n\tif (addr < 0x8000)\n\t\treturn this->_rom[addr];\n\treturn 0;\n}\n\nuint8_t\t\tRom::_readMbc1(uint16_t addr)\n{\n\tif (addr < 0x4000)\n\t\treturn this->_rom[addr];\n\telse if (addr < 0x8000)\n\t\treturn this->_rom[(addr - 0x4000) + (this->_bank * 0x4000)];\n\telse if (addr >= 0xA000 && addr < 0xC000)\n\t\treturn this->_eram[addr + (this->_rambank * 0x2000)];\n\treturn 0;\n}\n\nuint8_t\t\tRom::_readMbc2(uint16_t addr)\n{\n\treturn 0;\n}\n\nuint8_t\t\tRom::_readMbc3(uint16_t addr)\n{\n\treturn 0;\n}\n\nuint8_t\t\tRom::_readMbc5(uint16_t addr)\n{\n\treturn 0;\n}\n\nvoid\t\tRom::_writeRom(uint16_t addr, uint8_t val)\n{\n\treturn ;\n}\n\nvoid\t\tRom::_writeMbc1(uint16_t addr, uint8_t val)\n{\n\tswitch (addr & 0xF000){\n\t\tcase 0x0000:\n\t\tcase 0x1000:\n\t\t\t\/\/ RAMCS\n\t\t\tif (val == 0x00 || val == 0x0A)\n\t\t\t\tthis->_write_protect = val;\n\t\t\tbreak;\n\t\tcase 0x2000:\n\t\tcase 0x3000:\n\t\t\t\/\/ Rom bank code\n\t\t\tif (val >= 0x01 && val <= 0x1F)\n\t\t\t{\n\t\t\t\tval &= 0x1F;\n\t\t\t\tthis->_bank &= 0xE0;\n\t\t\t\tthis->_bank |= val;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0x4000:\n\t\tcase 0x5000:\n\t\t\t\/\/ Upper Rom bank code\n\t\t\tif (val <= 0x03)\n\t\t\t{\n\t\t\t\tif (this->_tbank == 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/ ROM\n\t\t\t\t\tval <<= 5;\n\t\t\t\t\tthis->_bank &= 0x1F;\n\t\t\t\t\tval &= 0xE0;\n\t\t\t\t\tthis->_bank |= val;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ ERAM\n\t\t\t\t\tthis->_rambank = val;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0x6000:\n\t\tcase 0x7000:\n\t\t\t\/\/ Rom\/Ram change\n\t\t\tif (val == 0x00 || val == 0x01)\n\t\t\t\tthis->_tbank = val;\n\t\t\tbreak;\n\t\tcase 0xA000:\n\t\tcase 0xB000:\n\t\t\t\/\/ ERAM\n\t\t\tif (this->_write_protect == 0x0A)\n\t\t\t\tthis->_eram[addr + (this->_rambank * 0x2000)] = val;\n\t\t\tbreak;\n\t}\n}\n\nvoid\t\tRom::_writeMbc2(uint16_t addr, uint8_t val) {}\nvoid\t\tRom::_writeMbc3(uint16_t addr, uint8_t val) {}\nvoid\t\tRom::_writeMbc5(uint16_t addr, uint8_t val) {}\nAjout gestion MBC2#include \n#include \n#include \"Rom.hpp\"\n\nRom\t\t\tRom::_instance = Rom();\n\nRom::Rom(void)\n{\n\tthis->_eram = NULL;\n\tthis->_rom = NULL;\n\tthis->_mbcPtrRead = {\n\t\tstd::bind(&Rom::_readRom, this, std::placeholders::_1),\n\t\tstd::bind(&Rom::_readMbc1, this, std::placeholders::_1),\n\t\tstd::bind(&Rom::_readMbc2, this, std::placeholders::_1),\n\t\tstd::bind(&Rom::_readMbc3, this, std::placeholders::_1),\n\t\tstd::bind(&Rom::_readMbc5, this, std::placeholders::_1)\n\t\t};\n\tthis->_mbcPtrWrite = {\n\t\tstd::bind(&Rom::_writeRom, this, std::placeholders::_1, std::placeholders::_2),\n\t\tstd::bind(&Rom::_writeMbc1, this, std::placeholders::_1, std::placeholders::_2),\n\t\tstd::bind(&Rom::_writeMbc2, this, std::placeholders::_1, std::placeholders::_2),\n\t\tstd::bind(&Rom::_writeMbc3, this, std::placeholders::_1, std::placeholders::_2),\n\t\tstd::bind(&Rom::_writeMbc5, this, std::placeholders::_1, std::placeholders::_2)\n\t\t};\n}\n\nRom::~Rom(void)\n{\n\tif (this->_rom != NULL)\n\t\tdelete[] this->_rom;\n\tif (this->_eram != NULL)\n\t\tdelete[] this->_eram;\n}\n\nRom\t\t\t&Rom::Instance(void)\n{\n\treturn Rom::_instance;\n}\n\nvoid\t\tRom::init(void)\n{\n\tuint8_t\tflag_cgb;\n\n\tflag_cgb = (this->_rom[CGBFLAG] & 0xFF);\n\tif (flag_cgb == 0x00 || flag_cgb == 0x80)\n\t\tthis->_hardware = GB;\n\telse if (flag_cgb == 0xC0)\n\t\tthis->_hardware = GBC;\n\tif (this->getBankEram(this->_rom[RAMSIZE]) > 0)\n\t\tthis->_eram = new uint8_t [this->getBankEram(this->_rom[RAMSIZE]) * 8192];\n\tthis->_bank = 0;\n\tthis->_rambank = 0;\n\tthis->_write_protect = 0;\n\tthis->_mbc = this->getMbc(this->_rom[CARTRIDGE]);\n}\n\nint\t\t\tRom::load(const char *file)\n{\n\tstd::ifstream\tromFile;\n\tuint32_t\t\trom_size;\n\n\tif (this->_rom != NULL)\n\t\tdelete[] this->_rom;\n\tif (this->_eram != NULL)\n\t\tdelete[] this->_eram;\n\tthis->_rom = NULL;\n\tthis->_eram = NULL;\n\tromFile.open(file, std::ios::in | std::ios::ate | std::ios::binary);\n\tif (romFile.is_open())\n\t{\n\t\trom_size = romFile.tellg();\n\t\tthis->_rom = new char [rom_size];\n\t\tromFile.seekg(0, std::ios::beg);\n\t\tromFile.read(this->_rom, rom_size);\n\t\tromFile.close();\n\t\tthis->init();\n\t\t\/\/ TODO check if ROM valide (nitendo logo, checksum, ...)\n\t\tif (this->_mbc == 0xFF)\n\t\t\treturn -2;\n\t\treturn 0;\n\t}\n\treturn -1;\n}\n\nhtype\t\tRom::getHardware(void)\n{\n\treturn this->_hardware;\n}\n\nuint8_t\t\tRom::read(uint16_t addr)\n{\n\tif (this->_rom == NULL || this->_mbc == 0xFF)\n\t\treturn -1;\n\treturn this->_mbcPtrRead[this->_mbc](addr);\n}\n\nvoid\t\tRom::write(uint16_t addr, uint8_t val)\n{\n\tif (this->_rom == NULL || this->_mbc == 0xFF)\n\t\treturn ;\n\tthis->_mbcPtrWrite[this->_mbc](addr, val);\n}\n\nvoid\t\tRom::reset(void)\n{\n}\n\nuint8_t\t\tRom::getBankEram(uint8_t octet)\n{\n\tif (octet == 1 || octet == 2)\n\t\treturn 1;\n\telse if (octet == 3)\n\t\treturn 4;\n\telse if (octet == 4)\n\t\treturn 16;\n\treturn 0;\n}\n\nbool\t\tRom::isLoaded(void)\n{\n\tif (this->_rom == NULL)\n\t\treturn false;\n\treturn true;\n}\n\nuint8_t\t\tRom::getMbc(uint8_t octet)\n{\n\tswitch (octet)\n\t{\n\t\tcase 0x00:\n\t\tcase 0x08:\n\t\tcase 0x09:\n\t\t\treturn ROM;\n\t\t\tbreak;\n\t\tcase 0x01:\n\t\tcase 0x02:\n\t\tcase 0x03:\n\t\t\treturn MBC1;\n\t\t\tbreak;\n\t\tcase 0x05:\n\t\tcase 0x06:\n\t\t\treturn MBC2;\n\t\t\tbreak ;\n\t\tcase 0x0F:\n\t\tcase 0x10:\n\t\tcase 0x11:\n\t\tcase 0x12:\n\t\tcase 0x13:\n\t\t\treturn MBC3;\n\t\t\tbreak ;\n\t\tcase 0x19:\n\t\tcase 0x1A:\n\t\tcase 0x1B:\n\t\tcase 0x1C:\n\t\tcase 0x1D:\n\t\tcase 0x1E:\n\t\t\treturn MBC5;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -1;\n\t\t\tbreak;\n\t}\n\treturn -1;\n}\n\nuint8_t\t\tRom::_readRom(uint16_t addr)\n{\n\tif (addr < 0x8000)\n\t\treturn this->_rom[addr];\n\treturn 0;\n}\n\nuint8_t\t\tRom::_readMbc1(uint16_t addr)\n{\n\tif (addr < 0x4000)\n\t\treturn this->_rom[addr];\n\telse if (addr < 0x8000)\n\t\treturn this->_rom[(addr - 0x4000) + (this->_bank * 0x4000)];\n\telse if (addr >= 0xA000 && addr < 0xC000)\n\t\treturn this->_eram[addr + (this->_rambank * 0x2000)];\n\treturn 0;\n}\n\nuint8_t\t\tRom::_readMbc2(uint16_t addr)\n{\n\tif (addr < 0x4000)\n\t\treturn this->_rom[addr];\n\telse if (addr < 0x8000)\n\t\treturn this->_rom[(addr - 0x4000) + (this->_bank * 0x4000)];\n\telse if (addr >= 0xA000 && addr < 0xA200)\n\t\treturn this->_eram[addr];\n\treturn 0;\n}\n\nuint8_t\t\tRom::_readMbc3(uint16_t addr)\n{\n\treturn 0;\n}\n\nuint8_t\t\tRom::_readMbc5(uint16_t addr)\n{\n\treturn 0;\n}\n\nvoid\t\tRom::_writeRom(uint16_t addr, uint8_t val)\n{\n\treturn ;\n}\n\nvoid\t\tRom::_writeMbc1(uint16_t addr, uint8_t val)\n{\n\tswitch (addr & 0xF000){\n\t\tcase 0x0000:\n\t\tcase 0x1000:\n\t\t\t\/\/ RAMCS\n\t\t\tif (val == 0x00 || val == 0x0A)\n\t\t\t\tthis->_write_protect = val;\n\t\t\tbreak;\n\t\tcase 0x2000:\n\t\tcase 0x3000:\n\t\t\t\/\/ Rom bank code\n\t\t\tif (val >= 0x01 && val <= 0x1F)\n\t\t\t{\n\t\t\t\tval &= 0x1F;\n\t\t\t\tthis->_bank &= 0xE0;\n\t\t\t\tthis->_bank |= val;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0x4000:\n\t\tcase 0x5000:\n\t\t\t\/\/ Upper Rom bank code\n\t\t\tif (val <= 0x03)\n\t\t\t{\n\t\t\t\tif (this->_tbank == 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/ ROM\n\t\t\t\t\tval <<= 5;\n\t\t\t\t\tthis->_bank &= 0x1F;\n\t\t\t\t\tval &= 0xE0;\n\t\t\t\t\tthis->_bank |= val;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ ERAM\n\t\t\t\t\tthis->_rambank = val;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0x6000:\n\t\tcase 0x7000:\n\t\t\t\/\/ Rom\/Ram change\n\t\t\tif (val == 0x00 || val == 0x01)\n\t\t\t\tthis->_tbank = val;\n\t\t\tbreak;\n\t\tcase 0xA000:\n\t\tcase 0xB000:\n\t\t\t\/\/ ERAM\n\t\t\tif (this->_write_protect == 0x0A)\n\t\t\t\tthis->_eram[addr + (this->_rambank * 0x2000)] = val;\n\t\t\tbreak;\n\t}\n}\n\nvoid\t\tRom::_writeMbc2(uint16_t addr, uint8_t val)\n{\n\tswitch (addr & 0xF000){\n\t\tcase 0x0000:\n\t\t\t\/\/ RAMCS\n\t\t\tthis->_write_protect = val;\n\t\t\tbreak;\n\t\tcase 0x2000:\n\t\t\t\/\/ Rom bank code\n\t\t\tif ((addr & 0x0F00) == 0x0100)\n\t\t\t{\n\t\t\t\tif (val >= 0x01 && val <= 0x0F)\n\t\t\t\t{\n\t\t\t\t\tval &= 0x0F;\n\t\t\t\t\tthis->_bank &= 0xF0;\n\t\t\t\t\tthis->_bank |= val;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0xA000:\n\t\t\t\/\/ ERAM\n\t\t\tif ((addr & 0x0F00) == 0x00 || (addr & 0x0F00) == 0x01)\n\t\t\t{\n\t\t\t\tif (this->_write_protect == 0x0A)\n\t\t\t\t\tthis->_eram[addr] = val;\n\t\t\t}\n\t\t\tbreak;\n\t}\n}\n\nvoid\t\tRom::_writeMbc3(uint16_t addr, uint8_t val) {}\nvoid\t\tRom::_writeMbc5(uint16_t addr, uint8_t val) {}\n<|endoftext|>"} {"text":"#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\nusing namespace std;\nros::Publisher pub;\n\nstruct Plane {\n\tpcl::PointXYZ min;\n\tpcl::PointXYZ max;\n};\n\nvoid printROSPoint(geometry_msgs::Point *p) {\n\tROS_INFO(\"Point: %f %f %f\", p->x, p->y, p->z);\n}\n\nvoid printPlane(struct Plane *plane) {\n\tROS_INFO(\"AABB: %f %f %f -> %f %f %f\", plane->min.x, plane->min.y, plane->min.z, plane->max.x, plane->max.z,\n\t\tplane->max.z);\n}\n\nvoid printPoint(pcl::PointXYZ *p) {\n\tROS_INFO(\"Point: %f %f %f\", p->x, p->y, p->z);\n}\n\nvoid getAABB(pcl::PointCloud::Ptr cloud, struct Plane *plane) {\n\tpcl::MomentOfInertiaEstimation feature_extractor;\n\tfeature_extractor.setInputCloud(cloud);\n\tfeature_extractor.compute();\n\tfeature_extractor.getAABB(plane->min, plane->max);\n}\n\n\/**\n * Transforms a point from PCL coordinate system to ROS coordinate system\n *\n * Documentation:\n * ROS: http:\/\/wiki.ros.org\/geometry\/CoordinateFrameConventions\n *\/\nvoid transformPCLPointToROSPoint(pcl::PointXYZ *input, geometry_msgs::Point *output) {\n\toutput->x = input->z;\n\toutput->y = input->x * (-1.f);\n\toutput->z = input->y * (-1.f);\n}\n\nvoid buildRosMarker(visualization_msgs::Marker *marker, struct Plane *plane, unsigned int id) {\n\tmarker->header.frame_id = \"camera_link\";\n\tmarker->header.stamp = ros::Time::now();\n\tmarker->ns = \"hmmwv\";\n\tmarker->id = id;\n\tmarker->lifetime = ros::Duration();\n\n\tmarker->type = visualization_msgs::Marker::LINE_STRIP;\n\tmarker->action = visualization_msgs::Marker::ADD;\n\n\tmarker->scale.x = 0.05f;\n\n\tmarker->color.r = static_cast (rand()) \/ static_cast (RAND_MAX);\n\tmarker->color.g = static_cast (rand()) \/ static_cast (RAND_MAX);\n\tmarker->color.b = static_cast (rand()) \/ static_cast (RAND_MAX);\n\tmarker->color.a = 1.0;\n\n\t\/*\n\t * Get vertices of the rectangle and transform them to ROS coordinates\n\t *\n\t * p2-----------------p3\n\t * | |\n\t * | |\n\t * p1-----------------p4\n\t *\n\t *\/\n\n\tgeometry_msgs::Point p1;\n\ttransformPCLPointToROSPoint(&plane->min, &p1);\n\n\tgeometry_msgs::Point p2;\n\tpcl::PointXYZ leftTop(plane->min.x, plane->max.y, plane->min.z);\n\ttransformPCLPointToROSPoint(&leftTop, &p2);\n\n\tgeometry_msgs::Point p3;\n\ttransformPCLPointToROSPoint(&plane->max, &p3);\n\n\tgeometry_msgs::Point p4;\n\tpcl::PointXYZ rightBottom(plane->max.x, plane->min.y, plane->max.z);\n\ttransformPCLPointToROSPoint(&rightBottom, &p4);\n\n\tmarker->points.push_back(p1);\n\tmarker->points.push_back(p2);\n\tmarker->points.push_back(p3);\n\tmarker->points.push_back(p4);\n\tmarker->points.push_back(p1);\n}\n\nvoid callback(const sensor_msgs::PointCloud2ConstPtr& input) {\n\tROS_INFO(\"Callback!\");\n\n\t\/\/ convert from ros::pointcloud2 to pcl::pointcloud2\n\tpcl::PCLPointCloud2* unfilteredCloud = new pcl::PCLPointCloud2;\n\tpcl::PCLPointCloud2ConstPtr unfilteredCloudPtr(unfilteredCloud);\n\tpcl_conversions::toPCL(*input, *unfilteredCloud);\n\n\t\/\/ create a voxelgrid to downsample the input data to speed things up.\n\tpcl::PCLPointCloud2::Ptr filteredCloud (new pcl::PCLPointCloud2);\n\n\tpcl::VoxelGrid sor;\n\tsor.setInputCloud(unfilteredCloudPtr);\n\tsor.setLeafSize(0.01f, 0.01f, 0.01f);\n\tsor.filter(*filteredCloud);\n\n\t\/\/ convert to pointcloud\n\tpcl::PointCloud::Ptr cloud(new pcl::PointCloud);\n\tpcl::fromPCLPointCloud2(*filteredCloud, *cloud);\n\n\t\/\/ Does the parametric segmentation\n\tpcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);\n\tpcl::PointIndices::Ptr inliers(new pcl::PointIndices);\n\n\tpcl::SACSegmentation seg;\n\tseg.setOptimizeCoefficients(true);\n\n\tseg.setModelType(pcl::SACMODEL_PLANE);\n\tseg.setModelType(pcl::SACMODEL_PLANE);\n\tseg.setMaxIterations(1000);\n\tseg.setDistanceThreshold(0.01);\n\n\tpcl::ExtractIndices extract;\n\tpcl::PointCloud::Ptr cloud1(new pcl::PointCloud),\n\t\tcloud2(new pcl::PointCloud);\n\tunsigned int pointsAtStart = cloud->points.size(), id = 0;\n\n\tstd::vector planes;\n\tvisualization_msgs::MarkerArray markerArray;\n\n\t\/\/ while 10% of the original cloud is still present\n\twhile (cloud->points.size() > 0.1 * pointsAtStart) {\n\n\t\tseg.setInputCloud(cloud);\n\t\tseg.segment(*inliers, *coefficients);\n\n\t\tif (inliers->indices.size() == 0) {\n\t\t\tROS_WARN(\"Could not estimate a planar model for the given dataset.\");\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ extract the inliers\n\t\textract.setInputCloud(cloud);\n\t\textract.setIndices(inliers);\n\t\textract.setNegative(false);\n\t\textract.filter(*cloud1);\n\n\t\textract.setNegative(true);\n\t\textract.filter(*cloud2);\n\t\tcloud.swap(cloud2);\n\n\t\t\/\/ calculate AABB and add to planes list\n\t\tstruct Plane plane;\n\t\tgetAABB(cloud1, &plane);\n\n\t\t\/\/ calculate the height of the plane and remove planes with less than 5 cm or more than 40 cm\n\t\tfloat height = plane.max.y - plane.min.y;\n\t\tROS_INFO(\"Height: %f\", height);\n\t\tif (height <= 0.4f && height >= 0.0f) {\n\t\t\tvisualization_msgs::Marker marker;\n\t\t\tbuildRosMarker(&marker, &plane, id);\n\t\t\tmarkerArray.markers.push_back(marker);\n\t\t}\n\n\t\tid++;\n\t}\n\n pub.publish(markerArray);\n}\n\nint main(int argc, char **argv) {\n\n\tros::init(argc, argv, \"stairwaydetector\");\n\tros::NodeHandle nh;\n\tros::Subscriber sub = nh.subscribe(\"\/camera\/depth\/points\", 1, callback);\n\tpub = nh.advertise(\"\/hmmwv\/steps\", 0);\n\n\tros::spin();\n\t\n\treturn 0;\n}\nSome stairsdetection implementation pimps#include \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\nusing namespace std;\nros::Publisher pub;\n\nstruct Plane {\n\tpcl::PointXYZ min;\n\tpcl::PointXYZ max;\n};\n\nvoid printROSPoint(geometry_msgs::Point *p) {\n\tROS_INFO(\"Point: %f %f %f\", p->x, p->y, p->z);\n}\n\nvoid printPlane(struct Plane *plane) {\n\tROS_INFO(\"AABB: %f %f %f -> %f %f %f\", plane->min.x, plane->min.y, plane->min.z, plane->max.x, plane->max.z,\n\t\tplane->max.z);\n}\n\nvoid printPoint(pcl::PointXYZ *p) {\n\tROS_INFO(\"Point: %f %f %f\", p->x, p->y, p->z);\n}\n\nvoid getAABB(pcl::PointCloud::Ptr cloud, struct Plane *plane) {\n\tpcl::MomentOfInertiaEstimation feature_extractor;\n\tfeature_extractor.setInputCloud(cloud);\n\tfeature_extractor.compute();\n\tfeature_extractor.getAABB(plane->min, plane->max);\n}\n\n\/**\n * Transforms a point from PCL coordinate system to ROS coordinate system\n *\n * Documentation:\n * ROS: http:\/\/wiki.ros.org\/geometry\/CoordinateFrameConventions\n *\/\nvoid transformPCLPointToROSPoint(pcl::PointXYZ *input, geometry_msgs::Point *output) {\n\toutput->x = input->z;\n\toutput->y = input->x * (-1.f);\n\toutput->z = input->y * (-1.f);\n}\n\nvoid buildRosMarker(visualization_msgs::Marker *marker, struct Plane *plane, unsigned int id) {\n\tmarker->header.frame_id = \"camera_link\";\n\tmarker->header.stamp = ros::Time::now();\n\tmarker->ns = \"hmmwv\";\n\tmarker->id = id;\n\tmarker->lifetime = ros::Duration();\n\n\tmarker->type = visualization_msgs::Marker::LINE_STRIP;\n\tmarker->action = visualization_msgs::Marker::ADD;\n\n\tmarker->scale.x = 0.05f;\n\n\tmarker->color.r = static_cast (rand()) \/ static_cast (RAND_MAX);\n\tmarker->color.g = static_cast (rand()) \/ static_cast (RAND_MAX);\n\tmarker->color.b = static_cast (rand()) \/ static_cast (RAND_MAX);\n\tmarker->color.a = 1.0;\n\n\t\/*\n\t * Get vertices of the rectangle and transform them to ROS coordinates\n\t *\n\t * p2-----------------p3\n\t * | |\n\t * | |\n\t * p1-----------------p4\n\t *\n\t *\/\n\n\tgeometry_msgs::Point p1;\n\ttransformPCLPointToROSPoint(&plane->min, &p1);\n\n\tgeometry_msgs::Point p2;\n\tpcl::PointXYZ leftTop(plane->min.x, plane->max.y, plane->min.z);\n\ttransformPCLPointToROSPoint(&leftTop, &p2);\n\n\tgeometry_msgs::Point p3;\n\ttransformPCLPointToROSPoint(&plane->max, &p3);\n\n\tgeometry_msgs::Point p4;\n\tpcl::PointXYZ rightBottom(plane->max.x, plane->min.y, plane->max.z);\n\ttransformPCLPointToROSPoint(&rightBottom, &p4);\n\n\tmarker->points.push_back(p1);\n\tmarker->points.push_back(p2);\n\tmarker->points.push_back(p3);\n\tmarker->points.push_back(p4);\n\tmarker->points.push_back(p1);\n}\n\nvoid callback(const sensor_msgs::PointCloud2ConstPtr& input) {\n\tROS_INFO(\"===================================\");\n\n\t\/\/ convert from ros::pointcloud2 to pcl::pointcloud2\n\tpcl::PCLPointCloud2* unfilteredCloud = new pcl::PCLPointCloud2;\n\tpcl::PCLPointCloud2ConstPtr unfilteredCloudPtr(unfilteredCloud);\n\tpcl_conversions::toPCL(*input, *unfilteredCloud);\n\n\t\/\/ downsample the input data to speed things up.\n\tpcl::PCLPointCloud2::Ptr filteredCloud(new pcl::PCLPointCloud2);\n\n\tpcl::VoxelGrid sor;\n\tsor.setInputCloud(unfilteredCloudPtr);\n\tsor.setLeafSize(0.01f, 0.01f, 0.01f);\n\tsor.filter(*filteredCloud);\n\n\t\/\/ convert to pointcloud\n\tpcl::PointCloud::Ptr cloud(new pcl::PointCloud);\n\tpcl::fromPCLPointCloud2(*filteredCloud, *cloud);\n\n\t\/\/ Do the parametric segmentation\n\tpcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);\n\tpcl::PointIndices::Ptr inliers(new pcl::PointIndices);\n\n\tpcl::SACSegmentation seg;\n\tseg.setOptimizeCoefficients(true);\n\n\tseg.setModelType(pcl::SACMODEL_PLANE);\n\tseg.setMethodType(pcl::SAC_RANSAC);\n\tseg.setMaxIterations(1000);\n\tseg.setDistanceThreshold(0.01);\n\n\tpcl::ExtractIndices extract;\n\tpcl::PointCloud::Ptr cloud1(new pcl::PointCloud),\n\t\tcloud2(new pcl::PointCloud);\n\tunsigned int pointsAtStart = cloud->points.size(), id = 0;\n\n\tstd::vector planes;\n\tvisualization_msgs::MarkerArray markerArray;\n\n\t\/\/ while 5% of the original cloud is still present\n\twhile (cloud->points.size() > 0.05 * pointsAtStart) {\n\n\t\tseg.setInputCloud(cloud);\n\t\tseg.segment(*inliers, *coefficients);\n\n\t\tif (inliers->indices.size() == 0) {\n\t\t\tROS_WARN(\"Could not estimate a planar model for the given dataset.\");\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ extract the inliers\n\t\textract.setInputCloud(cloud);\n\t\textract.setIndices(inliers);\n\t\textract.setNegative(false);\n\t\textract.filter(*cloud1);\n\n\t\textract.setNegative(true);\n\t\textract.filter(*cloud2);\n\t\tcloud.swap(cloud2);\n\n\t\t\/\/ calculate AABB and add to planes list\n\t\tstruct Plane plane;\n\t\tgetAABB(cloud1, &plane);\n\n\t\t\/\/ calculate the width of the plane and remove planes with less than 30cm\n\t\t\/\/ calculate the height of the plane and remove planes with less than 5cm or more than 40cm\n\t\tfloat width = fabs(plane.max.x - plane.min.x);\n\t\tfloat height = plane.max.y - plane.min.y;\n\t\tROS_INFO(\"Width: %f | Height: %f\", width, height);\n\t\tif (width >= 0.3f && height <= 0.4f && height >= 0.15f) {\n\t\t\tvisualization_msgs::Marker marker;\n\t\t\tbuildRosMarker(&marker, &plane, id);\n\t\t\tmarkerArray.markers.push_back(marker);\n\t\t}\n\n\t\tid++;\n\t}\n\n pub.publish(markerArray);\n}\n\nint main(int argc, char **argv) {\n\n\tros::init(argc, argv, \"stairwaydetector\");\n\tros::NodeHandle nh;\n\tros::Subscriber sub = nh.subscribe(\"\/camera\/depth\/points\", 1, callback);\n\tpub = nh.advertise(\"\/hmmwv\/steps\", 0);\n\n\tros::spin();\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\n\n\n#include \n#include \n#include \/\/ SIGKILL\n\n#include \"logMsg\/logMsg.h\" \/\/ LM_X\n\n#include \"au\/string.h\" \/\/ au::xml_...\n#include \"au\/TokenTaker.h\" \/\/ au::TokenTake\n#include \"au\/ErrorManager.h\" \/\/ au::ErrorManager\n#include \"au\/Token.h\" \/\/ au::Token\n#include \"au\/xml.h\" \/\/ au::xml...\n\n\n#include \"Notification.h\" \/\/ engine::Notification\n\n#include \"engine\/EngineElement.h\"\t\t\t\t\t\/\/ engine::EngineElement\n#include \"engine\/ProcessItem.h\" \/\/ engine::ProcessItem\n#include \"engine\/DiskOperation.h\"\t\t\t\t\t\/\/ engine::DiskOperation\n#include \"engine\/NotificationElement.h\" \/\/ engine::EngineNotificationElement\n\n#include \"engine\/MemoryManager.h\"\n#include \"engine\/DiskManager.h\"\n#include \"engine\/ProcessManager.h\"\n\n#include \"engine\/Engine.h\"\t\t\t\t\t\t\t\/\/ Own interface\n\n\/\/ Goyo. From 60 to 60000\n#define ENGINE_MAX_RUNNING_TIME 60000\n\nNAMESPACE_BEGIN(engine)\n\n\/\/ Common engine\nEngine *engine = NULL;\n\nvoid* runEngineBakground(void* e )\n{\n engine->run();\n return NULL;\n}\n\nEngine::Engine() : EngineService(\"Engine\") , token(\"EngineToken\")\n{\n running_element = NULL; \/\/ Initially, no running element\n flag_finish_threads = false; \/\/ Put this to \"true\" when destroying Engine\n}\n\nEngine::~Engine()\n{\n \/\/ Waiting for all threads to finish\n engine->finish_threads();\n \n \/\/ Remove pending elements in Engine\n elements.clearList();\n}\n\nEngine* Engine::shared()\n{\n if (!engine )\n LM_X(1,(\"Please init Engine with Engine::init()\"));\n return engine;\n}\n\n\nvoid Engine::init()\n{\n if ( engine )\n {\n LM_W((\"Init engine twice... just ignoring\"));\n return;\n }\n \n \/\/ Create the unique engine entity\n engine = new Engine();\n \n \/\/ Add a simple periodic element to not die inmediatelly\n EngineElement *element = new NotificationElement( new Notification(\"alive\") , 10 );\n engine->elements.push_back( element );\n \n LM_T( LmtEngine , (\"Running engine in background...\") );\n pthread_create(&engine->t, 0, runEngineBakground, NULL);\n \n \/\/ Function to remove this engine and all EngineServices like MemoryMamager, DiskManager, ProcessManager etc...\n atexit( destroy_engine_services );\n}\n\nvoid Engine::finish_threads()\n{\n flag_finish_threads = true;\n LM_M((\"Waiting threads of Engine to finish...\"));\n pthread_join(t, NULL);\n LM_M((\"All Engine threads finished\"));\n}\n\n\n\nEngineElement* Engine::intern_getNextElement()\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token , \"Engine::getNextElement\");\n \n \/\/ Compute current time\n time_t now = time(NULL);\n \n if( now >= elements.front()->getThriggerTime() )\n {\n EngineElement* element = elements.front();\n elements.pop_front();\n return element;\n }\n \n return NULL;\n}\n\nbool Engine::isEmpty()\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token , \"Engine::getNextElement\");\n \n return ( elements.size() == 0);\n \n}\n\nvoid Engine::getNextElement( )\n{\n \/\/ Defauly values\n running_element = NULL;\n \n while( true )\n {\n \/\/ Keep a total counter of loops\n counter++; \n \n \/\/ If no more elements, just return\n if( isEmpty() )\n {\n LM_T( LmtEngine, (\"SamsonEngine: No more elements to process in the engine. Quitting ...\"));\n return;\n }\n \n \/\/ Try to get an element\n EngineElement* element = intern_getNextElement();\n \n if( element )\n {\n running_element = element;\n return;\n }\n else\n sleep(1); \/\/ Sleep until the next element\n \n }\n}\n\nvoid Engine::run()\n{\n \n LM_T( LmtEngine , (\"Engine run\"));\n \n counter = 0; \/\/ Init the counter to elements managed by this run-time\n \n while( true )\n {\n \n \/\/ Finish this thread if necessary\n if( flag_finish_threads )\n return; \n \n \/\/ Get next element or sleep time\n getNextElement( );\n \n \/\/ Run or sleep\n if ( !running_element )\n LM_X(1,(\"Internal error at Engine\"));\n \n {\n \/\/ Execute the item selected as running_element\n \n time_t now = time(NULL);\n LM_T( LmtEngine, (\"[START] Engine executing %s at time:%lu, wanted:%lu\" , running_element->getDescription().c_str(), now, running_element->thiggerTime));\n \n if ((now - running_element->thiggerTime) > 30)\n {\n LM_W((\"[WARNING] Task %s delayed %d seconds in starting. This should not be more than 30\", running_element->getDescription().c_str() , (int)(now - running_element->thiggerTime )));\n }\n \n \/\/ Reset cronometer for this particular task\n cronometer.reset();\n \n running_element->run();\n \n \/\/ Compute the time spent in this element\n time_t t = cronometer.diffTimeInSeconds();\n \/\/ Goyo\n if( t > 1 )\n LM_W((\"[WARNING2] Task %s spent %s seconds.\", running_element->getDescription().c_str() , au::time_string( t ).c_str() ));\n \n LM_T( LmtEngine, (\"[DONE] Engine executing %s\" , running_element->getDescription().c_str()));\n \n EngineElement * _running_element = running_element;\n \n running_element = NULL; \/\/ Put running element to NULL\n \n if( _running_element->isRepeated() )\n {\n \/\/ Insert again\n _running_element->Reschedule(now);\n add( _running_element );\n }\n else\n delete _running_element;\n \n }\n }\n}\n\n\nstd::list::iterator Engine::_find_pos( EngineElement *e)\n{\n for (std::list::iterator i = elements.begin() ; i != elements.end() ; i++)\n {\n if( (*i)->getThriggerTime() > e->getThriggerTime() )\n return i;\n }\n \n return elements.end();\n}\n\n#pragma mark ----\n\n\/\/ get xml information\nvoid Engine::getInfo( std::ostringstream& output)\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token , \"Engine::str\");\n \n au::xml_open(output, \"engine\");\n \n au::xml_simple(output , \"loops\" , counter );\n \n if( running_element )\n au::xml_simple( output , \"running_element\" , running_element->getDescription() );\n else\n au::xml_simple( output , \"running_element\" , \"No running element\" );\n \n au::xml_iterate_list( output , \"elements\" , elements );\n \n au::xml_simple( output , \"uptime\" , uptime.diffTimeInSeconds() );\n \n au::xml_close(output , \"engine\");\n \n}\n\n\n\/\/ Functions to register objects ( general and for a particular notification )\nvoid Engine::register_object( Object* object )\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token , \"Engine::register_object\" );\n \n objectsManager.add( object );\n}\n\nvoid Engine::register_object_for_channel( Object* object, const char* channel )\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token,\"Engine::register_object_for_channel\");\n \n objectsManager.add( object , channel );\n}\n\n\/\/ Generic method to unregister an object\nvoid Engine::unregister_object( Object* object )\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token , \"Engine::unregister_object\");\n \n objectsManager.remove( object );\n}\n\n\n\/\/ Run a particular notification\n\/\/ Only executed from friend class \"NotificationElement\"\nvoid Engine::send( Notification * notification )\n{\n objectsManager.send( notification );\n}\n\n\/\/ Add a notification\nvoid Engine::notify( Notification* notification )\n{\n \/\/ Push a notification element with the notification\n add( new NotificationElement( notification ) );\n}\n\nvoid Engine::notify( Notification* notification , int seconds )\n{\n \/\/ Push a notification element with the notification ( in this case with periodic time )\n add( new NotificationElement( notification , seconds ) );\n}\n\n\/\/ Function to add a simple foreground tasks \nvoid Engine::add( EngineElement *element )\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token);\n \n \/\/ Insert an element in the engine\n elements.insert( engine->_find_pos( element ) , element );\n \n \/\/ Wake up main thread if sleeping\n tt.wakeUp();\n}\n\n\/\/ Get an object by its registry names\nObject* Engine::getObjectByName( const char *name )\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token);\n \n return objectsManager.getObjectByName(name);\n \n}\n\nNAMESPACE_ENDBetter check of excesive time for engine operations\n\n\n#include \n#include \n#include \/\/ SIGKILL\n\n#include \"logMsg\/logMsg.h\" \/\/ LM_X\n\n#include \"au\/string.h\" \/\/ au::xml_...\n#include \"au\/TokenTaker.h\" \/\/ au::TokenTake\n#include \"au\/ErrorManager.h\" \/\/ au::ErrorManager\n#include \"au\/Token.h\" \/\/ au::Token\n#include \"au\/xml.h\" \/\/ au::xml...\n\n\n#include \"Notification.h\" \/\/ engine::Notification\n\n#include \"engine\/EngineElement.h\"\t\t\t\t\t\/\/ engine::EngineElement\n#include \"engine\/ProcessItem.h\" \/\/ engine::ProcessItem\n#include \"engine\/DiskOperation.h\"\t\t\t\t\t\/\/ engine::DiskOperation\n#include \"engine\/NotificationElement.h\" \/\/ engine::EngineNotificationElement\n\n#include \"engine\/MemoryManager.h\"\n#include \"engine\/DiskManager.h\"\n#include \"engine\/ProcessManager.h\"\n\n#include \"engine\/Engine.h\"\t\t\t\t\t\t\t\/\/ Own interface\n\n\/\/ Goyo. From 60 to 60000\n#define ENGINE_MAX_RUNNING_TIME 60000\n\nNAMESPACE_BEGIN(engine)\n\n\/\/ Common engine\nEngine *engine = NULL;\n\nvoid* runEngineBakground(void* e )\n{\n engine->run();\n return NULL;\n}\n\nEngine::Engine() : EngineService(\"Engine\") , token(\"EngineToken\")\n{\n running_element = NULL; \/\/ Initially, no running element\n flag_finish_threads = false; \/\/ Put this to \"true\" when destroying Engine\n}\n\nEngine::~Engine()\n{\n \/\/ Waiting for all threads to finish\n engine->finish_threads();\n \n \/\/ Remove pending elements in Engine\n elements.clearList();\n}\n\nEngine* Engine::shared()\n{\n if (!engine )\n LM_X(1,(\"Please init Engine with Engine::init()\"));\n return engine;\n}\n\n\nvoid Engine::init()\n{\n if ( engine )\n {\n LM_W((\"Init engine twice... just ignoring\"));\n return;\n }\n \n \/\/ Create the unique engine entity\n engine = new Engine();\n \n \/\/ Add a simple periodic element to not die inmediatelly\n EngineElement *element = new NotificationElement( new Notification(\"alive\") , 10 );\n engine->elements.push_back( element );\n \n LM_T( LmtEngine , (\"Running engine in background...\") );\n pthread_create(&engine->t, 0, runEngineBakground, NULL);\n \n \/\/ Function to remove this engine and all EngineServices like MemoryMamager, DiskManager, ProcessManager etc...\n atexit( destroy_engine_services );\n}\n\nvoid Engine::finish_threads()\n{\n flag_finish_threads = true;\n LM_M((\"Waiting threads of Engine to finish...\"));\n pthread_join(t, NULL);\n LM_M((\"All Engine threads finished\"));\n}\n\n\n\nEngineElement* Engine::intern_getNextElement()\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token , \"Engine::getNextElement\");\n \n \/\/ Compute current time\n time_t now = time(NULL);\n \n if( now >= elements.front()->getThriggerTime() )\n {\n EngineElement* element = elements.front();\n elements.pop_front();\n return element;\n }\n \n return NULL;\n}\n\nbool Engine::isEmpty()\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token , \"Engine::getNextElement\");\n \n return ( elements.size() == 0);\n \n}\n\nvoid Engine::getNextElement( )\n{\n \/\/ Defauly values\n running_element = NULL;\n \n while( true )\n {\n \/\/ Keep a total counter of loops\n counter++; \n \n \/\/ If no more elements, just return\n if( isEmpty() )\n {\n LM_T( LmtEngine, (\"SamsonEngine: No more elements to process in the engine. Quitting ...\"));\n return;\n }\n \n \/\/ Try to get an element\n EngineElement* element = intern_getNextElement();\n \n if( element )\n {\n running_element = element;\n return;\n }\n else\n sleep(1); \/\/ Sleep until the next element\n \n }\n}\n\nvoid Engine::run()\n{\n \n LM_T( LmtEngine , (\"Engine run\"));\n \n counter = 0; \/\/ Init the counter to elements managed by this run-time\n \n while( true )\n {\n \n \/\/ Finish this thread if necessary\n if( flag_finish_threads )\n return; \n \n \/\/ Get next element or sleep time\n getNextElement( );\n \n \/\/ Run or sleep\n if ( !running_element )\n LM_X(1,(\"Internal error at Engine\"));\n \n {\n \/\/ Execute the item selected as running_element\n \n time_t now = time(NULL);\n LM_T( LmtEngine, (\"[START] Engine executing %s at time:%lu, wanted:%lu\" , running_element->getDescription().c_str(), now, running_element->thiggerTime));\n \n if ((now - running_element->thiggerTime) > 30)\n {\n LM_W((\"[WARNING] Task %s delayed %d seconds in starting. This should not be more than 30\", running_element->getDescription().c_str() , (int)(now - running_element->thiggerTime )));\n }\n \n \/\/ Reset cronometer for this particular task\n cronometer.reset();\n \n running_element->run();\n \n \/\/ Compute the time spent in this element\n double t = cronometer.diffTime();\n \/\/ Goyo\n if( t > 1.0 )\n LM_W((\"[WARNING2] Task %s spent %s seconds.\", running_element->getDescription().c_str() , au::time_string( t ).c_str() ));\n \n LM_T( LmtEngine, (\"[DONE] Engine executing %s\" , running_element->getDescription().c_str()));\n \n EngineElement * _running_element = running_element;\n \n running_element = NULL; \/\/ Put running element to NULL\n \n if( _running_element->isRepeated() )\n {\n \/\/ Insert again\n _running_element->Reschedule(now);\n add( _running_element );\n }\n else\n delete _running_element;\n \n }\n }\n}\n\n\nstd::list::iterator Engine::_find_pos( EngineElement *e)\n{\n for (std::list::iterator i = elements.begin() ; i != elements.end() ; i++)\n {\n if( (*i)->getThriggerTime() > e->getThriggerTime() )\n return i;\n }\n \n return elements.end();\n}\n\n#pragma mark ----\n\n\/\/ get xml information\nvoid Engine::getInfo( std::ostringstream& output)\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token , \"Engine::str\");\n \n au::xml_open(output, \"engine\");\n \n au::xml_simple(output , \"loops\" , counter );\n \n if( running_element )\n au::xml_simple( output , \"running_element\" , running_element->getDescription() );\n else\n au::xml_simple( output , \"running_element\" , \"No running element\" );\n \n au::xml_iterate_list( output , \"elements\" , elements );\n \n au::xml_simple( output , \"uptime\" , uptime.diffTimeInSeconds() );\n \n au::xml_close(output , \"engine\");\n \n}\n\n\n\/\/ Functions to register objects ( general and for a particular notification )\nvoid Engine::register_object( Object* object )\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token , \"Engine::register_object\" );\n \n objectsManager.add( object );\n}\n\nvoid Engine::register_object_for_channel( Object* object, const char* channel )\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token,\"Engine::register_object_for_channel\");\n \n objectsManager.add( object , channel );\n}\n\n\/\/ Generic method to unregister an object\nvoid Engine::unregister_object( Object* object )\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token , \"Engine::unregister_object\");\n \n objectsManager.remove( object );\n}\n\n\n\/\/ Run a particular notification\n\/\/ Only executed from friend class \"NotificationElement\"\nvoid Engine::send( Notification * notification )\n{\n objectsManager.send( notification );\n}\n\n\/\/ Add a notification\nvoid Engine::notify( Notification* notification )\n{\n \/\/ Push a notification element with the notification\n add( new NotificationElement( notification ) );\n}\n\nvoid Engine::notify( Notification* notification , int seconds )\n{\n \/\/ Push a notification element with the notification ( in this case with periodic time )\n add( new NotificationElement( notification , seconds ) );\n}\n\n\/\/ Function to add a simple foreground tasks \nvoid Engine::add( EngineElement *element )\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token);\n \n \/\/ Insert an element in the engine\n elements.insert( engine->_find_pos( element ) , element );\n \n \/\/ Wake up main thread if sleeping\n tt.wakeUp();\n}\n\n\/\/ Get an object by its registry names\nObject* Engine::getObjectByName( const char *name )\n{\n \/\/ Mutex protection\n au::TokenTaker tt(&token);\n \n return objectsManager.getObjectByName(name);\n \n}\n\nNAMESPACE_END<|endoftext|>"} {"text":"#include \"Variant.h\"\n#include \"convert.h\"\n#include \n\nusing namespace std;\nusing namespace vcf;\n\nint main(int argc, char** argv) {\n\n VariantCallFile variantFile;\n\n if (argc > 1) {\n string filename = argv[1];\n variantFile.open(filename);\n } else {\n variantFile.open(std::cin);\n }\n\n if (!variantFile.is_open()) {\n return 1;\n }\n\n variantFile.addHeaderLine(\"##INFO=\");\n cout << variantFile.header << endl;\n\n Variant var(variantFile);\n while (variantFile.getNextVariant(var)) {\n\tvector& lengths = var.info[\"length\"];\n\tlengths.clear();\n\tfor (vector::iterator a = var.alt.begin(); a != var.alt.end(); ++a) {\n\t lengths.push_back(convert(abs((int) a->size() - (int) var.ref.size())));\n\t}\n cout << var << endl;\n }\n\n return 0;\n\n}\n\nupdate to vcflength, use +\/- instead of abs(...)#include \"Variant.h\"\n#include \"convert.h\"\n#include \n\nusing namespace std;\nusing namespace vcf;\n\nint main(int argc, char** argv) {\n\n VariantCallFile variantFile;\n\n if (argc > 1) {\n string filename = argv[1];\n variantFile.open(filename);\n } else {\n variantFile.open(std::cin);\n }\n\n if (!variantFile.is_open()) {\n return 1;\n }\n\n variantFile.addHeaderLine(\"##INFO=\");\n cout << variantFile.header << endl;\n\n Variant var(variantFile);\n while (variantFile.getNextVariant(var)) {\n vector& lengths = var.info[\"length\"];\n lengths.clear();\n for (vector::iterator a = var.alt.begin(); a != var.alt.end(); ++a) {\n lengths.push_back(convert((int) a->size() - (int) var.ref.size()));\n }\n cout << var << endl;\n }\n\n return 0;\n\n}\n\n<|endoftext|>"} {"text":"\/\/ illarionserver - server for the game Illarion\n\/\/ Copyright 2011 Illarion e.V.\n\/\/\n\/\/ This file is part of illarionserver.\n\/\/\n\/\/ illarionserver is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ illarionserver is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with illarionserver. If not, see .\n\n\n#include \"db\/ConnectionManager.hpp\"\n#include \"db\/SchemaHelper.hpp\"\n#include \"db\/SelectQuery.hpp\"\n#include \"db\/Result.hpp\"\n\n#include \"ArmorObjectTable.hpp\"\n#include \"types.hpp\"\n\n#include \n#include \n\nArmorObjectTable::ArmorObjectTable() : m_dataOK(false) {\n reload();\n}\n\nvoid ArmorObjectTable::reload() {\n#ifdef DataConnect_DEBUG\n std::cout << \"ArmorObjectTable: reload\" << std::endl;\n#endif\n\n try {\n Database::PConnection connection =\n Database::ConnectionManager::getInstance().getConnection();\n\n Database::SelectQuery query(*connection);\n query.addColumn(\"armor\", \"arm_itemid\");\n query.addColumn(\"armor\", \"arm_bodyparts\");\n query.addColumn(\"armor\", \"arm_puncture\");\n query.addColumn(\"armor\", \"arm_stroke\");\n query.addColumn(\"armor\", \"arm_thrust\");\n query.addColumn(\"armor\", \"arm_magicdisturbance\");\n query.addColumn(\"armor\", \"arm_absorb\");\n query.addColumn(\"armor\", \"arm_stiffness\");\n query.addServerTable(\"armor\");\n\n Database::Result results = query.execute();\n Database::ConnectionManager::getInstance().releaseConnection(connection);\n\n if (!results.empty()) {\n clearOldTable();\n ArmorStruct temprecord;\n\n for (Database::Result::ConstIterator itr = results.begin();\n itr != results.end(); ++itr) {\n\n temprecord.BodyParts = (TYPE_OF_BODYPARTS)((*itr)[\"arm_bodyparts\"].as());\n temprecord.PunctureArmor = (TYPE_OF_PUNCTUREARMOR)((*itr)[\"arm_puncture\"].as());\n temprecord.StrokeArmor = (TYPE_OF_STROKEARMOR)((*itr)[\"arm_stroke\"].as());\n temprecord.ThrustArmor = (TYPE_OF_THRUSTARMOR)((*itr)[\"arm_thrust\"].as());\n temprecord.MagicDisturbance = (TYPE_OF_MAGICDISTURBANCE)(*itr)[\"arm_magicdisturbance\"].as();\n temprecord.Absorb = (*itr)[\"arm_absorb\"].as();\n temprecord.Stiffness = (*itr)[\"arm_stiffness\"].as();\n\n m_table[(TYPE_OF_ITEM_ID)((*itr)[\"arm_itemid\"].as())] = temprecord;\n }\n\n m_dataOK = true;\n } else {\n m_dataOK = false;\n }\n\n#ifdef DataConnect_DEBUG\n std::cout << \"loaded \" << rows;\n std::cout << \" rows into ArmorObjectTable\" << std::endl;\n#endif\n\n } catch (...) {\n m_dataOK = false;\n }\n}\n\nbool ArmorObjectTable::find(TYPE_OF_ITEM_ID Id, ArmorStruct &ret) {\n TABLE::iterator iterator;\n iterator = m_table.find(Id);\n\n if (iterator == m_table.end()) {\n return false;\n } else {\n ret = (*iterator).second;\n return true;\n }\n}\n\n\n\nvoid ArmorObjectTable::clearOldTable() {\n m_table.clear();\n}\n\n\nArmorObjectTable::~ArmorObjectTable() {\n clearOldTable();\n}\nCleaned implementation of the new database interface to the armor object table\/\/ illarionserver - server for the game Illarion\n\/\/ Copyright 2011 Illarion e.V.\n\/\/\n\/\/ This file is part of illarionserver.\n\/\/\n\/\/ illarionserver is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ illarionserver is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with illarionserver. If not, see .\n\n#include \"ArmorObjectTable.hpp\"\n\n#include \"db\/ConnectionManager.hpp\"\n#include \"db\/SchemaHelper.hpp\"\n#include \"db\/SelectQuery.hpp\"\n#include \"db\/Result.hpp\"\n\n#include \"types.hpp\"\n\n#include \n#include \n\nArmorObjectTable::ArmorObjectTable() : m_dataOK(false) {\n reload();\n}\n\nvoid ArmorObjectTable::reload() {\n#ifdef DataConnect_DEBUG\n std::cout << \"ArmorObjectTable: reload\" << std::endl;\n#endif\n\n try {\n Database::PConnection connection =\n Database::ConnectionManager::getInstance().getConnection();\n\n Database::SelectQuery query(*connection);\n query.addColumn(\"armor\", \"arm_itemid\");\n query.addColumn(\"armor\", \"arm_bodyparts\");\n query.addColumn(\"armor\", \"arm_puncture\");\n query.addColumn(\"armor\", \"arm_stroke\");\n query.addColumn(\"armor\", \"arm_thrust\");\n query.addColumn(\"armor\", \"arm_magicdisturbance\");\n query.addColumn(\"armor\", \"arm_absorb\");\n query.addColumn(\"armor\", \"arm_stiffness\");\n query.addServerTable(\"armor\");\n\n Database::Result results = query.execute();\n Database::ConnectionManager::getInstance().releaseConnection(connection);\n\n if (!results.empty()) {\n clearOldTable();\n ArmorStruct temprecord;\n\n for (Database::Result::ConstIterator itr = results.begin();\n itr != results.end(); ++itr) {\n\n temprecord.BodyParts = (TYPE_OF_BODYPARTS)((*itr)[\"arm_bodyparts\"].as());\n temprecord.PunctureArmor = (TYPE_OF_PUNCTUREARMOR)((*itr)[\"arm_puncture\"].as());\n temprecord.StrokeArmor = (TYPE_OF_STROKEARMOR)((*itr)[\"arm_stroke\"].as());\n temprecord.ThrustArmor = (TYPE_OF_THRUSTARMOR)((*itr)[\"arm_thrust\"].as());\n temprecord.MagicDisturbance = (TYPE_OF_MAGICDISTURBANCE)(*itr)[\"arm_magicdisturbance\"].as();\n temprecord.Absorb = (*itr)[\"arm_absorb\"].as();\n temprecord.Stiffness = (*itr)[\"arm_stiffness\"].as();\n\n m_table[(TYPE_OF_ITEM_ID)((*itr)[\"arm_itemid\"].as())] = temprecord;\n }\n\n m_dataOK = true;\n } else {\n m_dataOK = false;\n }\n\n#ifdef DataConnect_DEBUG\n std::cout << \"loaded \" << rows;\n std::cout << \" rows into ArmorObjectTable\" << std::endl;\n#endif\n\n } catch (...) {\n m_dataOK = false;\n }\n}\n\nbool ArmorObjectTable::find(TYPE_OF_ITEM_ID Id, ArmorStruct &ret) {\n TABLE::iterator iterator;\n iterator = m_table.find(Id);\n\n if (iterator == m_table.end()) {\n return false;\n } else {\n ret = (*iterator).second;\n return true;\n }\n}\n\n\n\nvoid ArmorObjectTable::clearOldTable() {\n m_table.clear();\n}\n\n\nArmorObjectTable::~ArmorObjectTable() {\n clearOldTable();\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: hfi_tag.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2004-11-15 13:34:38 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#include \n#include \"hfi_tag.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"hfi_typetext.hxx\"\n#include \"hi_ary.hxx\"\n#include \"hi_env.hxx\"\n#include \"hi_linkhelper.hxx\"\n\n\nusing ary::info::DocuTex2;\n\n\ninline void\nHF_IdlTag::Enter_TextOut( Xml::Element & o_rText ) const\n{\n aTextOut.Out().Enter(o_rText);\n}\n\ninline void\nHF_IdlTag::Leave_TextOut() const\n{\n aTextOut.Out().Leave();\n}\n\ninline void\nHF_IdlTag::PutText_Out( const ary::info::DocuTex2 & i_rText ) const\n{\n i_rText.DisplayAt( const_cast< HF_IdlDocuTextDisplay& >(aTextOut) );\n}\n\n\n\nHF_IdlTag::HF_IdlTag( Environment & io_rEnv,\n const ary::idl::CodeEntity & i_rScopeGivingCe )\n : HtmlFactory_Idl( io_rEnv, 0 ),\n pTitleOut(0),\n aTextOut(io_rEnv, 0, i_rScopeGivingCe)\n{\n}\n\nHF_IdlTag::~HF_IdlTag()\n{\n}\n\nvoid\nHF_IdlTag::Produce_byData( Xml::Element & o_rTitle,\n Xml::Element & o_rText,\n const ary::info::AtTag2 & i_rTag ) const\n{\n pTitleOut = &o_rTitle;\n Enter_TextOut(o_rText);\n i_rTag.DisplayAt( const_cast< HF_IdlTag& >(*this) );\n Leave_TextOut();\n}\n\nvoid\nHF_IdlTag::Display_StdAtTag( const csi::dsapi::DT_StdAtTag & i_rTag )\n{\n if ( i_rTag.Text().IsEmpty() )\n return;\n\n csv_assert( pTitleOut != 0 );\n *pTitleOut << i_rTag.Title();\n PutText_Out( i_rTag.Text() );\n}\n\nvoid\nHF_IdlTag::Display_SeeAlsoAtTag( const csi::dsapi::DT_SeeAlsoAtTag & i_rTag )\n{\n if ( i_rTag.Text().IsEmpty() )\n return;\n\n csv_assert( pTitleOut != 0 );\n *pTitleOut << \"See also\";\n\n HF_IdlTypeText aLinkText(Env(),aTextOut.CurOut(),true, &aTextOut.ScopeGivingCe());\n aLinkText.Produce_byData( i_rTag.LinkText() );\n\n aTextOut.CurOut() << new Html::LineBreak;\n PutText_Out( i_rTag.Text() );\n}\n\nvoid\nHF_IdlTag::Display_ParameterAtTag( const csi::dsapi::DT_ParameterAtTag & i_rTag )\n{\n csv_assert( pTitleOut != 0 );\n *pTitleOut\n << ( StreamLock(100)() << \"Parameter \" << i_rTag.Title() << c_str );\n PutText_Out( i_rTag.Text() );\n}\n\nvoid\nHF_IdlTag::Display_SinceAtTag( const csi::dsapi::DT_SinceAtTag & i_rTag )\n{\n csv_assert(pTitleOut != 0);\n\n if ( i_rTag.Text().IsEmpty() )\n {\n return;\n }\n\n \/\/ Transform the value of the @since tag into the text to be displayed.\n String sDisplay =\n autodoc::CommandLine::Get_().DisplayOf_SinceTagValue(\n i_rTag.Text().TextOfFirstToken() );\n if (sDisplay.empty())\n return;\n\n *pTitleOut << \"Since \";\n DocuTex2 aHelp;\n aHelp.AddToken(* new csi::dsapi::DT_TextToken(sDisplay));\n PutText_Out(aHelp);\n}\n\n\n\/\/******************** HF_IdlShortDocu *********************\/\n\nHF_IdlShortDocu::HF_IdlShortDocu( Environment & io_rEnv,\n Xml::Element & o_rOut )\n : HtmlFactory_Idl( io_rEnv, &o_rOut )\n{\n}\n\nHF_IdlShortDocu::~HF_IdlShortDocu()\n{\n}\n\nvoid\nHF_IdlShortDocu::Produce_byData( const ary::idl::CodeEntity & i_rCe )\n{\n if (i_rCe.Docu() == 0)\n return;\n\n const ce_info &\n rDocu = *i_rCe.Docu();\n if ( rDocu.IsDeprecated() )\n {\n CurOut()\n >> *new Html::Bold\n << \"[ DEPRECATED ]\" << new Html::LineBreak;\n }\n if ( rDocu.IsOptional() )\n {\n CurOut()\n >> *new Html::Bold\n << \"[ OPTIONAL ]\" << new Html::LineBreak;\n }\n\n HF_IdlDocuTextDisplay\n aText( Env(), &CurOut(), i_rCe);\n rDocu.Short().DisplayAt(aText);\n}\n\n\n\/\/******************** HF_IdlDocuTextDisplay *********************\/\n\n\nHF_IdlDocuTextDisplay::HF_IdlDocuTextDisplay( Environment & io_rEnv,\n Xml::Element * o_pOut,\n const ary::idl::CodeEntity & i_rScopeGivingCe )\n : HtmlFactory_Idl(io_rEnv, o_pOut),\n sScope(),\n sLinkToken(),\n bGatherLink(false),\n pScopeGivingCe(&i_rScopeGivingCe)\n{\n}\n\nHF_IdlDocuTextDisplay::~HF_IdlDocuTextDisplay()\n{\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_TextToken( const csi::dsapi::DT_TextToken & i_rToken )\n{\n if (bGatherLink)\n {\n if (sLinkToken.length() == 0)\n {\n sLinkToken = i_rToken.GetText();\n return;\n }\n else\n {\n Cerr() << \"Error in documentation: Too many or too few tokens for a link in or .\" << Endl();\n Cerr() << \" Link won't be created, but all tokens shown plain.\" << Endl();\n Cerr() << \" \\\"\" << sLinkToken << \"\\\"\";\n if ( pScopeGivingCe != 0 )\n Cerr() << \" in \" << pScopeGivingCe->LocalName();\n Cerr() << Endl();\n StopLinkGathering();\n }\n } \/\/ endif (bGatherLink)\n\n CurOut() << new Xml::XmlCode( i_rToken.GetText() ) << \" \";\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_MupType( const csi::dsapi::DT_MupType & i_rToken )\n{\n if (i_rToken.IsBegin())\n {\n StartLinkGathering(i_rToken.Scope());\n }\n else\n {\n if (bGatherLink)\n {\n CreateTypeLink();\n CurOut()\n << \" \";\n StopLinkGathering();\n }\n }\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_MupMember( const csi::dsapi::DT_MupMember & i_rToken )\n{\n if (i_rToken.IsBegin())\n {\n StartLinkGathering(i_rToken.Scope());\n }\n else\n {\n if (bGatherLink)\n {\n CreateMemberLink();\n CurOut()\n << \" \";\n StopLinkGathering();\n }\n }\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_MupConst( const csi::dsapi::DT_MupConst & i_rToken )\n{\n CurOut()\n >> *new Html::Bold\n << i_rToken.GetText();\n CurOut()\n << \" \";\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_Style( const csi::dsapi::DT_Style & i_rToken )\n{\n CurOut() << new Xml::XmlCode( i_rToken.GetText() );\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_EOL()\n{\n CurOut() << \"\\n\";\n}\n\nvoid\nHF_IdlDocuTextDisplay::CreateTypeLink()\n{\n if (strchr(sLinkToken,':') != 0)\n {\n Cerr() << \"Warning: Qualified name (probably member) \\\"\"\n << sLinkToken\n << \"\\\" found in tag in \"\n << Env().CurPageCe_AsText()\n << Endl();\n CurOut() << sLinkToken;\n return;\n }\n HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());\n aLink.Produce_LinkInDocu(sScope, sLinkToken, String::Null_());\n}\n\nvoid\nHF_IdlDocuTextDisplay::CreateMemberLink()\n{\n\n HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());\n\n const char *\n sSplit = strchr(sLinkToken,':');\n\n if (sSplit != 0)\n {\n String sCe(sLinkToken.c_str(), sSplit - sLinkToken.c_str());\n String sMember(sSplit+2);\n\n if (NOT sScope.empty() OR ScopeGivingCe().LocalName() != sCe )\n aLink.Produce_LinkInDocu(sScope, sCe, sMember);\n else\n aLink.Produce_LocalLinkInDocu(sMember);\n }\n else\n {\n aLink.Produce_LocalLinkInDocu(sLinkToken);\n }\n}\nINTEGRATION: CWS adc10 (1.5.2); FILE MERGED 2005\/01\/12 13:14:25 np 1.5.2.1: #i31025# Convenient error log file.\/*************************************************************************\n *\n * $RCSfile: hfi_tag.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2005-01-27 11:18:53 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#include \n#include \"hfi_tag.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"hfi_typetext.hxx\"\n#include \"hi_ary.hxx\"\n#include \"hi_env.hxx\"\n#include \"hi_linkhelper.hxx\"\n\n\nusing ary::info::DocuTex2;\n\n\ninline void\nHF_IdlTag::Enter_TextOut( Xml::Element & o_rText ) const\n{\n aTextOut.Out().Enter(o_rText);\n}\n\ninline void\nHF_IdlTag::Leave_TextOut() const\n{\n aTextOut.Out().Leave();\n}\n\ninline void\nHF_IdlTag::PutText_Out( const ary::info::DocuTex2 & i_rText ) const\n{\n i_rText.DisplayAt( const_cast< HF_IdlDocuTextDisplay& >(aTextOut) );\n}\n\n\n\nHF_IdlTag::HF_IdlTag( Environment & io_rEnv,\n const ary::idl::CodeEntity & i_rScopeGivingCe )\n : HtmlFactory_Idl( io_rEnv, 0 ),\n pTitleOut(0),\n aTextOut(io_rEnv, 0, i_rScopeGivingCe)\n{\n}\n\nHF_IdlTag::~HF_IdlTag()\n{\n}\n\nvoid\nHF_IdlTag::Produce_byData( Xml::Element & o_rTitle,\n Xml::Element & o_rText,\n const ary::info::AtTag2 & i_rTag ) const\n{\n pTitleOut = &o_rTitle;\n Enter_TextOut(o_rText);\n i_rTag.DisplayAt( const_cast< HF_IdlTag& >(*this) );\n Leave_TextOut();\n}\n\nvoid\nHF_IdlTag::Display_StdAtTag( const csi::dsapi::DT_StdAtTag & i_rTag )\n{\n if ( i_rTag.Text().IsEmpty() )\n return;\n\n csv_assert( pTitleOut != 0 );\n *pTitleOut << i_rTag.Title();\n PutText_Out( i_rTag.Text() );\n}\n\nvoid\nHF_IdlTag::Display_SeeAlsoAtTag( const csi::dsapi::DT_SeeAlsoAtTag & i_rTag )\n{\n if ( i_rTag.Text().IsEmpty() )\n return;\n\n csv_assert( pTitleOut != 0 );\n *pTitleOut << \"See also\";\n\n HF_IdlTypeText aLinkText(Env(),aTextOut.CurOut(),true, &aTextOut.ScopeGivingCe());\n aLinkText.Produce_byData( i_rTag.LinkText() );\n\n aTextOut.CurOut() << new Html::LineBreak;\n PutText_Out( i_rTag.Text() );\n}\n\nvoid\nHF_IdlTag::Display_ParameterAtTag( const csi::dsapi::DT_ParameterAtTag & i_rTag )\n{\n csv_assert( pTitleOut != 0 );\n *pTitleOut\n << ( StreamLock(100)() << \"Parameter \" << i_rTag.Title() << c_str );\n PutText_Out( i_rTag.Text() );\n}\n\nvoid\nHF_IdlTag::Display_SinceAtTag( const csi::dsapi::DT_SinceAtTag & i_rTag )\n{\n csv_assert(pTitleOut != 0);\n\n if ( i_rTag.Text().IsEmpty() )\n {\n return;\n }\n\n \/\/ Transform the value of the @since tag into the text to be displayed.\n String sDisplay =\n autodoc::CommandLine::Get_().DisplayOf_SinceTagValue(\n i_rTag.Text().TextOfFirstToken() );\n if (sDisplay.empty())\n return;\n\n *pTitleOut << \"Since \";\n DocuTex2 aHelp;\n aHelp.AddToken(* new csi::dsapi::DT_TextToken(sDisplay));\n PutText_Out(aHelp);\n}\n\n\n\/\/******************** HF_IdlShortDocu *********************\/\n\nHF_IdlShortDocu::HF_IdlShortDocu( Environment & io_rEnv,\n Xml::Element & o_rOut )\n : HtmlFactory_Idl( io_rEnv, &o_rOut )\n{\n}\n\nHF_IdlShortDocu::~HF_IdlShortDocu()\n{\n}\n\nvoid\nHF_IdlShortDocu::Produce_byData( const ary::idl::CodeEntity & i_rCe )\n{\n if (i_rCe.Docu() == 0)\n return;\n\n const ce_info &\n rDocu = *i_rCe.Docu();\n if ( rDocu.IsDeprecated() )\n {\n CurOut()\n >> *new Html::Bold\n << \"[ DEPRECATED ]\" << new Html::LineBreak;\n }\n if ( rDocu.IsOptional() )\n {\n CurOut()\n >> *new Html::Bold\n << \"[ OPTIONAL ]\" << new Html::LineBreak;\n }\n\n HF_IdlDocuTextDisplay\n aText( Env(), &CurOut(), i_rCe);\n rDocu.Short().DisplayAt(aText);\n}\n\n\n\/\/******************** HF_IdlDocuTextDisplay *********************\/\n\n\nHF_IdlDocuTextDisplay::HF_IdlDocuTextDisplay( Environment & io_rEnv,\n Xml::Element * o_pOut,\n const ary::idl::CodeEntity & i_rScopeGivingCe )\n : HtmlFactory_Idl(io_rEnv, o_pOut),\n sScope(),\n sLinkToken(),\n bGatherLink(false),\n pScopeGivingCe(&i_rScopeGivingCe)\n{\n}\n\nHF_IdlDocuTextDisplay::~HF_IdlDocuTextDisplay()\n{\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_TextToken( const csi::dsapi::DT_TextToken & i_rToken )\n{\n if (bGatherLink)\n {\n if (sLinkToken.length() == 0)\n {\n sLinkToken = i_rToken.GetText();\n return;\n }\n else\n {\n if ( pScopeGivingCe == 0 )\n { \/\/ only in original file\n TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsText(), 0);\n }\n else\n {\n Cerr() << \"Error in documentation: Too many or too few tokens for a link in or .\" << Endl();\n Cerr() << \" Link won't be created, but all tokens shown plain.\" << Endl();\n Cerr() << \" \\\"\" << sLinkToken << \"\\\"\";\n if ( pScopeGivingCe != 0 )\n Cerr() << \" in \" << pScopeGivingCe->LocalName();\n Cerr() << Endl();\n }\n StopLinkGathering();\n }\n } \/\/ endif (bGatherLink)\n\n CurOut() << new Xml::XmlCode( i_rToken.GetText() ) << \" \";\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_MupType( const csi::dsapi::DT_MupType & i_rToken )\n{\n if (i_rToken.IsBegin())\n {\n StartLinkGathering(i_rToken.Scope());\n }\n else\n {\n if (bGatherLink)\n {\n CreateTypeLink();\n CurOut()\n << \" \";\n StopLinkGathering();\n }\n }\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_MupMember( const csi::dsapi::DT_MupMember & i_rToken )\n{\n if (i_rToken.IsBegin())\n {\n StartLinkGathering(i_rToken.Scope());\n }\n else\n {\n if (bGatherLink)\n {\n CreateMemberLink();\n CurOut()\n << \" \";\n StopLinkGathering();\n }\n }\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_MupConst( const csi::dsapi::DT_MupConst & i_rToken )\n{\n CurOut()\n >> *new Html::Bold\n << i_rToken.GetText();\n CurOut()\n << \" \";\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_Style( const csi::dsapi::DT_Style & i_rToken )\n{\n CurOut() << new Xml::XmlCode( i_rToken.GetText() );\n}\n\nvoid\nHF_IdlDocuTextDisplay::Display_EOL()\n{\n CurOut() << \"\\n\";\n}\n\nvoid\nHF_IdlDocuTextDisplay::CreateTypeLink()\n{\n if (strchr(sLinkToken,':') != 0)\n {\n TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsFile(\".idl\"), 0);\n CurOut() << sLinkToken;\n return;\n }\n HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());\n aLink.Produce_LinkInDocu(sScope, sLinkToken, String::Null_());\n}\n\nvoid\nHF_IdlDocuTextDisplay::CreateMemberLink()\n{\n\n HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());\n\n const char *\n sSplit = strchr(sLinkToken,':');\n\n if (sSplit != 0)\n {\n String sCe(sLinkToken.c_str(), sSplit - sLinkToken.c_str());\n String sMember(sSplit+2);\n\n if (NOT sScope.empty() OR ScopeGivingCe().LocalName() != sCe )\n aLink.Produce_LinkInDocu(sScope, sCe, sMember);\n else\n aLink.Produce_LocalLinkInDocu(sMember);\n }\n else\n {\n aLink.Produce_LocalLinkInDocu(sLinkToken);\n }\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the test suite of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n#include \n#include \n#include \n#include \n\nclass tst_QmlGraphicsLoader : public QObject\n\n{\n Q_OBJECT\npublic:\n tst_QmlGraphicsLoader();\n\nprivate slots:\n void url();\n void invalidUrl();\n void component();\n void clear();\n void urlToComponent();\n void componentToUrl();\n void sizeLoaderToItem();\n void sizeItemToLoader();\n void noResize();\n\nprivate:\n QmlEngine engine;\n};\n\n\/*\ninline QUrl TEST_FILE(const QString &filename)\n{\n QFileInfo fileInfo(__FILE__);\n return QUrl::fromLocalFile(fileInfo.absoluteDir().filePath(filename));\n}\n\ninline QUrl TEST_FILE(const char *filename)\n{\n return TEST_FILE(QLatin1String(filename));\n}\n*\/\n\ntst_QmlGraphicsLoader::tst_QmlGraphicsLoader()\n{\n}\n\nvoid tst_QmlGraphicsLoader::url()\n{\n QmlComponent component(&engine, QByteArray(\"import Qt 4.6\\nLoader { source: \\\"Rect120x60.qml\\\" }\"), QUrl(\"file:\/\/\" SRCDIR \"\/\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QVERIFY(loader->item());\n QVERIFY(loader->source() == QUrl(\"file:\/\/\" SRCDIR \"\/Rect120x60.qml\"));\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(loader->status(), QmlGraphicsLoader::Ready);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n\n delete loader;\n}\n\nvoid tst_QmlGraphicsLoader::component()\n{\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/SetSourceComponent.qml\"));\n QmlGraphicsItem *item = qobject_cast(component.create());\n QVERIFY(item);\n\n QmlGraphicsLoader *loader = qobject_cast(item->QGraphicsObject::children().at(1)); \n QVERIFY(loader);\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(loader->status(), QmlGraphicsLoader::Ready);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n\n delete loader;\n}\n\nvoid tst_QmlGraphicsLoader::invalidUrl()\n{\n\/\/ QTest::ignoreMessage(QtWarningMsg, \"(:-1: File error for URL file:\/\/\" SRCDIR \"\/IDontExist.qml)\");\n\n QmlComponent component(&engine, QByteArray(\"import Qt 4.6\\nLoader { source: \\\"IDontExist.qml\\\" }\"), QUrl(\"file:\/\/\" SRCDIR \"\/\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QVERIFY(loader->item() == 0);\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(loader->status(), QmlGraphicsLoader::Error);\n QCOMPARE(static_cast(loader)->children().count(), 0);\n\n delete loader;\n}\n\nvoid tst_QmlGraphicsLoader::clear()\n{\n {\n QmlComponent component(&engine, QByteArray(\n \"import Qt 4.6\\n\"\n \" Loader { id: loader\\n\"\n \" source: 'Rect120x60.qml'\\n\"\n \" Timer { interval: 200; running: true; onTriggered: loader.source = '' }\\n\"\n \" }\")\n , QUrl(\"file:\/\/\" SRCDIR \"\/\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n\n QTest::qWait(500);\n\n QVERIFY(loader->item() == 0);\n QCOMPARE(loader->progress(), 0.0);\n QCOMPARE(loader->status(), QmlGraphicsLoader::Null);\n QCOMPARE(static_cast(loader)->children().count(), 0);\n\n delete loader;\n }\n {\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/SetSourceComponent.qml\"));\n QmlGraphicsItem *item = qobject_cast(component.create());\n QVERIFY(item);\n\n QmlGraphicsLoader *loader = qobject_cast(item->QGraphicsObject::children().at(1)); \n QVERIFY(loader);\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n\n loader->setSourceComponent(0);\n\n QVERIFY(loader->item() == 0);\n QCOMPARE(loader->progress(), 0.0);\n QCOMPARE(loader->status(), QmlGraphicsLoader::Null);\n QCOMPARE(static_cast(loader)->children().count(), 0);\n\n delete loader;\n }\n}\n\nvoid tst_QmlGraphicsLoader::urlToComponent()\n{\n QmlComponent component(&engine, QByteArray(\"import Qt 4.6\\n\"\n \"Loader {\\n\"\n \" id: loader\\n\"\n \" Component { id: myComp; Rectangle { width: 10; height: 10 } }\\n\"\n \" source: \\\"Rect120x60.qml\\\"\\n\"\n \" Timer { interval: 100; running: true; onTriggered: loader.sourceComponent = myComp }\\n\"\n \"}\" )\n , QUrl(\"file:\/\/\" SRCDIR \"\/\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QTest::qWait(500);\n QVERIFY(loader != 0);\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n QCOMPARE(loader->width(), 10.0);\n QCOMPARE(loader->height(), 10.0);\n\n delete loader;\n}\n\nvoid tst_QmlGraphicsLoader::componentToUrl()\n{\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/SetSourceComponent.qml\"));\n QmlGraphicsItem *item = qobject_cast(component.create());\n QVERIFY(item);\n\n QmlGraphicsLoader *loader = qobject_cast(item->QGraphicsObject::children().at(1)); \n QVERIFY(loader);\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n\n loader->setSource(QUrl(\"file:\/\/\" SRCDIR \"\/Rect120x60.qml\"));\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n QCOMPARE(loader->width(), 120.0);\n QCOMPARE(loader->height(), 60.0);\n\n delete loader;\n}\n\nvoid tst_QmlGraphicsLoader::sizeLoaderToItem()\n{\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/SizeToItem.qml\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QVERIFY(loader->resizeMode() == QmlGraphicsLoader::SizeLoaderToItem);\n QCOMPARE(loader->width(), 120.0);\n QCOMPARE(loader->height(), 60.0);\n\n \/\/ Check resize\n QmlGraphicsItem *rect = loader->item();\n QVERIFY(rect);\n rect->setWidth(150);\n rect->setHeight(45);\n QCOMPARE(loader->width(), 150.0);\n QCOMPARE(loader->height(), 45.0);\n\n \/\/ Switch mode\n loader->setResizeMode(QmlGraphicsLoader::SizeItemToLoader);\n loader->setWidth(180);\n loader->setHeight(30);\n QCOMPARE(rect->width(), 180.0);\n QCOMPARE(rect->height(), 30.0);\n}\n\nvoid tst_QmlGraphicsLoader::sizeItemToLoader()\n{\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/SizeToLoader.qml\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QVERIFY(loader->resizeMode() == QmlGraphicsLoader::SizeItemToLoader);\n QCOMPARE(loader->width(), 200.0);\n QCOMPARE(loader->height(), 80.0);\n\n QmlGraphicsItem *rect = loader->item();\n QVERIFY(rect);\n QCOMPARE(rect->width(), 200.0);\n QCOMPARE(rect->height(), 80.0);\n\n \/\/ Check resize\n loader->setWidth(180);\n loader->setHeight(30);\n QCOMPARE(rect->width(), 180.0);\n QCOMPARE(rect->height(), 30.0);\n}\n\nvoid tst_QmlGraphicsLoader::noResize()\n{\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/NoResize.qml\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QCOMPARE(loader->width(), 200.0);\n QCOMPARE(loader->height(), 80.0);\n\n QmlGraphicsItem *rect = loader->item();\n QVERIFY(rect);\n QCOMPARE(rect->width(), 120.0);\n QCOMPARE(rect->height(), 60.0);\n}\n\nQTEST_MAIN(tst_QmlGraphicsLoader)\n\n#include \"tst_qmlgraphicsloader.moc\"\nFix error message (warning often have trailing spaces)\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the test suite of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n#include \n#include \n#include \n#include \n\nclass tst_QmlGraphicsLoader : public QObject\n\n{\n Q_OBJECT\npublic:\n tst_QmlGraphicsLoader();\n\nprivate slots:\n void url();\n void invalidUrl();\n void component();\n void clear();\n void urlToComponent();\n void componentToUrl();\n void sizeLoaderToItem();\n void sizeItemToLoader();\n void noResize();\n\nprivate:\n QmlEngine engine;\n};\n\n\/*\ninline QUrl TEST_FILE(const QString &filename)\n{\n QFileInfo fileInfo(__FILE__);\n return QUrl::fromLocalFile(fileInfo.absoluteDir().filePath(filename));\n}\n\ninline QUrl TEST_FILE(const char *filename)\n{\n return TEST_FILE(QLatin1String(filename));\n}\n*\/\n\ntst_QmlGraphicsLoader::tst_QmlGraphicsLoader()\n{\n}\n\nvoid tst_QmlGraphicsLoader::url()\n{\n QmlComponent component(&engine, QByteArray(\"import Qt 4.6\\nLoader { source: \\\"Rect120x60.qml\\\" }\"), QUrl(\"file:\/\/\" SRCDIR \"\/\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QVERIFY(loader->item());\n QVERIFY(loader->source() == QUrl(\"file:\/\/\" SRCDIR \"\/Rect120x60.qml\"));\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(loader->status(), QmlGraphicsLoader::Ready);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n\n delete loader;\n}\n\nvoid tst_QmlGraphicsLoader::component()\n{\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/SetSourceComponent.qml\"));\n QmlGraphicsItem *item = qobject_cast(component.create());\n QVERIFY(item);\n\n QmlGraphicsLoader *loader = qobject_cast(item->QGraphicsObject::children().at(1)); \n QVERIFY(loader);\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(loader->status(), QmlGraphicsLoader::Ready);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n\n delete loader;\n}\n\nvoid tst_QmlGraphicsLoader::invalidUrl()\n{\n QTest::ignoreMessage(QtWarningMsg, \"(:-1: File error for URL file:\/\/\" SRCDIR \"\/IDontExist.qml) \");\n\n QmlComponent component(&engine, QByteArray(\"import Qt 4.6\\nLoader { source: \\\"IDontExist.qml\\\" }\"), QUrl(\"file:\/\/\" SRCDIR \"\/\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QVERIFY(loader->item() == 0);\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(loader->status(), QmlGraphicsLoader::Error);\n QCOMPARE(static_cast(loader)->children().count(), 0);\n\n delete loader;\n}\n\nvoid tst_QmlGraphicsLoader::clear()\n{\n {\n QmlComponent component(&engine, QByteArray(\n \"import Qt 4.6\\n\"\n \" Loader { id: loader\\n\"\n \" source: 'Rect120x60.qml'\\n\"\n \" Timer { interval: 200; running: true; onTriggered: loader.source = '' }\\n\"\n \" }\")\n , QUrl(\"file:\/\/\" SRCDIR \"\/\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n\n QTest::qWait(500);\n\n QVERIFY(loader->item() == 0);\n QCOMPARE(loader->progress(), 0.0);\n QCOMPARE(loader->status(), QmlGraphicsLoader::Null);\n QCOMPARE(static_cast(loader)->children().count(), 0);\n\n delete loader;\n }\n {\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/SetSourceComponent.qml\"));\n QmlGraphicsItem *item = qobject_cast(component.create());\n QVERIFY(item);\n\n QmlGraphicsLoader *loader = qobject_cast(item->QGraphicsObject::children().at(1)); \n QVERIFY(loader);\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n\n loader->setSourceComponent(0);\n\n QVERIFY(loader->item() == 0);\n QCOMPARE(loader->progress(), 0.0);\n QCOMPARE(loader->status(), QmlGraphicsLoader::Null);\n QCOMPARE(static_cast(loader)->children().count(), 0);\n\n delete loader;\n }\n}\n\nvoid tst_QmlGraphicsLoader::urlToComponent()\n{\n QmlComponent component(&engine, QByteArray(\"import Qt 4.6\\n\"\n \"Loader {\\n\"\n \" id: loader\\n\"\n \" Component { id: myComp; Rectangle { width: 10; height: 10 } }\\n\"\n \" source: \\\"Rect120x60.qml\\\"\\n\"\n \" Timer { interval: 100; running: true; onTriggered: loader.sourceComponent = myComp }\\n\"\n \"}\" )\n , QUrl(\"file:\/\/\" SRCDIR \"\/\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QTest::qWait(500);\n QVERIFY(loader != 0);\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n QCOMPARE(loader->width(), 10.0);\n QCOMPARE(loader->height(), 10.0);\n\n delete loader;\n}\n\nvoid tst_QmlGraphicsLoader::componentToUrl()\n{\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/SetSourceComponent.qml\"));\n QmlGraphicsItem *item = qobject_cast(component.create());\n QVERIFY(item);\n\n QmlGraphicsLoader *loader = qobject_cast(item->QGraphicsObject::children().at(1)); \n QVERIFY(loader);\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n\n loader->setSource(QUrl(\"file:\/\/\" SRCDIR \"\/Rect120x60.qml\"));\n QVERIFY(loader->item());\n QCOMPARE(loader->progress(), 1.0);\n QCOMPARE(static_cast(loader)->children().count(), 1);\n QCOMPARE(loader->width(), 120.0);\n QCOMPARE(loader->height(), 60.0);\n\n delete loader;\n}\n\nvoid tst_QmlGraphicsLoader::sizeLoaderToItem()\n{\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/SizeToItem.qml\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QVERIFY(loader->resizeMode() == QmlGraphicsLoader::SizeLoaderToItem);\n QCOMPARE(loader->width(), 120.0);\n QCOMPARE(loader->height(), 60.0);\n\n \/\/ Check resize\n QmlGraphicsItem *rect = loader->item();\n QVERIFY(rect);\n rect->setWidth(150);\n rect->setHeight(45);\n QCOMPARE(loader->width(), 150.0);\n QCOMPARE(loader->height(), 45.0);\n\n \/\/ Switch mode\n loader->setResizeMode(QmlGraphicsLoader::SizeItemToLoader);\n loader->setWidth(180);\n loader->setHeight(30);\n QCOMPARE(rect->width(), 180.0);\n QCOMPARE(rect->height(), 30.0);\n}\n\nvoid tst_QmlGraphicsLoader::sizeItemToLoader()\n{\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/SizeToLoader.qml\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QVERIFY(loader->resizeMode() == QmlGraphicsLoader::SizeItemToLoader);\n QCOMPARE(loader->width(), 200.0);\n QCOMPARE(loader->height(), 80.0);\n\n QmlGraphicsItem *rect = loader->item();\n QVERIFY(rect);\n QCOMPARE(rect->width(), 200.0);\n QCOMPARE(rect->height(), 80.0);\n\n \/\/ Check resize\n loader->setWidth(180);\n loader->setHeight(30);\n QCOMPARE(rect->width(), 180.0);\n QCOMPARE(rect->height(), 30.0);\n}\n\nvoid tst_QmlGraphicsLoader::noResize()\n{\n QmlComponent component(&engine, QUrl(\"file:\/\/\" SRCDIR \"\/NoResize.qml\"));\n QmlGraphicsLoader *loader = qobject_cast(component.create());\n QVERIFY(loader != 0);\n QCOMPARE(loader->width(), 200.0);\n QCOMPARE(loader->height(), 80.0);\n\n QmlGraphicsItem *rect = loader->item();\n QVERIFY(rect);\n QCOMPARE(rect->width(), 120.0);\n QCOMPARE(rect->height(), 60.0);\n}\n\nQTEST_MAIN(tst_QmlGraphicsLoader)\n\n#include \"tst_qmlgraphicsloader.moc\"\n<|endoftext|>"} {"text":"\n#include \n\n#include \"SCIP.hpp\"\n#include \"scip_exception.hpp\"\n#include \n\n\n\/**************************************************************\n ******************** Solver ***********************\n **************************************************************\/\n\nSCIPSolver::SCIPSolver(){\n\n DBG(\"create a scip solver\\n%s\", \"\");\n\n var_counter = 0;\n _verbosity = 0;\n has_been_added = false;\n\n \/\/ Load up SCIP\n SCIP_CALL_EXC( SCIPcreate(& _scip) );\n \/\/ load default plugins linke separators, heuristics, etc.\n SCIP_CALL_EXC( SCIPincludeDefaultPlugins(_scip) );\n \/\/ create an empty problem\n SCIP_CALL_EXC( SCIPcreateProb(_scip, \"Numberjack Model\",\n\t\t\t\tNULL, NULL, NULL, NULL, NULL, NULL, NULL) );\n \/\/ set the objective sense to maximize, default is minimize\n SCIP_CALL_EXC( SCIPsetObjsense(_scip, SCIP_OBJSENSE_MAXIMIZE) );\n}\n\nSCIPSolver::~SCIPSolver(){ DBG(\"delete wrapped solver\\n%s\", \"\"); }\n\nSCIP* SCIPSolver::get_scip() {return _scip;}\n\nvoid SCIPSolver::initialise(MipWrapperExpArray& arg){\n DBG(\"Initialise the Solver with search vars %s\\n\", \"\");\n\n initialise();\n}\n\nvoid SCIPSolver::initialise(){\n DBG(\"initialise the solver%s\\n\", \"\");\n MipWrapperSolver::initialise();\n if(_obj != NULL) add_in_constraint(_obj, _obj_coef);\n for(unsigned int i = 0; i < _constraints.size(); ++i)\n add_in_constraint(_constraints[i]);\n has_been_added = true;\n}\n\nvoid SCIPSolver::add_in_constraint(LinearConstraint *con, double coef){\n DBG(\"Creating a SCIP representation of a constriant%s\\n\", \"\");\n \n double *weights = new double[con->_coefficients.size()];\n SCIP_VAR** vars = new SCIP_VAR*[con->_variables.size()];\n \n for(unsigned int i = 0; i < con->_variables.size(); ++i){\n \n DBG(\"\\tAdding variable to SCIP\\n%s\", \"\");\n \n if(con->_variables[i]->_var == NULL){\n \n SCIP_VAR* var_ptr;\n SCIP_VARTYPE type;\n \n if(con->_variables[i]->_continuous) type = SCIP_VARTYPE_CONTINUOUS;\n else type = SCIP_VARTYPE_INTEGER;\n \n SCIP_CALL_EXC(SCIPcreateVar(_scip, &var_ptr,\n\t\t\t\t \"SCIP_Var\",\n\t\t\t\t con->_variables[i]->_lower, \/\/ LB\n\t\t\t\t con->_variables[i]->_upper, \/\/ UB\n\t\t\t\t coef, \/\/ ective\n\t\t\t\t type,\n\t\t\t\t TRUE, FALSE, NULL, NULL, NULL, NULL, NULL) );\n SCIP_CALL_EXC( SCIPaddVar(_scip, var_ptr) );\n \n con->_variables[i]->_var = (void*) var_ptr;\n vars[i] = var_ptr;\n weights[i] = con->_coefficients[i];\n } else {\n vars[i] = (SCIP_VAR*) con->_variables[i]->_var;\n weights[i] = con->_coefficients[i];\n }\n }\n \n SCIP_CONS *scip_con;\n SCIP_CALL_EXC( SCIPcreateConsLinear(_scip, &scip_con,\"constraint\",\n\t\t\t\t\tcon->_variables.size(), \/\/ # vars\n\t\t\t\t\tvars, \/\/ variables\n\t\t\t\t\tweights, \/\/ values\n\t\t\t\t\tcon->_lhs, \/\/ LHS\n\t\t\t\t\tcon->_rhs, \/\/ RHS\n\t\t\t\t\tTRUE, TRUE, TRUE, TRUE, TRUE,\n\t\t\t\t\tFALSE, FALSE, FALSE, FALSE, FALSE) );\n SCIP_CALL_EXC( SCIPaddCons(_scip, scip_con) ); \n}\n\nint SCIPSolver::solve(){\n DBG(\"solve!%s\\n\", \"\");\n \n if(!has_been_added) initialise();\n\n if(_verbosity > 0 && _verbosity < 3){\n \/\/ Do nothing extra\n } else if(_verbosity >= 3){\n \/\/SCIP_CALL_EXC(SCIPwriteOrigProblem(_scip, \"scip_model\", NULL, TRUE));\n SCIP_CALL_EXC(SCIPprintOrigProblem(_scip, NULL, NULL, FALSE));\n } else {\n \/\/ disable scip output to stdout\n SCIP_CALL_EXC( SCIPsetMessagehdlr(_scip, NULL) );\n }\n\n SCIP_CALL_EXC( SCIPsolve(_scip) );\n SCIP_STATUS status = SCIPgetStatus(_scip);\n \n if( status == SCIP_STATUS_OPTIMAL ) return SAT;\n else if( status == SCIP_STATUS_INFEASIBLE ) return UNSAT;\n else return UNKNOWN;\n}\n\nvoid SCIPSolver::setTimeLimit(const int cutoff){\n SCIPsetRealParam(_scip, \"limits\/time\", (double)cutoff);\n}\n \nvoid SCIPSolver::setVerbosity(const int degree){ _verbosity = degree; }\n\nbool SCIPSolver::is_sat(){\n return !( SCIPgetStatus(_scip) == SCIP_STATUS_INFEASIBLE );\n}\n\nbool SCIPSolver::is_unsat(){ return ! is_sat(); }\n\nbool SCIPSolver::is_opt(){\n return SCIPgetStatus(_scip) == SCIP_STATUS_OPTIMAL;\n}\n\nvoid SCIPSolver::printStatistics(){\n std::cout << \"\\td Time: \" << getTime() << \"\\tNodes:\" << getNodes()\n\t << std::endl;\n if(_verbosity > 1){\n SCIP_CALL_EXC(SCIPprintStatistics(_scip, NULL));\n }\n}\n\nint SCIPSolver::getNodes(){ return _scip->stat->nnodes; }\n\ndouble SCIPSolver::getTime(){\n return SCIPclockGetTime(_scip->stat->solvingtime);\n}\n\ndouble SCIPSolver::get_value(void *ptr){\n return SCIPgetSolVal(_scip, SCIPgetBestSol(_scip), (SCIP_VAR*) ptr);\n}\nVariables coefficients in the objective was not being passed to SCIP.\n#include \n\n#include \"SCIP.hpp\"\n#include \"scip_exception.hpp\"\n#include \n\n\n\/**************************************************************\n ******************** Solver ***********************\n **************************************************************\/\n\nSCIPSolver::SCIPSolver(){\n\n DBG(\"create a scip solver\\n%s\", \"\");\n\n var_counter = 0;\n _verbosity = 0;\n has_been_added = false;\n\n \/\/ Load up SCIP\n SCIP_CALL_EXC( SCIPcreate(& _scip) );\n \/\/ load default plugins linke separators, heuristics, etc.\n SCIP_CALL_EXC( SCIPincludeDefaultPlugins(_scip) );\n \/\/ create an empty problem\n SCIP_CALL_EXC( SCIPcreateProb(_scip, \"Numberjack Model\",\n\t\t\t\tNULL, NULL, NULL, NULL, NULL, NULL, NULL) );\n \/\/ set the objective sense to maximize, default is minimize\n SCIP_CALL_EXC( SCIPsetObjsense(_scip, SCIP_OBJSENSE_MAXIMIZE) );\n}\n\nSCIPSolver::~SCIPSolver(){ DBG(\"delete wrapped solver\\n%s\", \"\"); }\n\nSCIP* SCIPSolver::get_scip() {return _scip;}\n\nvoid SCIPSolver::initialise(MipWrapperExpArray& arg){\n DBG(\"Initialise the Solver with search vars %s\\n\", \"\");\n\n initialise();\n}\n\nvoid SCIPSolver::initialise(){\n DBG(\"initialise the solver%s\\n\", \"\");\n MipWrapperSolver::initialise();\n if(_obj != NULL) add_in_constraint(_obj, _obj_coef);\n for(unsigned int i = 0; i < _constraints.size(); ++i)\n add_in_constraint(_constraints[i]);\n has_been_added = true;\n}\n\nvoid SCIPSolver::add_in_constraint(LinearConstraint *con, double coef){\n DBG(\"Creating a SCIP representation of a constriant%s\\n\", \"\");\n \n double *weights = new double[con->_coefficients.size()];\n SCIP_VAR** vars = new SCIP_VAR*[con->_variables.size()];\n \n for(unsigned int i = 0; i < con->_variables.size(); ++i){\n \n DBG(\"\\tAdding variable to SCIP\\n%s\", \"\");\n \n if(con->_variables[i]->_var == NULL){\n \n SCIP_VAR* var_ptr;\n SCIP_VARTYPE type;\n \n if(con->_variables[i]->_continuous) type = SCIP_VARTYPE_CONTINUOUS;\n else type = SCIP_VARTYPE_INTEGER;\n \n SCIP_CALL_EXC(SCIPcreateVar(_scip, &var_ptr,\n\t\t\t\t \"SCIP_Var\",\n\t\t\t\t con->_variables[i]->_lower, \/\/ LB\n\t\t\t\t con->_variables[i]->_upper, \/\/ UB\n\t\t\t\t coef * con->_coefficients[i], \/\/ ective\n\t\t\t\t type,\n\t\t\t\t TRUE, FALSE, NULL, NULL, NULL, NULL, NULL) );\n SCIP_CALL_EXC( SCIPaddVar(_scip, var_ptr) );\n \n con->_variables[i]->_var = (void*) var_ptr;\n vars[i] = var_ptr;\n weights[i] = con->_coefficients[i];\n } else {\n vars[i] = (SCIP_VAR*) con->_variables[i]->_var;\n weights[i] = con->_coefficients[i];\n }\n }\n \n SCIP_CONS *scip_con;\n SCIP_CALL_EXC( SCIPcreateConsLinear(_scip, &scip_con,\"constraint\",\n\t\t\t\t\tcon->_variables.size(), \/\/ # vars\n\t\t\t\t\tvars, \/\/ variables\n\t\t\t\t\tweights, \/\/ values\n\t\t\t\t\tcon->_lhs, \/\/ LHS\n\t\t\t\t\tcon->_rhs, \/\/ RHS\n\t\t\t\t\tTRUE, TRUE, TRUE, TRUE, TRUE,\n\t\t\t\t\tFALSE, FALSE, FALSE, FALSE, FALSE) );\n SCIP_CALL_EXC( SCIPaddCons(_scip, scip_con) ); \n}\n\nint SCIPSolver::solve(){\n DBG(\"solve!%s\\n\", \"\");\n \n if(!has_been_added) initialise();\n\n if(_verbosity > 0 && _verbosity < 3){\n \/\/ Do nothing extra\n } else if(_verbosity >= 3){\n SCIP_CALL_EXC(SCIPprintOrigProblem(_scip, NULL, NULL, FALSE));\n \/\/ SCIP_CALL_EXC(SCIPwriteOrigProblem(_scip, \"scip.lp\", \"lp\", TRUE));\n } else {\n \/\/ disable scip output to stdout\n SCIP_CALL_EXC( SCIPsetMessagehdlr(_scip, NULL) );\n }\n\n SCIP_CALL_EXC( SCIPsolve(_scip) );\n SCIP_STATUS status = SCIPgetStatus(_scip);\n \n if( status == SCIP_STATUS_OPTIMAL ) return SAT;\n else if( status == SCIP_STATUS_INFEASIBLE ) return UNSAT;\n else return UNKNOWN;\n}\n\nvoid SCIPSolver::setTimeLimit(const int cutoff){\n SCIPsetRealParam(_scip, \"limits\/time\", (double)cutoff);\n}\n \nvoid SCIPSolver::setVerbosity(const int degree){ _verbosity = degree; }\n\nbool SCIPSolver::is_sat(){\n return !( SCIPgetStatus(_scip) == SCIP_STATUS_INFEASIBLE );\n}\n\nbool SCIPSolver::is_unsat(){ return ! is_sat(); }\n\nbool SCIPSolver::is_opt(){\n return SCIPgetStatus(_scip) == SCIP_STATUS_OPTIMAL;\n}\n\nvoid SCIPSolver::printStatistics(){\n std::cout << \"\\td Time: \" << getTime() << \"\\tNodes:\" << getNodes()\n\t << std::endl;\n if(_verbosity > 1){\n SCIP_CALL_EXC(SCIPprintStatistics(_scip, NULL));\n }\n}\n\nint SCIPSolver::getNodes(){ return _scip->stat->nnodes; }\n\ndouble SCIPSolver::getTime(){\n return SCIPclockGetTime(_scip->stat->solvingtime);\n}\n\ndouble SCIPSolver::get_value(void *ptr){\n return SCIPgetSolVal(_scip, SCIPgetBestSol(_scip), (SCIP_VAR*) ptr);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/time.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n#include \"base\/mac\/scoped_cftyperef.h\"\n\nnamespace base {\n\n\/\/ The Time routines in this file use Mach and CoreFoundation APIs, since the\n\/\/ POSIX definition of time_t in Mac OS X wraps around after 2038--and\n\/\/ there are already cookie expiration dates, etc., past that time out in\n\/\/ the field. Using CFDate prevents that problem, and using mach_absolute_time\n\/\/ for TimeTicks gives us nice high-resolution interval timing.\n\n\/\/ Time -----------------------------------------------------------------------\n\n\/\/ Core Foundation uses a double second count since 2001-01-01 00:00:00 UTC.\n\/\/ The UNIX epoch is 1970-01-01 00:00:00 UTC.\n\/\/ Windows uses a Gregorian epoch of 1601. We need to match this internally\n\/\/ so that our time representations match across all platforms. See bug 14734.\n\/\/ irb(main):010:0> Time.at(0).getutc()\n\/\/ => Thu Jan 01 00:00:00 UTC 1970\n\/\/ irb(main):011:0> Time.at(-11644473600).getutc()\n\/\/ => Mon Jan 01 00:00:00 UTC 1601\nstatic const int64 kWindowsEpochDeltaSeconds = GG_INT64_C(11644473600);\nstatic const int64 kWindowsEpochDeltaMilliseconds =\n kWindowsEpochDeltaSeconds * Time::kMillisecondsPerSecond;\n\n\/\/ static\nconst int64 Time::kWindowsEpochDeltaMicroseconds =\n kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond;\n\n\/\/ Some functions in time.cc use time_t directly, so we provide an offset\n\/\/ to convert from time_t (Unix epoch) and internal (Windows epoch).\n\/\/ static\nconst int64 Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds;\n\n\/\/ static\nTime Time::Now() {\n CFAbsoluteTime now =\n CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970;\n return Time(static_cast(now * kMicrosecondsPerSecond) +\n kWindowsEpochDeltaMicroseconds);\n}\n\n\/\/ static\nTime Time::NowFromSystemTime() {\n \/\/ Just use Now() because Now() returns the system time.\n return Now();\n}\n\n\/\/ static\nTime Time::FromExploded(bool is_local, const Exploded& exploded) {\n CFGregorianDate date;\n date.second = exploded.second +\n exploded.millisecond \/ static_cast(kMillisecondsPerSecond);\n date.minute = exploded.minute;\n date.hour = exploded.hour;\n date.day = exploded.day_of_month;\n date.month = exploded.month;\n date.year = exploded.year;\n\n base::mac::ScopedCFTypeRef\n time_zone(is_local ? CFTimeZoneCopySystem() : NULL);\n CFAbsoluteTime seconds = CFGregorianDateGetAbsoluteTime(date, time_zone) +\n kCFAbsoluteTimeIntervalSince1970;\n return Time(static_cast(seconds * kMicrosecondsPerSecond) +\n kWindowsEpochDeltaMicroseconds);\n}\n\nvoid Time::Explode(bool is_local, Exploded* exploded) const {\n CFAbsoluteTime seconds =\n (static_cast((us_ - kWindowsEpochDeltaMicroseconds) \/\n kMicrosecondsPerSecond) - kCFAbsoluteTimeIntervalSince1970);\n\n base::mac::ScopedCFTypeRef\n time_zone(is_local ? CFTimeZoneCopySystem() : NULL);\n CFGregorianDate date = CFAbsoluteTimeGetGregorianDate(seconds, time_zone);\n\n exploded->year = date.year;\n exploded->month = date.month;\n exploded->day_of_month = date.day;\n exploded->hour = date.hour;\n exploded->minute = date.minute;\n exploded->second = date.second;\n exploded->millisecond =\n static_cast(date.second * kMillisecondsPerSecond) %\n kMillisecondsPerSecond;\n}\n\n\/\/ TimeTicks ------------------------------------------------------------------\n\n\/\/ static\nTimeTicks TimeTicks::Now() {\n uint64_t absolute_micro;\n\n static mach_timebase_info_data_t timebase_info;\n if (timebase_info.denom == 0) {\n \/\/ Zero-initialization of statics guarantees that denom will be 0 before\n \/\/ calling mach_timebase_info. mach_timebase_info will never set denom to\n \/\/ 0 as that would be invalid, so the zero-check can be used to determine\n \/\/ whether mach_timebase_info has already been called. This is\n \/\/ recommended by Apple's QA1398.\n kern_return_t kr = mach_timebase_info(&timebase_info);\n DCHECK(kr == KERN_SUCCESS);\n }\n\n \/\/ mach_absolute_time is it when it comes to ticks on the Mac. Other calls\n \/\/ with less precision (such as TickCount) just call through to\n \/\/ mach_absolute_time.\n\n \/\/ timebase_info converts absolute time tick units into nanoseconds. Convert\n \/\/ to microseconds up front to stave off overflows.\n absolute_micro = mach_absolute_time() \/ Time::kNanosecondsPerMicrosecond *\n timebase_info.numer \/ timebase_info.denom;\n\n \/\/ Don't bother with the rollover handling that the Windows version does.\n \/\/ With numer and denom = 1 (the expected case), the 64-bit absolute time\n \/\/ reported in nanoseconds is enough to last nearly 585 years.\n\n return TimeTicks(absolute_micro);\n}\n\n\/\/ static\nTimeTicks TimeTicks::HighResNow() {\n return Now();\n}\n\n} \/\/ namespace base\nPut the parentheses back where they belong in time_mac.cc. This will allow Aaron's new test in http:\/\/codereview.chromium.org\/4471001 to pass.\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/time.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n#include \"base\/mac\/scoped_cftyperef.h\"\n\nnamespace base {\n\n\/\/ The Time routines in this file use Mach and CoreFoundation APIs, since the\n\/\/ POSIX definition of time_t in Mac OS X wraps around after 2038--and\n\/\/ there are already cookie expiration dates, etc., past that time out in\n\/\/ the field. Using CFDate prevents that problem, and using mach_absolute_time\n\/\/ for TimeTicks gives us nice high-resolution interval timing.\n\n\/\/ Time -----------------------------------------------------------------------\n\n\/\/ Core Foundation uses a double second count since 2001-01-01 00:00:00 UTC.\n\/\/ The UNIX epoch is 1970-01-01 00:00:00 UTC.\n\/\/ Windows uses a Gregorian epoch of 1601. We need to match this internally\n\/\/ so that our time representations match across all platforms. See bug 14734.\n\/\/ irb(main):010:0> Time.at(0).getutc()\n\/\/ => Thu Jan 01 00:00:00 UTC 1970\n\/\/ irb(main):011:0> Time.at(-11644473600).getutc()\n\/\/ => Mon Jan 01 00:00:00 UTC 1601\nstatic const int64 kWindowsEpochDeltaSeconds = GG_INT64_C(11644473600);\nstatic const int64 kWindowsEpochDeltaMilliseconds =\n kWindowsEpochDeltaSeconds * Time::kMillisecondsPerSecond;\n\n\/\/ static\nconst int64 Time::kWindowsEpochDeltaMicroseconds =\n kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond;\n\n\/\/ Some functions in time.cc use time_t directly, so we provide an offset\n\/\/ to convert from time_t (Unix epoch) and internal (Windows epoch).\n\/\/ static\nconst int64 Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds;\n\n\/\/ static\nTime Time::Now() {\n CFAbsoluteTime now =\n CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970;\n return Time(static_cast(now * kMicrosecondsPerSecond) +\n kWindowsEpochDeltaMicroseconds);\n}\n\n\/\/ static\nTime Time::NowFromSystemTime() {\n \/\/ Just use Now() because Now() returns the system time.\n return Now();\n}\n\n\/\/ static\nTime Time::FromExploded(bool is_local, const Exploded& exploded) {\n CFGregorianDate date;\n date.second = exploded.second +\n exploded.millisecond \/ static_cast(kMillisecondsPerSecond);\n date.minute = exploded.minute;\n date.hour = exploded.hour;\n date.day = exploded.day_of_month;\n date.month = exploded.month;\n date.year = exploded.year;\n\n base::mac::ScopedCFTypeRef\n time_zone(is_local ? CFTimeZoneCopySystem() : NULL);\n CFAbsoluteTime seconds = CFGregorianDateGetAbsoluteTime(date, time_zone) +\n kCFAbsoluteTimeIntervalSince1970;\n return Time(static_cast(seconds * kMicrosecondsPerSecond) +\n kWindowsEpochDeltaMicroseconds);\n}\n\nvoid Time::Explode(bool is_local, Exploded* exploded) const {\n CFAbsoluteTime seconds =\n ((static_cast(us_) - kWindowsEpochDeltaMicroseconds) \/\n kMicrosecondsPerSecond) - kCFAbsoluteTimeIntervalSince1970;\n\n base::mac::ScopedCFTypeRef\n time_zone(is_local ? CFTimeZoneCopySystem() : NULL);\n CFGregorianDate date = CFAbsoluteTimeGetGregorianDate(seconds, time_zone);\n\n exploded->year = date.year;\n exploded->month = date.month;\n exploded->day_of_month = date.day;\n exploded->hour = date.hour;\n exploded->minute = date.minute;\n exploded->second = date.second;\n exploded->millisecond =\n static_cast(date.second * kMillisecondsPerSecond) %\n kMillisecondsPerSecond;\n}\n\n\/\/ TimeTicks ------------------------------------------------------------------\n\n\/\/ static\nTimeTicks TimeTicks::Now() {\n uint64_t absolute_micro;\n\n static mach_timebase_info_data_t timebase_info;\n if (timebase_info.denom == 0) {\n \/\/ Zero-initialization of statics guarantees that denom will be 0 before\n \/\/ calling mach_timebase_info. mach_timebase_info will never set denom to\n \/\/ 0 as that would be invalid, so the zero-check can be used to determine\n \/\/ whether mach_timebase_info has already been called. This is\n \/\/ recommended by Apple's QA1398.\n kern_return_t kr = mach_timebase_info(&timebase_info);\n DCHECK(kr == KERN_SUCCESS);\n }\n\n \/\/ mach_absolute_time is it when it comes to ticks on the Mac. Other calls\n \/\/ with less precision (such as TickCount) just call through to\n \/\/ mach_absolute_time.\n\n \/\/ timebase_info converts absolute time tick units into nanoseconds. Convert\n \/\/ to microseconds up front to stave off overflows.\n absolute_micro = mach_absolute_time() \/ Time::kNanosecondsPerMicrosecond *\n timebase_info.numer \/ timebase_info.denom;\n\n \/\/ Don't bother with the rollover handling that the Windows version does.\n \/\/ With numer and denom = 1 (the expected case), the 64-bit absolute time\n \/\/ reported in nanoseconds is enough to last nearly 585 years.\n\n return TimeTicks(absolute_micro);\n}\n\n\/\/ static\nTimeTicks TimeTicks::HighResNow() {\n return Now();\n}\n\n} \/\/ namespace base\n<|endoftext|>"} {"text":"\/*\n This file is part of KAddressBook.\n Copyright (C) 2003 Helge Deller \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n version 2 License as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n\/*\n * - ldifvcardthumbnail -\n *\n * kioslave which generates tumbnails for vCard and LDIF files.\n * The thumbnails are used e.g. by Konqueror or in the file selection\n * dialog.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ldifvcardcreator.h\"\n\nextern \"C\"\n{\n ThumbCreator *new_creator()\n {\n KGlobal::locale()->insertCatalog( \"kaddressbook\" );\n return new VCard_LDIFCreator;\n }\n}\n\nVCard_LDIFCreator::VCard_LDIFCreator()\n : mFont( 0 )\n{\n}\n\nVCard_LDIFCreator::~VCard_LDIFCreator()\n{\n delete mFont;\n}\n\n\nbool VCard_LDIFCreator::readContents( const QString &path )\n{\n \/\/ read file contents\n QFile file( path );\n if ( !file.open( QIODevice::ReadOnly ) )\n return false;\n\n QString info;\n text.truncate(0);\n\n \/\/ read the file\n QByteArray contents = file.readAll();\n file.close();\n\n \/\/ convert the file contents to a KABC::Addressee address\n KABC::Addressee::List addrList;\n KABC::Addressee addr;\n KABC::VCardConverter converter;\n\n addrList = converter.parseVCards( contents);\n if ( addrList.count() == 0 ) {\n KABC::AddresseeList l; \/\/ FIXME porting\n if ( !KABC::LDIFConverter::LDIFToAddressee( contents, l ) )\n\treturn false;\n \/\/ FIXME porting\n KABC::AddresseeList::ConstIterator it( l.constBegin() );\n for ( ; it != l.constEnd(); ++ it ) {\n addrList.append( *it );\n }\n }\n if ( addrList.count()>1 ) {\n \/\/ create an overview (list of all names)\n name = i18np(\"One contact found:\", \"%1 contacts found:\", addrList.count());\n int no, linenr;\n for (linenr=no=0; linenr<30 && no 0 );\n \/\/const QPixmap *fontPixmap = &(mSplitter->pixmap());\n\n for ( int i = 0; i < text.length(); i++ ) {\n if ( x > posNewLine || newLine ) { \/\/ start a new line?\n x = xborder;\n y += yOffset;\n\n if ( y > posLastLine ) \/\/ more text than space\n break;\n\n \/\/ after starting a new line, we also jump to the next\n \/\/ physical newline in the file if we don't come from one\n if ( !newLine ) {\n int pos = text.indexOf( '\\n', i );\n if ( pos > (int) i )\n i = pos +1;\n }\n\n newLine = false;\n }\n\n \/\/ check for newlines in the text (unix,dos)\n QChar ch = text.at( i );\n if ( ch == '\\n' ) {\n newLine = true;\n continue;\n } else if ( ch == '\\r' && text.at(i+1) == '\\n' ) {\n newLine = true;\n i++; \/\/ skip the next character (\\n) as well\n continue;\n }\n\n rect = glyphCoords( (unsigned char)ch.toLatin1(), mFont->width() );\n \/* FIXME porting\n if ( !rect.isEmpty() )\n bitBlt( &mPixmap, QPoint(x,y), fontPixmap, rect, Qt::CopyROP );\n *\/\n\n x += xOffset; \/\/ next character\n }\n\n return true;\n}\n\nbool VCard_LDIFCreator::createImageBig()\n{\n QFont normalFont( KGlobalSettings::generalFont() );\n QFont titleFont( normalFont );\n titleFont.setBold(true);\n \/\/ titleFont.setUnderline(true);\n titleFont.setItalic(true);\n\n QPainter painter(&mPixmap);\n painter.setFont(titleFont);\n QFontMetrics fm(painter.fontMetrics());\n\n \/\/ draw contact name\n painter.setClipRect(2, 2, pixmapSize.width()-4, pixmapSize.height()-4);\n QPoint p(5, fm.height()+2);\n painter.drawText(p, name);\n p.setY( 3*p.y()\/2 );\n\n \/\/ draw contact information\n painter.setFont(normalFont);\n fm = painter.fontMetrics();\n\n const QStringList list( text.split('\\n', QString::SkipEmptyParts) );\n for ( QStringList::ConstIterator it = list.begin();\n p.y()<=pixmapSize.height() && it != list.end(); ++it ) {\n p.setY( p.y() + fm.height() );\n painter.drawText(p, *it);\n }\n\n return true;\n}\n\nbool VCard_LDIFCreator::create(const QString &path, int width, int height, QImage &img)\n{\n if ( !readContents(path) )\n return false;\n\n \/\/ resize the image if necessary\n pixmapSize = QSize( width, height );\n if (height * 3 > width * 4)\n pixmapSize.setHeight( width * 4 \/ 3 );\n else\n pixmapSize.setWidth( height * 3 \/ 4 );\n\n if ( pixmapSize != mPixmap.size() )\n mPixmap = QPixmap( pixmapSize );\n\n mPixmap.fill( QColor( 245, 245, 245 ) ); \/\/ light-grey background\n\n \/\/ one pixel for the rectangle, the rest. whitespace\n xborder = 1 + pixmapSize.width()\/16; \/\/ minimum x-border\n yborder = 1 + pixmapSize.height()\/16; \/\/ minimum y-border\n\n bool ok;\n if ( width >= 150 \/*pixel*\/ )\n ok = createImageBig();\n else\n ok = createImageSmall();\n if (!ok)\n return false;\n\n img = mPixmap.toImage();\n return true;\n}\n\nThumbCreator::Flags VCard_LDIFCreator::flags() const\n{\n return (Flags)(DrawFrame | BlendIcon);\n}\nremove unused header\/*\n This file is part of KAddressBook.\n Copyright (C) 2003 Helge Deller \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n version 2 License as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n\/*\n * - ldifvcardthumbnail -\n *\n * kioslave which generates tumbnails for vCard and LDIF files.\n * The thumbnails are used e.g. by Konqueror or in the file selection\n * dialog.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ldifvcardcreator.h\"\n\nextern \"C\"\n{\n ThumbCreator *new_creator()\n {\n KGlobal::locale()->insertCatalog( \"kaddressbook\" );\n return new VCard_LDIFCreator;\n }\n}\n\nVCard_LDIFCreator::VCard_LDIFCreator()\n : mFont( 0 )\n{\n}\n\nVCard_LDIFCreator::~VCard_LDIFCreator()\n{\n delete mFont;\n}\n\n\nbool VCard_LDIFCreator::readContents( const QString &path )\n{\n \/\/ read file contents\n QFile file( path );\n if ( !file.open( QIODevice::ReadOnly ) )\n return false;\n\n QString info;\n text.truncate(0);\n\n \/\/ read the file\n QByteArray contents = file.readAll();\n file.close();\n\n \/\/ convert the file contents to a KABC::Addressee address\n KABC::Addressee::List addrList;\n KABC::Addressee addr;\n KABC::VCardConverter converter;\n\n addrList = converter.parseVCards( contents);\n if ( addrList.count() == 0 ) {\n KABC::AddresseeList l; \/\/ FIXME porting\n if ( !KABC::LDIFConverter::LDIFToAddressee( contents, l ) )\n\treturn false;\n \/\/ FIXME porting\n KABC::AddresseeList::ConstIterator it( l.constBegin() );\n for ( ; it != l.constEnd(); ++ it ) {\n addrList.append( *it );\n }\n }\n if ( addrList.count()>1 ) {\n \/\/ create an overview (list of all names)\n name = i18np(\"One contact found:\", \"%1 contacts found:\", addrList.count());\n int no, linenr;\n for (linenr=no=0; linenr<30 && no 0 );\n \/\/const QPixmap *fontPixmap = &(mSplitter->pixmap());\n\n for ( int i = 0; i < text.length(); i++ ) {\n if ( x > posNewLine || newLine ) { \/\/ start a new line?\n x = xborder;\n y += yOffset;\n\n if ( y > posLastLine ) \/\/ more text than space\n break;\n\n \/\/ after starting a new line, we also jump to the next\n \/\/ physical newline in the file if we don't come from one\n if ( !newLine ) {\n int pos = text.indexOf( '\\n', i );\n if ( pos > (int) i )\n i = pos +1;\n }\n\n newLine = false;\n }\n\n \/\/ check for newlines in the text (unix,dos)\n QChar ch = text.at( i );\n if ( ch == '\\n' ) {\n newLine = true;\n continue;\n } else if ( ch == '\\r' && text.at(i+1) == '\\n' ) {\n newLine = true;\n i++; \/\/ skip the next character (\\n) as well\n continue;\n }\n\n rect = glyphCoords( (unsigned char)ch.toLatin1(), mFont->width() );\n \/* FIXME porting\n if ( !rect.isEmpty() )\n bitBlt( &mPixmap, QPoint(x,y), fontPixmap, rect, Qt::CopyROP );\n *\/\n\n x += xOffset; \/\/ next character\n }\n\n return true;\n}\n\nbool VCard_LDIFCreator::createImageBig()\n{\n QFont normalFont( KGlobalSettings::generalFont() );\n QFont titleFont( normalFont );\n titleFont.setBold(true);\n \/\/ titleFont.setUnderline(true);\n titleFont.setItalic(true);\n\n QPainter painter(&mPixmap);\n painter.setFont(titleFont);\n QFontMetrics fm(painter.fontMetrics());\n\n \/\/ draw contact name\n painter.setClipRect(2, 2, pixmapSize.width()-4, pixmapSize.height()-4);\n QPoint p(5, fm.height()+2);\n painter.drawText(p, name);\n p.setY( 3*p.y()\/2 );\n\n \/\/ draw contact information\n painter.setFont(normalFont);\n fm = painter.fontMetrics();\n\n const QStringList list( text.split('\\n', QString::SkipEmptyParts) );\n for ( QStringList::ConstIterator it = list.begin();\n p.y()<=pixmapSize.height() && it != list.end(); ++it ) {\n p.setY( p.y() + fm.height() );\n painter.drawText(p, *it);\n }\n\n return true;\n}\n\nbool VCard_LDIFCreator::create(const QString &path, int width, int height, QImage &img)\n{\n if ( !readContents(path) )\n return false;\n\n \/\/ resize the image if necessary\n pixmapSize = QSize( width, height );\n if (height * 3 > width * 4)\n pixmapSize.setHeight( width * 4 \/ 3 );\n else\n pixmapSize.setWidth( height * 3 \/ 4 );\n\n if ( pixmapSize != mPixmap.size() )\n mPixmap = QPixmap( pixmapSize );\n\n mPixmap.fill( QColor( 245, 245, 245 ) ); \/\/ light-grey background\n\n \/\/ one pixel for the rectangle, the rest. whitespace\n xborder = 1 + pixmapSize.width()\/16; \/\/ minimum x-border\n yborder = 1 + pixmapSize.height()\/16; \/\/ minimum y-border\n\n bool ok;\n if ( width >= 150 \/*pixel*\/ )\n ok = createImageBig();\n else\n ok = createImageSmall();\n if (!ok)\n return false;\n\n img = mPixmap.toImage();\n return true;\n}\n\nThumbCreator::Flags VCard_LDIFCreator::flags() const\n{\n return (Flags)(DrawFrame | BlendIcon);\n}\n<|endoftext|>"} {"text":"#include \"cpp_uriparser.h\"\n#include \n#include \n\nusing namespace uri_parser;\n\nTEST(cppUriParser, traversing_through_url)\n{\n\n const char* url = \"http:\/\/www.example.com\/name%20with%20spaces\/lalala\/TheLastOne\";\n\n auto entry = uri_parser::UriParseUrl(url);\n auto pathHead = entry.PathHead();\n\n auto id = 0;\n for (auto pathFragment = std::begin(pathHead); pathFragment != std::end(pathHead); ++pathFragment, ++id)\n {\n switch (id)\n {\n case 0:\n EXPECT_STREQ(pathFragment->c_str(), \"name%20with%20spaces\");\n break;\n case 1:\n EXPECT_STREQ(pathFragment->c_str(), \"lalala\");\n break;\n case 2:\n EXPECT_STREQ(pathFragment->c_str(), \"TheLastOne\");\n break;\n default:\n ADD_FAILURE();\n break;\n }\n }\n}\n\nTEST(cppUriParser, unescape_test)\n{\n const char* url = \"http:\/\/www.example.com\/name%20with%20spaces\/lalala%01%FFg%0D%0A\";\n auto entry = uri_parser::UriParseUrl(url);\n\n auto unescapedString = entry.GetUnescapedUrlString();\n EXPECT_FALSE(unescapedString.empty());\n EXPECT_STREQ(\"http:\/\/www.example.com\/name with spaces\/lalala\\x01\\xffg\\r\\n\", unescapedString.c_str());\n}\n\nTEST(cppUriParser, unescaping_fragment)\n{\n {\n const wchar_t* url = L\"https:\/\/www.google.com\/webhp?lala=la#q=%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82\";\n auto entry = uri_parser::UriParseUrl(url);\n auto frag = entry.GetUnescapedFragment();\n\n EXPECT_TRUE(frag.is_initialized());\n EXPECT_STREQ(frag.get().c_str(), L\"q=\\xd0\\xbf\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82\");\n }\n const char* url = \"https:\/\/www.google.com\/webhp?lala=la#q=%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82\";\n auto entry = uri_parser::UriParseUrl(url);\n auto frag = entry.GetUnescapedFragment();\n\n EXPECT_TRUE(frag.is_initialized());\n EXPECT_STREQ(frag.get().c_str(), \"q=\\xd0\\xbf\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82\");\n}\n\nTEST(cppUriParser, UriTypesMoveTest)\n{\n typedef uri_parser::internal::UriTypes UriTypesChar;\n UriTypesChar uriTypes;\n\n EXPECT_TRUE(uriTypes.freeUriMembers);\n\n std::unique_ptr uriTypesEmpty = std::make_unique(std::move(uriTypes));\n EXPECT_TRUE(uriTypesEmpty->freeUriMembers);\n EXPECT_TRUE(uriTypes.freeUriMembers);\n}disabled types test#include \"cpp_uriparser.h\"\n#include \n#include \n\nusing namespace uri_parser;\n\nTEST(cppUriParser, traversing_through_url)\n{\n\n const char* url = \"http:\/\/www.example.com\/name%20with%20spaces\/lalala\/TheLastOne\";\n\n auto entry = uri_parser::UriParseUrl(url);\n auto pathHead = entry.PathHead();\n\n auto id = 0;\n for (auto pathFragment = std::begin(pathHead); pathFragment != std::end(pathHead); ++pathFragment, ++id)\n {\n switch (id)\n {\n case 0:\n EXPECT_STREQ(pathFragment->c_str(), \"name%20with%20spaces\");\n break;\n case 1:\n EXPECT_STREQ(pathFragment->c_str(), \"lalala\");\n break;\n case 2:\n EXPECT_STREQ(pathFragment->c_str(), \"TheLastOne\");\n break;\n default:\n ADD_FAILURE();\n break;\n }\n }\n}\n\nTEST(cppUriParser, unescape_test)\n{\n const char* url = \"http:\/\/www.example.com\/name%20with%20spaces\/lalala%01%FFg%0D%0A\";\n auto entry = uri_parser::UriParseUrl(url);\n\n auto unescapedString = entry.GetUnescapedUrlString();\n EXPECT_FALSE(unescapedString.empty());\n EXPECT_STREQ(\"http:\/\/www.example.com\/name with spaces\/lalala\\x01\\xffg\\r\\n\", unescapedString.c_str());\n}\n\nTEST(cppUriParser, unescaping_fragment)\n{\n {\n const wchar_t* url = L\"https:\/\/www.google.com\/webhp?lala=la#q=%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82\";\n auto entry = uri_parser::UriParseUrl(url);\n auto frag = entry.GetUnescapedFragment();\n\n EXPECT_TRUE(frag.is_initialized());\n EXPECT_STREQ(frag.get().c_str(), L\"q=\\xd0\\xbf\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82\");\n }\n const char* url = \"https:\/\/www.google.com\/webhp?lala=la#q=%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82\";\n auto entry = uri_parser::UriParseUrl(url);\n auto frag = entry.GetUnescapedFragment();\n\n EXPECT_TRUE(frag.is_initialized());\n EXPECT_STREQ(frag.get().c_str(), \"q=\\xd0\\xbf\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82\");\n}\n\nTEST(cppUriParser, DISABLED_UriTypesMoveTest)\n{\n typedef uri_parser::internal::UriTypes UriTypesChar;\n UriTypesChar uriTypes;\n \/*\n EXPECT_TRUE(uriTypes.freeUriMembers);\n\n std::unique_ptr uriTypesEmpty = std::make_unique(std::move(uriTypes));\n EXPECT_TRUE(uriTypesEmpty->freeUriMembers);\n EXPECT_TRUE(uriTypes.freeUriMembers);\n *\/\n}<|endoftext|>"} {"text":"#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"plotwidget.h\"\n#include \"signalhandler.h\"\n#include \"signaldata.h\"\n#include \"selectsignaldialog.h\"\n#include \"signaldescription.h\"\n#include \"lcmthread.h\"\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 \"qjson.h\"\n\n#include \"ctkPythonConsole.h\"\n#include \"ctkAbstractPythonManager.h\"\n#include \"pythonsignalhandler.h\"\n#include \"pythonchannelsubscribercollection.h\"\n\n\n#include \n#include \n\n\nclass MainWindow::Internal : public Ui::MainWindow\n{\npublic:\n\n};\n\n\nMainWindow::MainWindow(QWidget* parent): QMainWindow(parent)\n{\n mInternal = new Internal;\n mInternal->setupUi(this);\n\n mPlaying = false;\n this->setWindowTitle(\"Signal Scope\");\n\n mLCMThread = new LCMThread;\n mLCMThread->start();\n\n this->initPython();\n\n\n mScrollArea = new QScrollArea;\n mPlotArea = new QWidget;\n mPlotLayout = new QVBoxLayout(mPlotArea);\n\n mScrollArea->setWidget(mPlotArea);\n mScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n mScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n mScrollArea->setWidgetResizable(true);\n this->setCentralWidget(mScrollArea);\n\n mInternal->ActionOpen->setIcon(qApp->style()->standardIcon(QStyle::SP_DialogOpenButton));\n mInternal->ActionSave->setIcon(qApp->style()->standardIcon(QStyle::SP_DialogSaveButton));\n mInternal->ActionPause->setIcon(qApp->style()->standardIcon(QStyle::SP_MediaPlay));\n mInternal->ActionClearHistory->setIcon(qApp->style()->standardIcon(QStyle::SP_TrashIcon));\n mInternal->ActionAddPlot->setIcon(qApp->style()->standardIcon(QStyle::SP_TrashIcon));\n \/\/QStyle::SP_DialogDiscardButton\n\n this->connect(mInternal->ActionQuit, SIGNAL(triggered()), SLOT(close()));\n this->connect(mInternal->ActionOpen, SIGNAL(triggered()), SLOT(onOpenSettings()));\n this->connect(mInternal->ActionSave, SIGNAL(triggered()), SLOT(onSaveSettings()));\n this->connect(mInternal->ActionPause, SIGNAL(triggered()), SLOT(onTogglePause()));\n this->connect(mInternal->ActionAddPlot, SIGNAL(triggered()), SLOT(onNewPlotClicked()));\n this->connect(mInternal->ActionClearHistory, SIGNAL(triggered()), SLOT(onClearHistory()));\n\n this->connect(mInternal->ActionBackgroundColor, SIGNAL(triggered()), SLOT(onChooseBackgroundColor()));\n\n mInternal->toolBar->addSeparator();\n mInternal->toolBar->addWidget(new QLabel(\" Style: \"));\n\n QComboBox* curveStyleCombo = new QComboBox(this);\n curveStyleCombo->addItem(\"points\");\n curveStyleCombo->addItem(\"lines\");\n mInternal->toolBar->addWidget(curveStyleCombo);\n\n mInternal->toolBar->addWidget(new QLabel(\" Point size: \"));\n\n QSpinBox* pointSizeSpin = new QSpinBox(this);\n pointSizeSpin->setMinimum(1);\n pointSizeSpin->setMaximum(20);\n pointSizeSpin->setSingleStep(1);\n pointSizeSpin->setValue(1);\n mInternal->toolBar->addWidget(pointSizeSpin);\n\n this->connect(curveStyleCombo, SIGNAL(currentIndexChanged(const QString&)), SLOT(onCurveStyleChanged(QString)));\n this->connect(pointSizeSpin, SIGNAL(valueChanged(int)), SLOT(onPointSizeChanged(int)));\n\n mRedrawTimer = new QTimer(this);\n \/\/mRedrawTimer->setSingleShot(true);\n this->connect(mRedrawTimer, SIGNAL(timeout()), this, SLOT(onRedrawPlots()));\n\n QShortcut* showConsole = new QShortcut(QKeySequence(\"F8\"), this);\n this->connect(showConsole, SIGNAL(activated()), this->mConsole, SLOT(show()));\n\n this->connect(new QShortcut(QKeySequence(\"Ctrl+W\"), this->mConsole), SIGNAL(activated()), this->mConsole, SLOT(close()));\n\n QString closeShortcut = \"Ctrl+D\";\n #ifdef Q_OS_DARWIN\n closeShortcut = \"Meta+D\";\n #endif\n this->connect(new QShortcut(QKeySequence(closeShortcut), this->mConsole), SIGNAL(activated()), this->mConsole, SLOT(close()));\n\n this->resize(1024,800);\n this->handleCommandLineArgs();\n\n this->onTogglePause();\n\n \/\/this->testPythonSignals();\n}\n\nMainWindow::~MainWindow()\n{\n\n QString settingsFile = QDir::homePath() + \"\/.signal_scope.json\";\n this->saveSettings(settingsFile);\n\n mLCMThread->stop();\n mLCMThread->wait(250);\n delete mLCMThread;\n\n delete mInternal;\n}\n\nvoid MainWindow::handleCommandLineArgs()\n{\n QStringList args = QApplication::instance()->arguments();\n\n if (args.length() > 1)\n {\n QString filename = args[1];\n this->loadSettings(filename);\n }\n else\n {\n QString settingsFile = QDir::homePath() + \"\/.signal_scope.json\";\n if (QFileInfo(settingsFile).exists())\n {\n this->loadSettings(settingsFile);\n }\n }\n}\n\nvoid MainWindow::testPythonSignals()\n{\n this->onRemoveAllPlots();\n PlotWidget* plot = this->addPlot();\n\n QString testFile = QString(getenv(\"DRC_BASE\")) + \"\/software\/motion_estimate\/signal_scope\/src\/signal_scope\/userSignals.py\";\n this->loadPythonSignals(plot, testFile);\n}\n\nvoid MainWindow::initPython()\n{\n this->mPythonManager = new ctkAbstractPythonManager(this);\n this->mConsole = new ctkPythonConsole(this);\n this->mConsole->setWindowFlags(Qt::Dialog);\n this->mConsole->initialize(this->mPythonManager);\n this->mConsole->setAttribute(Qt::WA_QuitOnClose, true);\n this->mConsole->resize(600, 280);\n this->mConsole->setProperty(\"isInteractive\", true);\n this->mPythonManager->addObjectToPythonMain(\"_console\", this->mConsole);\n\n this->mPythonManager->executeFile(QString(getenv(\"DRC_BASE\")) + \"\/software\/motion_estimate\/signal_scope\/src\/signal_scope\/signalScopeSetup.py\");\n PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();\n PythonQtObjectPtr decodeCallback = PythonQt::self()->getVariable(mainContext, \"decodeMessageFunction\");\n\n this->mSubscribers = new PythonChannelSubscriberCollection(mLCMThread, decodeCallback, this);\n}\n\nvoid MainWindow::loadPythonSignals(PlotWidget* plot, const QString& filename)\n{\n this->mPythonManager->executeFile(filename);\n PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();\n QList signalsMap = PythonQt::self()->getVariable(mainContext, \"signals\").toList();\n foreach (const QVariant& signalItem, signalsMap)\n {\n QList signalItemList = signalItem.toList();\n QString channel = signalItemList[0].toString();\n PythonQtObjectPtr callback = signalItemList[1].value();\n\n SignalDescription signalDescription;\n signalDescription.mChannel = channel;\n PythonSignalHandler* signalHandler = new PythonSignalHandler(&signalDescription, callback);\n plot->addSignal(signalHandler);\n }\n}\n\nvoid MainWindow::onCurveStyleChanged(QString style)\n{\n QwtPlotCurve::CurveStyle curveStyle = style == \"lines\" ? QwtPlotCurve::Lines : QwtPlotCurve::Dots;\n\n foreach (PlotWidget* plot, mPlots)\n {\n plot->setCurveStyle(curveStyle);\n }\n}\n\n\nvoid MainWindow::onPointSizeChanged(int pointSize)\n{\n foreach (PlotWidget* plot, mPlots)\n {\n plot->setPointSize(pointSize - 1);\n }\n}\n\nvoid MainWindow::onClearHistory()\n{\n foreach (PlotWidget* plot, mPlots)\n {\n plot->clearHistory();\n }\n}\n\nQString MainWindow::defaultSettingsDir()\n{\n QString configDir = qgetenv(\"DRC_BASE\") + \"\/software\/config\/signal_scope_configs\";\n if (QDir(configDir).exists())\n {\n return QDir(configDir).canonicalPath();\n }\n else\n {\n return QDir::currentPath();\n }\n}\n\nvoid MainWindow::onChooseBackgroundColor()\n{\n QStringList colors;\n colors << \"Black\" << \"White\";\n\n bool ok;\n QString color = QInputDialog::getItem(this, \"Choose background color\", \"Color\", colors, 0, false, &ok);\n if (ok)\n {\n this->setPlotBackgroundColor(color);\n }\n}\n\nvoid MainWindow::onChoosePointSize()\n{\n bool ok;\n int pointSize = QInputDialog::getInt(this, \"Choose point size\", \"Point size\", 1, 1, 20, 1, &ok);\n if (ok)\n {\n foreach (PlotWidget* plot, mPlots)\n {\n plot->setPointSize(pointSize - 1);\n }\n }\n}\n\nvoid MainWindow::setPlotBackgroundColor(QString color)\n{\n foreach (PlotWidget* plot, mPlots)\n {\n plot->setBackgroundColor(color);\n }\n}\n\nvoid MainWindow::onSyncXAxis(double x0, double x1)\n{\n foreach (PlotWidget* plot, mPlots)\n {\n if (plot == this->sender())\n continue;\n\n plot->setXAxisScale(x0, x1);\n plot->replot();\n }\n}\n\nvoid MainWindow::onRedrawPlots()\n{\n mFPSCounter.update();\n \/\/printf(\"redraw fps: %f\\n\", this->mFPSCounter.averageFPS());\n\n if (mPlots.isEmpty())\n {\n return;\n }\n\n QList signalDataList;\n foreach (PlotWidget* plot, mPlots)\n {\n foreach (SignalHandler* signalHandler, plot->signalHandlers())\n {\n signalDataList.append(signalHandler->signalData());\n }\n }\n\n if (signalDataList.isEmpty())\n {\n return;\n }\n\n double maxTime = -std::numeric_limits::max();\n\n foreach (SignalData* signalData, signalDataList)\n {\n signalData->updateValues();\n double signalMaxTime = signalData->lastSampleTime();\n\n if (signalMaxTime > maxTime)\n {\n maxTime = signalMaxTime;\n }\n }\n\n if (maxTime == -std::numeric_limits::max())\n {\n return;\n }\n\n foreach (PlotWidget* plot, mPlots)\n {\n \/\/plot->setEndTime(maxTime + (plot->timeWindow()\/2.0) );\n plot->setEndTime(maxTime);\n plot->replot();\n }\n}\n\nvoid MainWindow::onOpenSettings()\n{\n QString filter = \"JSON (*.json)\";\n QString filename = QFileDialog::getOpenFileName(this, \"Open Settings\", this->defaultSettingsDir(), filter);\n if (filename.length())\n {\n this->onRemoveAllPlots();\n this->loadSettings(filename);\n }\n}\n\nvoid MainWindow::onSaveSettings()\n{\n QString defaultFile = mLastOpenFile.isEmpty() ? this->defaultSettingsDir() : mLastOpenFile;\n QString filter = \"JSON (*.json)\";\n QString filename = QFileDialog::getSaveFileName(this, \"Save Settings\", defaultFile, filter);\n if (filename.length())\n {\n this->saveSettings(filename);\n }\n}\n\nvoid MainWindow::saveSettings(const QString& filename)\n{\n QMap settings;\n\n settings[\"windowWidth\"] = this->width();\n settings[\"windowHeight\"] = this->height();\n\n QList plotSettings;\n foreach (PlotWidget* plot, mPlots)\n {\n plotSettings.append(plot->saveSettings());\n }\n\n settings[\"plots\"] = plotSettings;\n\n Json::encodeFile(filename, settings);\n}\n\nvoid MainWindow::loadSettings(const QString& filename)\n{\n QMap settings = Json::decodeFile(filename);\n this->loadSettings(settings);\n}\n\nvoid MainWindow::loadSettings(const QMap& settings)\n{\n QList plots = settings.value(\"plots\").toList();\n foreach (const QVariant& plot, plots)\n {\n PlotWidget* plotWidget = this->addPlot();\n QMap plotSettings = plot.toMap();\n plotWidget->loadSettings(plotSettings);\n\n QString pythonFile = plotSettings.value(\"pythonScript\").toString();\n if (pythonFile.length())\n {\n pythonFile = QString(getenv(\"DRC_BASE\")) + \"\/\" + pythonFile;\n this->loadPythonSignals(plotWidget, pythonFile);\n }\n }\n\n int windowWidth = settings.value(\"windowWidth\", 1024).toInt();\n int windowHeight = settings.value(\"windowHeight\", 800).toInt();\n this->resize(windowWidth, windowHeight);\n}\n\nvoid MainWindow::onTogglePause()\n{\n mPlaying = !mPlaying;\n mInternal->ActionPause->setChecked(mPlaying);\n mInternal->ActionPause->setIcon(qApp->style()->standardIcon(mPlaying ? QStyle::SP_MediaPause : QStyle::SP_MediaPlay));\n mInternal->ActionPause->setText(mPlaying ? \"Pause\" : \"Play\");\n\n\n foreach (PlotWidget* plot, mPlots)\n {\n if (mPlaying)\n plot->start();\n else\n plot->stop();\n }\n\n if (mPlaying)\n {\n mRedrawTimer->start(33);\n }\n else\n {\n mRedrawTimer->stop();\n }\n}\n\nQList MainWindow::getSignalSelectionFromUser()\n{\n SelectSignalDialog dialog(this);\n int result = dialog.exec();\n if (result != QDialog::Accepted)\n {\n return QList();\n }\n\n return dialog.createSignalHandlers();\n}\n\nvoid MainWindow::onNewPlotClicked()\n{\n QList signalHandlers = this->getSignalSelectionFromUser();\n if (signalHandlers.isEmpty())\n {\n return;\n }\n\n PlotWidget* plot = this->addPlot();\n foreach (SignalHandler* signalHandler, signalHandlers)\n {\n plot->addSignal(signalHandler);\n }\n}\n\nPlotWidget* MainWindow::addPlot()\n{\n PlotWidget* plot = new PlotWidget(mSubscribers);\n mPlotLayout->addWidget(plot);\n this->connect(plot, SIGNAL(removePlotRequested(PlotWidget*)), SLOT(onRemovePlot(PlotWidget*)));\n this->connect(plot, SIGNAL(addSignalRequested(PlotWidget*)), SLOT(onAddSignalToPlot(PlotWidget*)));\n this->connect(plot, SIGNAL(syncXAxisScale(double, double)), SLOT(onSyncXAxis(double, double)));\n mPlots.append(plot);\n\n if (mPlaying)\n plot->start();\n else\n plot->stop();\n\n return plot;\n}\n\nvoid MainWindow::onAddSignalToPlot(PlotWidget* plot)\n{\n if (!plot)\n {\n return;\n }\n\n QList signalHandlers = this->getSignalSelectionFromUser();\n if (signalHandlers.isEmpty())\n {\n return;\n }\n\n foreach (SignalHandler* signalHandler, signalHandlers)\n {\n plot->addSignal(signalHandler);\n }\n}\n\nvoid MainWindow::onRemoveAllPlots()\n{\n QList plots = mPlots;\n foreach(PlotWidget* plot, plots)\n {\n this->onRemovePlot(plot);\n }\n}\n\nvoid MainWindow::onRemovePlot(PlotWidget* plot)\n{\n if (!plot)\n {\n return;\n }\n\n mPlotLayout->removeWidget(plot);\n mPlots.removeAll(plot);\n delete plot;\n}\navoid flicker when moving plots in play mode#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"plotwidget.h\"\n#include \"signalhandler.h\"\n#include \"signaldata.h\"\n#include \"selectsignaldialog.h\"\n#include \"signaldescription.h\"\n#include \"lcmthread.h\"\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 \"qjson.h\"\n\n#include \"ctkPythonConsole.h\"\n#include \"ctkAbstractPythonManager.h\"\n#include \"pythonsignalhandler.h\"\n#include \"pythonchannelsubscribercollection.h\"\n\n\n#include \n#include \n\n\nclass MainWindow::Internal : public Ui::MainWindow\n{\npublic:\n\n};\n\n\nMainWindow::MainWindow(QWidget* parent): QMainWindow(parent)\n{\n mInternal = new Internal;\n mInternal->setupUi(this);\n\n mPlaying = false;\n this->setWindowTitle(\"Signal Scope\");\n\n mLCMThread = new LCMThread;\n mLCMThread->start();\n\n this->initPython();\n\n\n mScrollArea = new QScrollArea;\n mPlotArea = new QWidget;\n mPlotLayout = new QVBoxLayout(mPlotArea);\n\n mScrollArea->setWidget(mPlotArea);\n mScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n mScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n mScrollArea->setWidgetResizable(true);\n this->setCentralWidget(mScrollArea);\n\n mInternal->ActionOpen->setIcon(qApp->style()->standardIcon(QStyle::SP_DialogOpenButton));\n mInternal->ActionSave->setIcon(qApp->style()->standardIcon(QStyle::SP_DialogSaveButton));\n mInternal->ActionPause->setIcon(qApp->style()->standardIcon(QStyle::SP_MediaPlay));\n mInternal->ActionClearHistory->setIcon(qApp->style()->standardIcon(QStyle::SP_TrashIcon));\n mInternal->ActionAddPlot->setIcon(qApp->style()->standardIcon(QStyle::SP_TrashIcon));\n \/\/QStyle::SP_DialogDiscardButton\n\n this->connect(mInternal->ActionQuit, SIGNAL(triggered()), SLOT(close()));\n this->connect(mInternal->ActionOpen, SIGNAL(triggered()), SLOT(onOpenSettings()));\n this->connect(mInternal->ActionSave, SIGNAL(triggered()), SLOT(onSaveSettings()));\n this->connect(mInternal->ActionPause, SIGNAL(triggered()), SLOT(onTogglePause()));\n this->connect(mInternal->ActionAddPlot, SIGNAL(triggered()), SLOT(onNewPlotClicked()));\n this->connect(mInternal->ActionClearHistory, SIGNAL(triggered()), SLOT(onClearHistory()));\n\n this->connect(mInternal->ActionBackgroundColor, SIGNAL(triggered()), SLOT(onChooseBackgroundColor()));\n\n mInternal->toolBar->addSeparator();\n mInternal->toolBar->addWidget(new QLabel(\" Style: \"));\n\n QComboBox* curveStyleCombo = new QComboBox(this);\n curveStyleCombo->addItem(\"points\");\n curveStyleCombo->addItem(\"lines\");\n mInternal->toolBar->addWidget(curveStyleCombo);\n\n mInternal->toolBar->addWidget(new QLabel(\" Point size: \"));\n\n QSpinBox* pointSizeSpin = new QSpinBox(this);\n pointSizeSpin->setMinimum(1);\n pointSizeSpin->setMaximum(20);\n pointSizeSpin->setSingleStep(1);\n pointSizeSpin->setValue(1);\n mInternal->toolBar->addWidget(pointSizeSpin);\n\n this->connect(curveStyleCombo, SIGNAL(currentIndexChanged(const QString&)), SLOT(onCurveStyleChanged(QString)));\n this->connect(pointSizeSpin, SIGNAL(valueChanged(int)), SLOT(onPointSizeChanged(int)));\n\n mRedrawTimer = new QTimer(this);\n \/\/mRedrawTimer->setSingleShot(true);\n this->connect(mRedrawTimer, SIGNAL(timeout()), this, SLOT(onRedrawPlots()));\n\n QShortcut* showConsole = new QShortcut(QKeySequence(\"F8\"), this);\n this->connect(showConsole, SIGNAL(activated()), this->mConsole, SLOT(show()));\n\n this->connect(new QShortcut(QKeySequence(\"Ctrl+W\"), this->mConsole), SIGNAL(activated()), this->mConsole, SLOT(close()));\n\n QString closeShortcut = \"Ctrl+D\";\n #ifdef Q_OS_DARWIN\n closeShortcut = \"Meta+D\";\n #endif\n this->connect(new QShortcut(QKeySequence(closeShortcut), this->mConsole), SIGNAL(activated()), this->mConsole, SLOT(close()));\n\n this->resize(1024,800);\n this->handleCommandLineArgs();\n\n this->onTogglePause();\n\n \/\/this->testPythonSignals();\n}\n\nMainWindow::~MainWindow()\n{\n\n QString settingsFile = QDir::homePath() + \"\/.signal_scope.json\";\n this->saveSettings(settingsFile);\n\n mLCMThread->stop();\n mLCMThread->wait(250);\n delete mLCMThread;\n\n delete mInternal;\n}\n\nvoid MainWindow::handleCommandLineArgs()\n{\n QStringList args = QApplication::instance()->arguments();\n\n if (args.length() > 1)\n {\n QString filename = args[1];\n this->loadSettings(filename);\n }\n else\n {\n QString settingsFile = QDir::homePath() + \"\/.signal_scope.json\";\n if (QFileInfo(settingsFile).exists())\n {\n this->loadSettings(settingsFile);\n }\n }\n}\n\nvoid MainWindow::testPythonSignals()\n{\n this->onRemoveAllPlots();\n PlotWidget* plot = this->addPlot();\n\n QString testFile = QString(getenv(\"DRC_BASE\")) + \"\/software\/motion_estimate\/signal_scope\/src\/signal_scope\/userSignals.py\";\n this->loadPythonSignals(plot, testFile);\n}\n\nvoid MainWindow::initPython()\n{\n this->mPythonManager = new ctkAbstractPythonManager(this);\n this->mConsole = new ctkPythonConsole(this);\n this->mConsole->setWindowFlags(Qt::Dialog);\n this->mConsole->initialize(this->mPythonManager);\n this->mConsole->setAttribute(Qt::WA_QuitOnClose, true);\n this->mConsole->resize(600, 280);\n this->mConsole->setProperty(\"isInteractive\", true);\n this->mPythonManager->addObjectToPythonMain(\"_console\", this->mConsole);\n\n this->mPythonManager->executeFile(QString(getenv(\"DRC_BASE\")) + \"\/software\/motion_estimate\/signal_scope\/src\/signal_scope\/signalScopeSetup.py\");\n PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();\n PythonQtObjectPtr decodeCallback = PythonQt::self()->getVariable(mainContext, \"decodeMessageFunction\");\n\n this->mSubscribers = new PythonChannelSubscriberCollection(mLCMThread, decodeCallback, this);\n}\n\nvoid MainWindow::loadPythonSignals(PlotWidget* plot, const QString& filename)\n{\n this->mPythonManager->executeFile(filename);\n PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();\n QList signalsMap = PythonQt::self()->getVariable(mainContext, \"signals\").toList();\n foreach (const QVariant& signalItem, signalsMap)\n {\n QList signalItemList = signalItem.toList();\n QString channel = signalItemList[0].toString();\n PythonQtObjectPtr callback = signalItemList[1].value();\n\n SignalDescription signalDescription;\n signalDescription.mChannel = channel;\n PythonSignalHandler* signalHandler = new PythonSignalHandler(&signalDescription, callback);\n plot->addSignal(signalHandler);\n }\n}\n\nvoid MainWindow::onCurveStyleChanged(QString style)\n{\n QwtPlotCurve::CurveStyle curveStyle = style == \"lines\" ? QwtPlotCurve::Lines : QwtPlotCurve::Dots;\n\n foreach (PlotWidget* plot, mPlots)\n {\n plot->setCurveStyle(curveStyle);\n }\n}\n\n\nvoid MainWindow::onPointSizeChanged(int pointSize)\n{\n foreach (PlotWidget* plot, mPlots)\n {\n plot->setPointSize(pointSize - 1);\n }\n}\n\nvoid MainWindow::onClearHistory()\n{\n foreach (PlotWidget* plot, mPlots)\n {\n plot->clearHistory();\n }\n}\n\nQString MainWindow::defaultSettingsDir()\n{\n QString configDir = qgetenv(\"DRC_BASE\") + \"\/software\/config\/signal_scope_configs\";\n if (QDir(configDir).exists())\n {\n return QDir(configDir).canonicalPath();\n }\n else\n {\n return QDir::currentPath();\n }\n}\n\nvoid MainWindow::onChooseBackgroundColor()\n{\n QStringList colors;\n colors << \"Black\" << \"White\";\n\n bool ok;\n QString color = QInputDialog::getItem(this, \"Choose background color\", \"Color\", colors, 0, false, &ok);\n if (ok)\n {\n this->setPlotBackgroundColor(color);\n }\n}\n\nvoid MainWindow::onChoosePointSize()\n{\n bool ok;\n int pointSize = QInputDialog::getInt(this, \"Choose point size\", \"Point size\", 1, 1, 20, 1, &ok);\n if (ok)\n {\n foreach (PlotWidget* plot, mPlots)\n {\n plot->setPointSize(pointSize - 1);\n }\n }\n}\n\nvoid MainWindow::setPlotBackgroundColor(QString color)\n{\n foreach (PlotWidget* plot, mPlots)\n {\n plot->setBackgroundColor(color);\n }\n}\n\nvoid MainWindow::onSyncXAxis(double x0, double x1)\n{\n if (mPlaying)\n return;\n\n foreach (PlotWidget* plot, mPlots)\n {\n if (plot == this->sender())\n continue;\n\n plot->setXAxisScale(x0, x1);\n plot->replot();\n }\n}\n\nvoid MainWindow::onRedrawPlots()\n{\n mFPSCounter.update();\n \/\/printf(\"redraw fps: %f\\n\", this->mFPSCounter.averageFPS());\n\n if (mPlots.isEmpty())\n {\n return;\n }\n\n QList signalDataList;\n foreach (PlotWidget* plot, mPlots)\n {\n foreach (SignalHandler* signalHandler, plot->signalHandlers())\n {\n signalDataList.append(signalHandler->signalData());\n }\n }\n\n if (signalDataList.isEmpty())\n {\n return;\n }\n\n double maxTime = -std::numeric_limits::max();\n\n foreach (SignalData* signalData, signalDataList)\n {\n signalData->updateValues();\n double signalMaxTime = signalData->lastSampleTime();\n\n if (signalMaxTime > maxTime)\n {\n maxTime = signalMaxTime;\n }\n }\n\n if (maxTime == -std::numeric_limits::max())\n {\n return;\n }\n\n foreach (PlotWidget* plot, mPlots)\n {\n \/\/plot->setEndTime(maxTime + (plot->timeWindow()\/2.0) );\n plot->setEndTime(maxTime);\n plot->replot();\n }\n}\n\nvoid MainWindow::onOpenSettings()\n{\n QString filter = \"JSON (*.json)\";\n QString filename = QFileDialog::getOpenFileName(this, \"Open Settings\", this->defaultSettingsDir(), filter);\n if (filename.length())\n {\n this->onRemoveAllPlots();\n this->loadSettings(filename);\n }\n}\n\nvoid MainWindow::onSaveSettings()\n{\n QString defaultFile = mLastOpenFile.isEmpty() ? this->defaultSettingsDir() : mLastOpenFile;\n QString filter = \"JSON (*.json)\";\n QString filename = QFileDialog::getSaveFileName(this, \"Save Settings\", defaultFile, filter);\n if (filename.length())\n {\n this->saveSettings(filename);\n }\n}\n\nvoid MainWindow::saveSettings(const QString& filename)\n{\n QMap settings;\n\n settings[\"windowWidth\"] = this->width();\n settings[\"windowHeight\"] = this->height();\n\n QList plotSettings;\n foreach (PlotWidget* plot, mPlots)\n {\n plotSettings.append(plot->saveSettings());\n }\n\n settings[\"plots\"] = plotSettings;\n\n Json::encodeFile(filename, settings);\n}\n\nvoid MainWindow::loadSettings(const QString& filename)\n{\n QMap settings = Json::decodeFile(filename);\n this->loadSettings(settings);\n}\n\nvoid MainWindow::loadSettings(const QMap& settings)\n{\n QList plots = settings.value(\"plots\").toList();\n foreach (const QVariant& plot, plots)\n {\n PlotWidget* plotWidget = this->addPlot();\n QMap plotSettings = plot.toMap();\n plotWidget->loadSettings(plotSettings);\n\n QString pythonFile = plotSettings.value(\"pythonScript\").toString();\n if (pythonFile.length())\n {\n pythonFile = QString(getenv(\"DRC_BASE\")) + \"\/\" + pythonFile;\n this->loadPythonSignals(plotWidget, pythonFile);\n }\n }\n\n int windowWidth = settings.value(\"windowWidth\", 1024).toInt();\n int windowHeight = settings.value(\"windowHeight\", 800).toInt();\n this->resize(windowWidth, windowHeight);\n}\n\nvoid MainWindow::onTogglePause()\n{\n mPlaying = !mPlaying;\n mInternal->ActionPause->setChecked(mPlaying);\n mInternal->ActionPause->setIcon(qApp->style()->standardIcon(mPlaying ? QStyle::SP_MediaPause : QStyle::SP_MediaPlay));\n mInternal->ActionPause->setText(mPlaying ? \"Pause\" : \"Play\");\n\n\n foreach (PlotWidget* plot, mPlots)\n {\n if (mPlaying)\n plot->start();\n else\n plot->stop();\n }\n\n if (mPlaying)\n {\n mRedrawTimer->start(33);\n }\n else\n {\n mRedrawTimer->stop();\n }\n}\n\nQList MainWindow::getSignalSelectionFromUser()\n{\n SelectSignalDialog dialog(this);\n int result = dialog.exec();\n if (result != QDialog::Accepted)\n {\n return QList();\n }\n\n return dialog.createSignalHandlers();\n}\n\nvoid MainWindow::onNewPlotClicked()\n{\n QList signalHandlers = this->getSignalSelectionFromUser();\n if (signalHandlers.isEmpty())\n {\n return;\n }\n\n PlotWidget* plot = this->addPlot();\n foreach (SignalHandler* signalHandler, signalHandlers)\n {\n plot->addSignal(signalHandler);\n }\n}\n\nPlotWidget* MainWindow::addPlot()\n{\n PlotWidget* plot = new PlotWidget(mSubscribers);\n mPlotLayout->addWidget(plot);\n this->connect(plot, SIGNAL(removePlotRequested(PlotWidget*)), SLOT(onRemovePlot(PlotWidget*)));\n this->connect(plot, SIGNAL(addSignalRequested(PlotWidget*)), SLOT(onAddSignalToPlot(PlotWidget*)));\n this->connect(plot, SIGNAL(syncXAxisScale(double, double)), SLOT(onSyncXAxis(double, double)));\n mPlots.append(plot);\n\n if (mPlaying)\n plot->start();\n else\n plot->stop();\n\n return plot;\n}\n\nvoid MainWindow::onAddSignalToPlot(PlotWidget* plot)\n{\n if (!plot)\n {\n return;\n }\n\n QList signalHandlers = this->getSignalSelectionFromUser();\n if (signalHandlers.isEmpty())\n {\n return;\n }\n\n foreach (SignalHandler* signalHandler, signalHandlers)\n {\n plot->addSignal(signalHandler);\n }\n}\n\nvoid MainWindow::onRemoveAllPlots()\n{\n QList plots = mPlots;\n foreach(PlotWidget* plot, plots)\n {\n this->onRemovePlot(plot);\n }\n}\n\nvoid MainWindow::onRemovePlot(PlotWidget* plot)\n{\n if (!plot)\n {\n return;\n }\n\n mPlotLayout->removeWidget(plot);\n mPlots.removeAll(plot);\n delete plot;\n}\n<|endoftext|>"} {"text":"reverse linkedlist<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n#include \n#include \/\/ dgemv, dgesvd\n#include \/\/ DenseMatrixView\n#include \/\/ make_unique\n#include \/\/ SVD\n\nnamespace AnyODE {\n\n template , typename Decomp_t=SVD>\n struct OdeSysIterativeBase : public OdeSysBase {\n int m_njacvec_dot=0, m_nprec_setup=0, m_nprec_solve=0;\n std::unique_ptr m_jac_cache {nullptr};\n std::unique_ptr m_prec_cache {nullptr};\n bool m_update_prec_cache = false;\n Real_t m_old_gamma;\n\n virtual Status jac_times_vec(const Real_t * const __restrict__ vec,\n Real_t * const __restrict__ out,\n Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy\n ) override\n {\n \/\/ See \"Jacobian information (matrix-vector product)\"\n \/\/ (4.6.8 in cvs_guide.pdf for sundials 2.7.0)\n auto status = AnyODE::Status::success;\n const int ny = this->get_ny();\n if (m_jac_cache == nullptr){\n m_jac_cache = make_unique(nullptr, ny, ny, ny, true);\n status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);\n }\n m_jac_cache->dot_vec(vec, out);\n m_njacvec_dot++;\n return status;\n }\n\n virtual Status prec_setup(Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy,\n bool jac_ok,\n bool& jac_recomputed,\n Real_t gamma) override\n {\n const int ny = this->get_ny();\n auto status = AnyODE::Status::success;\n ignore(gamma);\n \/\/ See \"Preconditioning (Jacobian data)\" in cvs_guide.pdf (4.6.10 for 2.7.0)\n if (m_jac_cache == nullptr)\n m_jac_cache = make_unique(nullptr, ny, ny, ny, true);\n\n if (jac_ok){\n jac_recomputed = false;\n } else {\n status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);\n m_update_prec_cache = true;\n jac_recomputed = true;\n }\n m_nprec_setup++;\n return status;\n }\n\n virtual Status prec_solve_left(const Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy,\n const Real_t * const __restrict__ r,\n Real_t * const __restrict__ z,\n Real_t gamma,\n Real_t delta,\n const Real_t * const __restrict__ ewt\n ) override\n {\n \/\/ See 4.6.9 on page 75 in cvs_guide.pdf (Sundials 2.6.2)\n \/\/ Solves P*z = r, where P ~= I - gamma*J\n ignore(delta);\n const int ny = this->get_ny();\n if (ewt)\n throw std::runtime_error(\"Not implemented.\");\n m_nprec_solve++;\n\n ignore(t); ignore(fy); ignore(y);\n bool recompute = false;\n if (m_prec_cache == nullptr){\n m_prec_cache = make_unique(nullptr, ny, ny, ny, true);\n recompute = true;\n } else {\n if (m_update_prec_cache or (m_old_gamma != gamma))\n recompute = true;\n }\n if (recompute){\n m_old_gamma = gamma;\n m_prec_cache->set_to_eye_plus_scaled_mtx(-gamma, *m_jac_cache);\n }\n int info;\n auto decomp = Decomp_t((JacMat_t*)(m_prec_cache.get()));\n info = decomp.solve(r, z);\n if (info == 0)\n return AnyODE::Status::success;\n return AnyODE::Status::recoverable_error;\n }\n\n\n };\n}\nForgot to rename class#pragma once\n\n#include \n\n#include \n#include \/\/ dgemv, dgesvd\n#include \/\/ DenseMatrix\n#include \/\/ make_unique\n#include \/\/ SVD\n\nnamespace AnyODE {\n\n template , typename Decomp_t=SVD>\n struct OdeSysIterativeBase : public OdeSysBase {\n int m_njacvec_dot=0, m_nprec_setup=0, m_nprec_solve=0;\n std::unique_ptr m_jac_cache {nullptr};\n std::unique_ptr m_prec_cache {nullptr};\n bool m_update_prec_cache = false;\n Real_t m_old_gamma;\n\n virtual Status jac_times_vec(const Real_t * const __restrict__ vec,\n Real_t * const __restrict__ out,\n Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy\n ) override\n {\n \/\/ See \"Jacobian information (matrix-vector product)\"\n \/\/ (4.6.8 in cvs_guide.pdf for sundials 2.7.0)\n auto status = AnyODE::Status::success;\n const int ny = this->get_ny();\n if (m_jac_cache == nullptr){\n m_jac_cache = make_unique(nullptr, ny, ny, ny, true);\n status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);\n }\n m_jac_cache->dot_vec(vec, out);\n m_njacvec_dot++;\n return status;\n }\n\n virtual Status prec_setup(Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy,\n bool jac_ok,\n bool& jac_recomputed,\n Real_t gamma) override\n {\n const int ny = this->get_ny();\n auto status = AnyODE::Status::success;\n ignore(gamma);\n \/\/ See \"Preconditioning (Jacobian data)\" in cvs_guide.pdf (4.6.10 for 2.7.0)\n if (m_jac_cache == nullptr)\n m_jac_cache = make_unique(nullptr, ny, ny, ny, true);\n\n if (jac_ok){\n jac_recomputed = false;\n } else {\n status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);\n m_update_prec_cache = true;\n jac_recomputed = true;\n }\n m_nprec_setup++;\n return status;\n }\n\n virtual Status prec_solve_left(const Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy,\n const Real_t * const __restrict__ r,\n Real_t * const __restrict__ z,\n Real_t gamma,\n Real_t delta,\n const Real_t * const __restrict__ ewt\n ) override\n {\n \/\/ See 4.6.9 on page 75 in cvs_guide.pdf (Sundials 2.6.2)\n \/\/ Solves P*z = r, where P ~= I - gamma*J\n ignore(delta);\n const int ny = this->get_ny();\n if (ewt)\n throw std::runtime_error(\"Not implemented.\");\n m_nprec_solve++;\n\n ignore(t); ignore(fy); ignore(y);\n bool recompute = false;\n if (m_prec_cache == nullptr){\n m_prec_cache = make_unique(nullptr, ny, ny, ny, true);\n recompute = true;\n } else {\n if (m_update_prec_cache or (m_old_gamma != gamma))\n recompute = true;\n }\n if (recompute){\n m_old_gamma = gamma;\n m_prec_cache->set_to_eye_plus_scaled_mtx(-gamma, *m_jac_cache);\n }\n int info;\n auto decomp = Decomp_t((JacMat_t*)(m_prec_cache.get()));\n info = decomp.solve(r, z);\n if (info == 0)\n return AnyODE::Status::success;\n return AnyODE::Status::recoverable_error;\n }\n\n\n };\n}\n<|endoftext|>"} {"text":"#pragma once\n#ifndef OPENGM_MAXIMUM_LIKELIHOOD_LEARNER_HXX\n#define OPENGM_MAXIMUM_LIKELIHOOD_LEARNER_HXX\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef double ValueType;\ntypedef size_t IndexType;\ntypedef size_t LabelType;\ntypedef opengm::meta::TypeListGenerator<\n opengm::ExplicitFunction,\n opengm::functions::learnable::LPotts,\n opengm::functions::learnable::SumOfExperts\n>::type FunctionListType;\n\ntypedef opengm::GraphicalModel<\n ValueType,opengm::Adder,\n FunctionListType,\n opengm::DiscreteSpace\n> GM;\n\ntypedef opengm::ICM INF;\ntypedef opengm::learning::Weights WeightType;\n\nstruct WeightGradientFunctor{\n WeightGradientFunctor(IndexType weight, std::vector::iterator labelVectorBegin)\n : weight_(weight),\n labelVectorBegin_(labelVectorBegin){\n }\n\n template\n void operator()(const F & function ){\n IndexType index=-1;\n for(size_t i=0; i::iterator labelVectorBegin_;\n ValueType result_;\n};\n\nnamespace opengm {\nnamespace learning {\n\ntemplate\nclass MaximumLikelihoodLearner\n{\npublic:\n typedef typename DATASET::GMType GMType;\n typedef typename GMType::ValueType ValueType;\n typedef typename GMType::IndexType IndexType;\n typedef typename GMType::LabelType LabelType;\n typedef typename GMType::FactorType FactorType;\n\n class Weight{\n public:\n std::vector weightUpperbound_;\n std::vector weightLowerbound_;\n std::vector testingPoints_;\n Weight(){;}\n };\n\n\n MaximumLikelihoodLearner(DATASET&, Weight& );\n\n template\n void learn(typename INF::Parameter& weight);\n\n const opengm::learning::Weights& getModelWeights(){return modelWeights_;}\n Weight& getLerningWeights(){return weight_;}\n\nprivate:\n DATASET& dataset_;\n opengm::learning::Weights modelWeights_;\n Weight weight_;\n};\n\ntemplate\nMaximumLikelihoodLearner::MaximumLikelihoodLearner(DATASET& ds, Weight& w )\n : dataset_(ds), weight_(w)\n{\n modelWeights_ = opengm::learning::Weights(ds.getNumberOfWeights());\n if(weight_.weightUpperbound_.size() != ds.getNumberOfWeights())\n weight_.weightUpperbound_.resize(ds.getNumberOfWeights(),10.0);\n if(weight_.weightLowerbound_.size() != ds.getNumberOfWeights())\n weight_.weightLowerbound_.resize(ds.getNumberOfWeights(),0.0);\n if(weight_.testingPoints_.size() != ds.getNumberOfWeights())\n weight_.testingPoints_.resize(ds.getNumberOfWeights(),10);\n}\n\n\ntemplate\ntemplate\nvoid MaximumLikelihoodLearner::learn(typename INF::Parameter& weight){\n\n opengm::learning::Weights modelWeight( dataset_.getNumberOfWeights() );\n opengm::learning::Weights bestModelWeight( dataset_.getNumberOfWeights() );\n double bestLoss = 100000000.0;\n std::vector point(dataset_.getNumberOfWeights(),0);\n std::vector gradient(dataset_.getNumberOfWeights(),0);\n std::vector Delta(dataset_.getNumberOfWeights(),0);\n for(IndexType p=0; p > w( dataset_.getNumberOfModels(), std::vector ( dataset_.getModel(0).numberOfVariables()) );\n\n \/***********************************************************************************************************\/\n \/\/ construct Ground Truth dependent weights\n \/***********************************************************************************************************\/\n\n for(IndexType m=0; m& gt = dataset_.getGT(m);\n\n for(IndexType v=0; v\" << count << \" \";\n\n \/\/ Get Weights\n for(IndexType p=0; p& mp = dataset_.getWeights();\n mp = modelWeight;\n std::vector< std::vector > confs( dataset_.getNumberOfModels() );\n double loss = 0;\n for(size_t m=0; m& gt = dataset_.getGT(m);\n loss += lossFunction.loss(confs[m].begin(), confs[m].end(), gt.begin(), gt.end());\n }\n\n std::cout << \" eta = \" << eta << \" weights \";\/\/<< std::endl;\n for(IndexType p=0; p FunctionType;\n typedef typename opengm::ViewConvertFunction ViewFunctionType;\n typedef typename GMType::FunctionIdentifier FunctionIdentifierType;\n typedef typename opengm::meta::TypeListGenerator::type FunctionListType;\n typedef opengm::GraphicalModel > GmBpType;\n typedef BeliefPropagationUpdateRules UpdateRules;\n typedef MessagePassing BeliefPropagation;\n\n const IndexType maxNumberOfIterations = 40;\n const double convergenceBound = 1e-7;\n const double damping = 0.5;\n typename BeliefPropagation::Parameter weight(maxNumberOfIterations, convergenceBound, damping);\n\n std::vector< std::vector > b ( dataset_.getNumberOfModels(), std::vector ( dataset_.getModel(0).numberOfFactors()) );\n\n for(IndexType m=0; m ViewFunctionType;\n typedef typename GMType::FunctionIdentifier FunctionIdentifierType;\n FunctionIdentifierType fid = bpModel.addFunction(ViewFunctionType(factor));\n bpModel.addFactor(fid, factor.variableIndicesBegin(), factor.variableIndicesEnd());\n }\n \/***********************************************************************************************************\/\n \/\/ run: Loopy Belief Propagation\n \/***********************************************************************************************************\/\n BeliefPropagation bp(bpModel, weight);\n const std::vector& gt = dataset_.getGT(m);\n bp.infer();\n typename GMType::IndependentFactorType marg;\n for(IndexType f = 0; f indexVector( marg.variableIndicesBegin(), marg.variableIndicesEnd() );\n std::vector labelVector( marg.numberOfVariables());\n for(IndexType v=0; v sum(dataset_.getNumberOfWeights());\n for(IndexType p=0; p >\n piW(dataset_.getNumberOfModels(),\n std::vector ( dataset_.getModel(0).numberOfFactors()));\n\n for(IndexType m=0; m& gt = dataset_.getGT(m);\n ValueType f_x; \/\/ f^{d}_{C;k} ( x^d_C ) J. Kappes p. 64\n\n for(IndexType f=0; f indexVector( factor.variableIndicesBegin(), factor.variableIndicesEnd() );\n std::vector labelVector( factor.numberOfVariables());\n piW[m][f]=1.0;\n\n for(IndexType v=0; v=200 ){\n search = false;\n }else{\n \/\/ Calculate the next point\n ValueType norm2=0.0;\n for(IndexType p=0; p \";\n std::cout << \" loss = \" << bestLoss << \" bestOptFun = \" << bestOptFun << std::endl;\n\n modelWeights_ = bestModelWeight;\n};\n}\n}\n#endif\n\n\nChange in eta.#pragma once\n#ifndef OPENGM_MAXIMUM_LIKELIHOOD_LEARNER_HXX\n#define OPENGM_MAXIMUM_LIKELIHOOD_LEARNER_HXX\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef double ValueType;\ntypedef size_t IndexType;\ntypedef size_t LabelType;\ntypedef opengm::meta::TypeListGenerator<\n opengm::ExplicitFunction,\n opengm::functions::learnable::LPotts,\n opengm::functions::learnable::SumOfExperts\n>::type FunctionListType;\n\ntypedef opengm::GraphicalModel<\n ValueType,opengm::Adder,\n FunctionListType,\n opengm::DiscreteSpace\n> GM;\n\ntypedef opengm::ICM INF;\ntypedef opengm::learning::Weights WeightType;\n\nstruct WeightGradientFunctor{\n WeightGradientFunctor(IndexType weight, std::vector::iterator labelVectorBegin)\n : weight_(weight),\n labelVectorBegin_(labelVectorBegin){\n }\n\n template\n void operator()(const F & function ){\n IndexType index=-1;\n for(size_t i=0; i::iterator labelVectorBegin_;\n ValueType result_;\n};\n\nnamespace opengm {\nnamespace learning {\n\ntemplate\nclass MaximumLikelihoodLearner\n{\npublic:\n typedef typename DATASET::GMType GMType;\n typedef typename GMType::ValueType ValueType;\n typedef typename GMType::IndexType IndexType;\n typedef typename GMType::LabelType LabelType;\n typedef typename GMType::FactorType FactorType;\n\n class Weight{\n public:\n std::vector weightUpperbound_;\n std::vector weightLowerbound_;\n std::vector testingPoints_;\n Weight(){;}\n };\n\n\n MaximumLikelihoodLearner(DATASET&, Weight& );\n\n template\n void learn(typename INF::Parameter& weight);\n\n const opengm::learning::Weights& getModelWeights(){return modelWeights_;}\n Weight& getLerningWeights(){return weight_;}\n\nprivate:\n DATASET& dataset_;\n opengm::learning::Weights modelWeights_;\n Weight weight_;\n};\n\ntemplate\nMaximumLikelihoodLearner::MaximumLikelihoodLearner(DATASET& ds, Weight& w )\n : dataset_(ds), weight_(w)\n{\n modelWeights_ = opengm::learning::Weights(ds.getNumberOfWeights());\n if(weight_.weightUpperbound_.size() != ds.getNumberOfWeights())\n weight_.weightUpperbound_.resize(ds.getNumberOfWeights(),10.0);\n if(weight_.weightLowerbound_.size() != ds.getNumberOfWeights())\n weight_.weightLowerbound_.resize(ds.getNumberOfWeights(),0.0);\n if(weight_.testingPoints_.size() != ds.getNumberOfWeights())\n weight_.testingPoints_.resize(ds.getNumberOfWeights(),10);\n}\n\n\ntemplate\ntemplate\nvoid MaximumLikelihoodLearner::learn(typename INF::Parameter& weight){\n\n opengm::learning::Weights modelWeight( dataset_.getNumberOfWeights() );\n opengm::learning::Weights bestModelWeight( dataset_.getNumberOfWeights() );\n double bestLoss = 100000000.0;\n std::vector point(dataset_.getNumberOfWeights(),0);\n std::vector gradient(dataset_.getNumberOfWeights(),0);\n std::vector Delta(dataset_.getNumberOfWeights(),0);\n for(IndexType p=0; p > w( dataset_.getNumberOfModels(), std::vector ( dataset_.getModel(0).numberOfVariables()) );\n\n \/***********************************************************************************************************\/\n \/\/ construct Ground Truth dependent weights\n \/***********************************************************************************************************\/\n\n for(IndexType m=0; m& gt = dataset_.getGT(m);\n\n for(IndexType v=0; v\" << count << \" \";\n\n \/\/ Get Weights\n for(IndexType p=0; p& mp = dataset_.getWeights();\n mp = modelWeight;\n std::vector< std::vector > confs( dataset_.getNumberOfModels() );\n double loss = 0;\n for(size_t m=0; m& gt = dataset_.getGT(m);\n loss += lossFunction.loss(confs[m].begin(), confs[m].end(), gt.begin(), gt.end());\n }\n\n std::cout << \" eta = \" << eta << \" weights \";\/\/<< std::endl;\n for(IndexType p=0; p FunctionType;\n typedef typename opengm::ViewConvertFunction ViewFunctionType;\n typedef typename GMType::FunctionIdentifier FunctionIdentifierType;\n typedef typename opengm::meta::TypeListGenerator::type FunctionListType;\n typedef opengm::GraphicalModel > GmBpType;\n typedef BeliefPropagationUpdateRules UpdateRules;\n typedef MessagePassing BeliefPropagation;\n\n const IndexType maxNumberOfIterations = 40;\n const double convergenceBound = 1e-7;\n const double damping = 0.5;\n typename BeliefPropagation::Parameter weight(maxNumberOfIterations, convergenceBound, damping);\n\n std::vector< std::vector > b ( dataset_.getNumberOfModels(), std::vector ( dataset_.getModel(0).numberOfFactors()) );\n\n for(IndexType m=0; m ViewFunctionType;\n typedef typename GMType::FunctionIdentifier FunctionIdentifierType;\n FunctionIdentifierType fid = bpModel.addFunction(ViewFunctionType(factor));\n bpModel.addFactor(fid, factor.variableIndicesBegin(), factor.variableIndicesEnd());\n }\n \/***********************************************************************************************************\/\n \/\/ run: Loopy Belief Propagation\n \/***********************************************************************************************************\/\n BeliefPropagation bp(bpModel, weight);\n const std::vector& gt = dataset_.getGT(m);\n bp.infer();\n typename GMType::IndependentFactorType marg;\n for(IndexType f = 0; f indexVector( marg.variableIndicesBegin(), marg.variableIndicesEnd() );\n std::vector labelVector( marg.numberOfVariables());\n for(IndexType v=0; v sum(dataset_.getNumberOfWeights());\n for(IndexType p=0; p >\n piW(dataset_.getNumberOfModels(),\n std::vector ( dataset_.getModel(0).numberOfFactors()));\n\n for(IndexType m=0; m& gt = dataset_.getGT(m);\n ValueType f_x; \/\/ f^{d}_{C;k} ( x^d_C ) J. Kappes p. 64\n\n for(IndexType f=0; f indexVector( factor.variableIndicesBegin(), factor.variableIndicesEnd() );\n std::vector labelVector( factor.numberOfVariables());\n piW[m][f]=1.0;\n\n for(IndexType v=0; v=200 ){\n search = false;\n }else{\n \/\/ Calculate the next point\n ValueType norm2=0.0;\n for(IndexType p=0; p \";\n std::cout << \" loss = \" << bestLoss << \" bestOptFun = \" << bestOptFun << std::endl;\n\n modelWeights_ = bestModelWeight;\n};\n}\n}\n#endif\n\n\n<|endoftext|>"} {"text":"\n#ifndef _config_ctor_hpp\n#define _config_ctor_hpp\n\n#include \n#include \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\/***************************************************************************\/\n\nnamespace construct_config {\nnamespace {\n\n\/\/ for other types (strings)\ntemplate\nstruct get_concrete_value {\n\ttemplate\n\tstatic T get(const char *key, const boost::property_tree::ptree &ini, const char *default_value) {\n\t\treturn default_value != nullptr\n\t\t\t? ini.get(key, default_value)\n\t\t\t: ini.get(key)\n\t\t;\n\t}\n};\n\n\/\/ specialization for arithmetic types\ntemplate<>\nstruct get_concrete_value {\n\ttemplate\n\tstatic T get(const char *key, const boost::property_tree::ptree &ini, const char *default_value) {\n\t\t\/\/ handle bool types\n\t\tif ( std::is_same::value ) {\n\t\t\treturn default_value != nullptr\n\t\t\t\t? ini.get(key, (std::strcmp(default_value, \"true\") == 0))\n\t\t\t\t: ini.get(key)\n\t\t\t;\n\t\t}\n\n\t\t\/\/ handle other arithmetic types\n\t\tstd::string val = default_value != nullptr\n\t\t\t? ini.get(key, default_value)\n\t\t\t: ini.get(key)\n\t\t;\n\t\tif ( val.empty() ) return T{};\n\n\t\tif ( (std::is_signed::value || std::is_unsigned::value) && !std::is_floating_point::value ) {\n\t\t\tstd::size_t mult = 1u;\n\t\t\tswitch ( val.back() ) {\n\t\t\t\tcase 'G': mult *= 1024u;\n\t\t\t\tcase 'M': mult *= 1024u;\n\t\t\t\tcase 'K': mult *= 1024u;\n\n\t\t\t\tval.pop_back();\n\t\t\t}\n\n\t\t\treturn (std::is_signed::value ? std::stol(val) : std::stoul(val));\n\t\t}\n\n\t\treturn std::stod(val);\n\t}\n};\n\n} \/\/ anon ns\n\ntemplate\nstatic T get_value(const char *key, const boost::property_tree::ptree &cfg, const char *default_value) {\n\tusing TT = typename std::remove_cv::type;\n\treturn get_concrete_value::value>::template get(key, cfg, default_value);\n}\n\ntemplate\nstruct print_value {\n\ttemplate\n\tstatic void print(const T &v, std::ostream &os) {\n\t\tos << '\\\"' << v << '\\\"';\n\t}\n};\n\ntemplate<>\nstruct print_value {\n\ttemplate\n\tstatic void print(const T &v, std::ostream &os) {\n\t\tos << std::boolalpha << v;\n\t}\n};\n\n} \/\/ ns construct_config\n\n\/***************************************************************************\/\n\n#define _CONSTRUCT_CONFIG__WRAP_SEQUENCE_X(...) \\\n\t((__VA_ARGS__)) _CONSTRUCT_CONFIG__WRAP_SEQUENCE_Y\n#define _CONSTRUCT_CONFIG__WRAP_SEQUENCE_Y(...) \\\n\t((__VA_ARGS__)) _CONSTRUCT_CONFIG__WRAP_SEQUENCE_X\n\n#define _CONSTRUCT_CONFIG__WRAP_SEQUENCE_X0\n#define _CONSTRUCT_CONFIG__WRAP_SEQUENCE_Y0\n\n\/***************************************************************************\/\n\n#define _CONSTRUCT_CONFIG__GENERATE_MEMBERS(unused, data, idx, elem) \\\n\tBOOST_PP_TUPLE_ELEM(0, elem) \/* type *\/ BOOST_PP_TUPLE_ELEM(1, elem) \/* var name *\/ ;\n\n#define _CONSTRUCT_CONFIG__INIT_MEMBERS_WITH_DEFAULT(...) \\\n\t,BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(2, __VA_ARGS__))\n\n#define _CONSTRUCT_CONFIG__INIT_MEMBERS_WITHOUT_DEFAULT(...) \\\n\t,nullptr\n\n#define _CONSTRUCT_CONFIG__INIT_MEMBERS(unused, data, idx, elem) \\\n\tBOOST_PP_COMMA_IF(idx) \\\n\t\t::construct_config::get_value( \\\n\t\t\t BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(1, elem)) \\\n\t\t\t,cfg \\\n\t\t\tBOOST_PP_IF( \\\n\t\t\t\t BOOST_PP_GREATER_EQUAL(BOOST_PP_TUPLE_SIZE(elem), 3) \\\n\t\t\t\t,_CONSTRUCT_CONFIG__INIT_MEMBERS_WITH_DEFAULT \\\n\t\t\t\t,_CONSTRUCT_CONFIG__INIT_MEMBERS_WITHOUT_DEFAULT \\\n\t\t\t)(elem) \\\n\t\t)\n\n#define _CONSTRUCT_CONFIG__ENUM_MEMBERS(unused, data, idx, elem) \\\n\tos << BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(1, elem)) \"=\"; \\\n\t::construct_config::print_value< \\\n\t\tstd::is_arithmetic::value \\\n\t>::print(BOOST_PP_TUPLE_ELEM(1, elem), os); \\\n\tos << std::endl;\n\n\/***************************************************************************\/\n\n#define _CONSTRUCT_CONFIG__ENUM_WRITE_MEMBERS(unused, data, idx, elem) \\\n\tptree.put(BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(1, elem)), cfg.BOOST_PP_TUPLE_ELEM(1, elem));\n\n\/***************************************************************************\/\n\n#define _CONSTRUCT_CONFIG__GENERATE_STRUCT(fmt, name, seq) \\\n\tstruct name { \\\n\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t _CONSTRUCT_CONFIG__GENERATE_MEMBERS \\\n\t\t\t,~ \\\n\t\t\t,seq \\\n\t\t) \\\n\t\t\\\n\t\tstatic name read(std::istream &is) { \\\n\t\t\tboost::property_tree::ptree cfg; \\\n\t\t\tboost::property_tree::read_##fmt(is, cfg); \\\n\t\t\t\\\n\t\t\treturn { \\\n\t\t\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t\t\t _CONSTRUCT_CONFIG__INIT_MEMBERS \\\n\t\t\t\t\t,~ \\\n\t\t\t\t\t,seq \\\n\t\t\t\t) \\\n\t\t\t}; \\\n\t\t} \\\n\t\tstatic name read(const std::string &fname) { \\\n\t\t\tboost::property_tree::ptree cfg; \\\n\t\t\tboost::property_tree::read_##fmt(fname, cfg); \\\n\t\t\t\\\n\t\t\treturn { \\\n\t\t\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t\t\t _CONSTRUCT_CONFIG__INIT_MEMBERS \\\n\t\t\t\t\t,~ \\\n\t\t\t\t\t,seq \\\n\t\t\t\t) \\\n\t\t\t}; \\\n\t\t} \\\n\t\t\\\n\t\tstatic void write(const std::string &fname, const name &cfg) { \\\n\t\t\tboost::property_tree::ptree ptree; \\\n\t\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t\t _CONSTRUCT_CONFIG__ENUM_WRITE_MEMBERS \\\n\t\t\t\t,~ \\\n\t\t\t\t,seq \\\n\t\t\t) \\\n\t\t\tboost::property_tree::write_##fmt(fname, ptree); \\\n\t\t} \\\n\t\tstatic void write(std::ostream &os, const name &cfg) { \\\n\t\t\tboost::property_tree::ptree ptree; \\\n\t\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t\t _CONSTRUCT_CONFIG__ENUM_WRITE_MEMBERS \\\n\t\t\t\t,~ \\\n\t\t\t\t,seq \\\n\t\t\t) \\\n\t\t\tboost::property_tree::write_##fmt(os, ptree); \\\n\t\t} \\\n\t\t\\\n\t\tvoid dump(std::ostream &os) const { \\\n\t\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t\t _CONSTRUCT_CONFIG__ENUM_MEMBERS \\\n\t\t\t\t,~ \\\n\t\t\t\t,seq \\\n\t\t\t) \\\n\t\t} \\\n\t};\n\n\/***************************************************************************\/\n\n#define CONSTRUCT_CONFIG( \\\n\t fmt \/* config file format *\/ \\\n\t,name \/* config struct name *\/ \\\n\t,seq \/* sequence of vars *\/ \\\n) \\\n\t_CONSTRUCT_CONFIG__GENERATE_STRUCT( \\\n\t\t fmt \\\n\t\t,name \\\n\t\t,BOOST_PP_CAT(_CONSTRUCT_CONFIG__WRAP_SEQUENCE_X seq, 0) \\\n\t)\n\n#define CONSTRUCT_INI_CONFIG(name, seq) \\\n\tCONSTRUCT_CONFIG(ini, name, seq)\n\n#define CONSTRUCT_JSON_CONFIG(name, seq) \\\n\tCONSTRUCT_CONFIG(json, name, seq)\n\n#define CONSTRUCT_XML_CONFIG(name, seq) \\\n\tCONSTRUCT_CONFIG(xml, name, seq)\n\n#define CONSTRUCT_INFO_CONFIG(name, seq) \\\n\tCONSTRUCT_CONFIG(info, name, seq)\n\n\/***************************************************************************\/\n\n#endif \/\/ _config_ctor_hpp\nUpdate config-ctor.hpp\n#ifndef _config_ctor_hpp\n#define _config_ctor_hpp\n\n#include \n#include \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\/***************************************************************************\/\n\nnamespace construct_config {\nnamespace {\n\n\/\/ for other types (strings)\ntemplate\nstruct get_concrete_value {\n\ttemplate\n\tstatic T get(const char *key, const boost::property_tree::ptree &ini, const char *default_value) {\n\t\treturn default_value != nullptr\n\t\t\t? ini.get(key, default_value)\n\t\t\t: ini.get(key)\n\t\t;\n\t}\n};\n\n\/\/ specialization for arithmetic types\ntemplate<>\nstruct get_concrete_value {\n\ttemplate\n\tstatic T get(const char *key, const boost::property_tree::ptree &ini, const char *default_value) {\n\t\t\/\/ handle bool types\n\t\tif ( std::is_same::value ) {\n\t\t\treturn default_value != nullptr\n\t\t\t\t? ini.get(key, (std::strcmp(default_value, \"true\") == 0))\n\t\t\t\t: ini.get(key)\n\t\t\t;\n\t\t}\n\n\t\t\/\/ handle other arithmetic types\n\t\tstd::string val = default_value != nullptr\n\t\t\t? ini.get(key, default_value)\n\t\t\t: ini.get(key)\n\t\t;\n\t\tif ( val.empty() ) return T{};\n\n\t\tif ( (std::is_signed::value || std::is_unsigned::value) && !std::is_floating_point::value ) {\n\t\t\tstd::size_t mult = 1u;\n\t\t\tswitch ( val.back() ) {\n\t\t\t\tcase 'G': mult *= 1024u;\n\t\t\t\tcase 'M': mult *= 1024u;\n\t\t\t\tcase 'K': mult *= 1024u;\n\n\t\t\t\tval.pop_back();\n\t\t\t}\n\n\t\t\treturn (std::is_signed::value ? std::stol(val) : std::stoul(val)) * mult;\n\t\t}\n\n\t\treturn std::stod(val);\n\t}\n};\n\n} \/\/ anon ns\n\ntemplate\nstatic T get_value(const char *key, const boost::property_tree::ptree &cfg, const char *default_value) {\n\tusing TT = typename std::remove_cv::type;\n\treturn get_concrete_value::value>::template get(key, cfg, default_value);\n}\n\ntemplate\nstruct print_value {\n\ttemplate\n\tstatic void print(const T &v, std::ostream &os) {\n\t\tos << '\\\"' << v << '\\\"';\n\t}\n};\n\ntemplate<>\nstruct print_value {\n\ttemplate\n\tstatic void print(const T &v, std::ostream &os) {\n\t\tos << std::boolalpha << v;\n\t}\n};\n\n} \/\/ ns construct_config\n\n\/***************************************************************************\/\n\n#define _CONSTRUCT_CONFIG__WRAP_SEQUENCE_X(...) \\\n\t((__VA_ARGS__)) _CONSTRUCT_CONFIG__WRAP_SEQUENCE_Y\n#define _CONSTRUCT_CONFIG__WRAP_SEQUENCE_Y(...) \\\n\t((__VA_ARGS__)) _CONSTRUCT_CONFIG__WRAP_SEQUENCE_X\n\n#define _CONSTRUCT_CONFIG__WRAP_SEQUENCE_X0\n#define _CONSTRUCT_CONFIG__WRAP_SEQUENCE_Y0\n\n\/***************************************************************************\/\n\n#define _CONSTRUCT_CONFIG__GENERATE_MEMBERS(unused, data, idx, elem) \\\n\tBOOST_PP_TUPLE_ELEM(0, elem) \/* type *\/ BOOST_PP_TUPLE_ELEM(1, elem) \/* var name *\/ ;\n\n#define _CONSTRUCT_CONFIG__INIT_MEMBERS_WITH_DEFAULT(...) \\\n\t,BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(2, __VA_ARGS__))\n\n#define _CONSTRUCT_CONFIG__INIT_MEMBERS_WITHOUT_DEFAULT(...) \\\n\t,nullptr\n\n#define _CONSTRUCT_CONFIG__INIT_MEMBERS(unused, data, idx, elem) \\\n\tBOOST_PP_COMMA_IF(idx) \\\n\t\t::construct_config::get_value( \\\n\t\t\t BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(1, elem)) \\\n\t\t\t,cfg \\\n\t\t\tBOOST_PP_IF( \\\n\t\t\t\t BOOST_PP_GREATER_EQUAL(BOOST_PP_TUPLE_SIZE(elem), 3) \\\n\t\t\t\t,_CONSTRUCT_CONFIG__INIT_MEMBERS_WITH_DEFAULT \\\n\t\t\t\t,_CONSTRUCT_CONFIG__INIT_MEMBERS_WITHOUT_DEFAULT \\\n\t\t\t)(elem) \\\n\t\t)\n\n#define _CONSTRUCT_CONFIG__ENUM_MEMBERS(unused, data, idx, elem) \\\n\tos << BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(1, elem)) \"=\"; \\\n\t::construct_config::print_value< \\\n\t\tstd::is_arithmetic::value \\\n\t>::print(BOOST_PP_TUPLE_ELEM(1, elem), os); \\\n\tos << std::endl;\n\n\/***************************************************************************\/\n\n#define _CONSTRUCT_CONFIG__ENUM_WRITE_MEMBERS(unused, data, idx, elem) \\\n\tptree.put(BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(1, elem)), cfg.BOOST_PP_TUPLE_ELEM(1, elem));\n\n\/***************************************************************************\/\n\n#define _CONSTRUCT_CONFIG__GENERATE_STRUCT(fmt, name, seq) \\\n\tstruct name { \\\n\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t _CONSTRUCT_CONFIG__GENERATE_MEMBERS \\\n\t\t\t,~ \\\n\t\t\t,seq \\\n\t\t) \\\n\t\t\\\n\t\tstatic name read(std::istream &is) { \\\n\t\t\tboost::property_tree::ptree cfg; \\\n\t\t\tboost::property_tree::read_##fmt(is, cfg); \\\n\t\t\t\\\n\t\t\treturn { \\\n\t\t\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t\t\t _CONSTRUCT_CONFIG__INIT_MEMBERS \\\n\t\t\t\t\t,~ \\\n\t\t\t\t\t,seq \\\n\t\t\t\t) \\\n\t\t\t}; \\\n\t\t} \\\n\t\tstatic name read(const std::string &fname) { \\\n\t\t\tboost::property_tree::ptree cfg; \\\n\t\t\tboost::property_tree::read_##fmt(fname, cfg); \\\n\t\t\t\\\n\t\t\treturn { \\\n\t\t\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t\t\t _CONSTRUCT_CONFIG__INIT_MEMBERS \\\n\t\t\t\t\t,~ \\\n\t\t\t\t\t,seq \\\n\t\t\t\t) \\\n\t\t\t}; \\\n\t\t} \\\n\t\t\\\n\t\tstatic void write(const std::string &fname, const name &cfg) { \\\n\t\t\tboost::property_tree::ptree ptree; \\\n\t\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t\t _CONSTRUCT_CONFIG__ENUM_WRITE_MEMBERS \\\n\t\t\t\t,~ \\\n\t\t\t\t,seq \\\n\t\t\t) \\\n\t\t\tboost::property_tree::write_##fmt(fname, ptree); \\\n\t\t} \\\n\t\tstatic void write(std::ostream &os, const name &cfg) { \\\n\t\t\tboost::property_tree::ptree ptree; \\\n\t\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t\t _CONSTRUCT_CONFIG__ENUM_WRITE_MEMBERS \\\n\t\t\t\t,~ \\\n\t\t\t\t,seq \\\n\t\t\t) \\\n\t\t\tboost::property_tree::write_##fmt(os, ptree); \\\n\t\t} \\\n\t\t\\\n\t\tvoid dump(std::ostream &os) const { \\\n\t\t\tBOOST_PP_SEQ_FOR_EACH_I( \\\n\t\t\t\t _CONSTRUCT_CONFIG__ENUM_MEMBERS \\\n\t\t\t\t,~ \\\n\t\t\t\t,seq \\\n\t\t\t) \\\n\t\t} \\\n\t};\n\n\/***************************************************************************\/\n\n#define CONSTRUCT_CONFIG( \\\n\t fmt \/* config file format *\/ \\\n\t,name \/* config struct name *\/ \\\n\t,seq \/* sequence of vars *\/ \\\n) \\\n\t_CONSTRUCT_CONFIG__GENERATE_STRUCT( \\\n\t\t fmt \\\n\t\t,name \\\n\t\t,BOOST_PP_CAT(_CONSTRUCT_CONFIG__WRAP_SEQUENCE_X seq, 0) \\\n\t)\n\n#define CONSTRUCT_INI_CONFIG(name, seq) \\\n\tCONSTRUCT_CONFIG(ini, name, seq)\n\n#define CONSTRUCT_JSON_CONFIG(name, seq) \\\n\tCONSTRUCT_CONFIG(json, name, seq)\n\n#define CONSTRUCT_XML_CONFIG(name, seq) \\\n\tCONSTRUCT_CONFIG(xml, name, seq)\n\n#define CONSTRUCT_INFO_CONFIG(name, seq) \\\n\tCONSTRUCT_CONFIG(info, name, seq)\n\n\/***************************************************************************\/\n\n#endif \/\/ _config_ctor_hpp\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ - Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ - Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ - Neither the name of Salesforce.com nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this\n\/\/ software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n\/\/ OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n\/\/ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n\/\/ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace distributions\n{\n\ntemplate\nstruct DirichletDiscrete\n{\n\nstatic const char * name () { return \"DirichletDiscrete\"; }\nstatic const char * short_name () { return \"dd\"; }\n\n\/\/----------------------------------------------------------------------------\n\/\/ Data\n\nint dim; \/\/ fixed parameter\nfloat alphas[max_dim]; \/\/ hyperparamter\n\n\/\/----------------------------------------------------------------------------\n\/\/ Datatypes\n\ntypedef uint32_t count_t;\n\ntypedef int Value;\n\nstruct Group\n{\n count_t count_sum;\n count_t counts[max_dim];\n};\n\nstruct Sampler\n{\n float ps[max_dim];\n};\n\nstruct Scorer\n{\n float alpha_sum;\n float alphas[max_dim];\n};\n\nstruct Classifier\n{\n std::vector groups;\n float alpha_sum;\n std::vector scores;\n VectorFloat scores_shift;\n};\n\nclass Fitter\n{\n std::vector groups;\n VectorFloat scores;\n};\n\n\/\/----------------------------------------------------------------------------\n\/\/ Mutation\n\nvoid group_init (\n Group & group,\n rng_t &) const\n{\n group.count_sum = 0;\n for (Value value = 0; value < dim; ++value) {\n group.counts[value] = 0;\n }\n}\n\nvoid group_add_value (\n Group & group,\n const Value & value,\n rng_t &) const\n{\n DIST_ASSERT1(value < dim, \"value out of bounds\");\n group.count_sum += 1;\n group.counts[value] += 1;\n}\n\nvoid group_remove_value (\n Group & group,\n const Value & value,\n rng_t &) const\n{\n DIST_ASSERT1(value < dim, \"value out of bounds\");\n group.count_sum -= 1;\n group.counts[value] -= 1;\n}\n\nvoid group_merge (\n Group & destin,\n const Group & source,\n rng_t &) const\n{\n DIST_ASSERT1(& destin != & source, \"cannot merge with self\");\n for (Value value = 0; value < dim; ++value) {\n destin.counts[value] += source.counts[value];\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Sampling\n\nvoid sampler_init (\n Sampler & sampler,\n const Group & group,\n rng_t & rng) const\n{\n for (Value value = 0; value < dim; ++value) {\n sampler.ps[value] = alphas[value] + group.counts[value];\n }\n\n sample_dirichlet(rng, dim, sampler.ps, sampler.ps);\n}\n\nValue sampler_eval (\n const Sampler & sampler,\n rng_t & rng) const\n{\n return sample_discrete(rng, dim, sampler.ps);\n}\n\nValue sample_value (\n const Group & group,\n rng_t & rng) const\n{\n Sampler sampler;\n sampler_init(sampler, group, rng);\n return sampler_eval(sampler, rng);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Scoring\n\nvoid scorer_init (\n Scorer & scorer,\n const Group & group,\n rng_t &) const\n{\n float alpha_sum = 0;\n for (Value value = 0; value < dim; ++value) {\n float alpha = alphas[value] + group.counts[value];\n scorer.alphas[value] = alpha;\n alpha_sum += alpha;\n }\n scorer.alpha_sum = alpha_sum;\n}\n\nfloat scorer_eval (\n const Scorer & scorer,\n const Value & value,\n rng_t &) const\n{\n DIST_ASSERT1(value < dim, \"value out of bounds\");\n return fast_log(scorer.alphas[value] \/ scorer.alpha_sum);\n}\n\nfloat score_value (\n const Group & group,\n const Value & value,\n rng_t & rng) const\n{\n DIST_ASSERT1(value < dim, \"value out of bounds\");\n Scorer scorer;\n scorer_init(scorer, group, rng);\n return scorer_eval(scorer, value, rng);\n}\n\nfloat score_group (\n const Group & group,\n rng_t &) const\n{\n float alpha_sum = 0;\n float score = 0;\n\n for (Value value = 0; value < dim; ++value) {\n float alpha = alphas[value];\n alpha_sum += alpha;\n score += fast_lgamma(alpha + group.counts[value]) - fast_lgamma(alpha);\n }\n\n score += fast_lgamma(alpha_sum) - fast_lgamma(alpha_sum + group.count_sum);\n\n return score;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Classification\n\nvoid classifier_init (\n Classifier & classifier,\n rng_t &) const\n{\n const size_t group_count = classifier.groups.size();\n classifier.scores_shift.resize(group_count);\n classifier.alpha_sum = 0;\n classifier.scores.resize(dim);\n for (Value value = 0; value < dim; ++value) {\n classifier.alpha_sum += alphas[value];\n classifier.scores[value].resize(group_count);\n }\n for (size_t groupid = 0; groupid < group_count; ++groupid) {\n const Group & group = classifier.groups[groupid];\n for (Value value = 0; value < dim; ++value) {\n classifier.scores[value][groupid] =\n alphas[value] + group.counts[value];\n }\n classifier.scores_shift[groupid] =\n classifier.alpha_sum + group.count_sum;\n }\n vector_log(group_count, classifier.scores_shift.data());\n for (Value value = 0; value < dim; ++value) {\n vector_log(group_count, classifier.scores[value].data());\n }\n}\n\nvoid classifier_add_group (\n Classifier & classifier,\n rng_t & rng) const\n{\n const size_t group_count = classifier.groups.size() + 1;\n classifier.groups.resize(group_count);\n group_init(classifier.groups.back(), rng);\n classifier.scores_shift.resize(group_count, 0);\n for (Value value = 0; value < dim; ++value) {\n classifier.scores[value].resize(group_count, 0);\n }\n}\n\nvoid classifier_remove_group (\n Classifier & classifier,\n size_t groupid) const\n{\n const size_t group_count = classifier.groups.size() - 1;\n if (groupid != group_count) {\n std::swap(classifier.groups[groupid], classifier.groups.back());\n classifier.scores_shift[groupid] = classifier.scores_shift.back();\n for (Value value = 0; value < dim; ++value) {\n VectorFloat & scores = classifier.scores[value];\n scores[groupid] = scores.back();\n }\n }\n classifier.groups.resize(group_count);\n classifier.scores_shift.resize(group_count);\n for (Value value = 0; value < dim; ++value) {\n classifier.scores[value].resize(group_count);\n }\n}\n\nvoid classifier_add_value (\n Classifier & classifier,\n size_t groupid,\n const Value & value,\n rng_t &) const\n{\n DIST_ASSERT1(groupid < classifier.groups.size(), \"groupid out of bounds\");\n DIST_ASSERT1(value < dim, \"value out of bounds\");\n Group & group = classifier.groups[groupid];\n count_t count_sum = group.count_sum += 1;\n count_t count = group.counts[value] += 1;\n classifier.scores[value][groupid] = fast_log(alphas[value] + count);\n classifier.scores_shift[groupid] =\n fast_log(classifier.alpha_sum + count_sum);\n}\n\nvoid classifier_remove_value (\n Classifier & classifier,\n size_t groupid,\n const Value & value,\n rng_t &) const\n{\n DIST_ASSERT1(groupid < classifier.groups.size(), \"groupid out of bounds\");\n DIST_ASSERT1(value < dim, \"value out of bounds\");\n Group & group = classifier.groups[groupid];\n count_t count_sum = group.count_sum -= 1;\n count_t count = group.counts[value] -= 1;\n classifier.scores[value][groupid] = fast_log(alphas[value] + count);\n classifier.scores_shift[groupid] =\n fast_log(classifier.alpha_sum + count_sum);\n}\n\nvoid classifier_score (\n const Classifier & classifier,\n const Value & value,\n VectorFloat & scores_accum,\n rng_t &) const\n{\n DIST_ASSERT1(value < dim, \"value out of bounds\");\n DIST_ASSERT2(\n scores_accum.size() == classifier.groups.size(),\n \"expected scores_accum.size() = \" << classifier.groups.size() <<\n \", actual \" << scores_accum.size());\n const size_t group_count = classifier.groups.size();\n vector_add_subtract(\n group_count,\n scores_accum.data(),\n classifier.scores[value].data(),\n classifier.scores_shift.data());\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Fitting\n\nvoid fitter_init (\n Fitter & fitter) const\n{\n const size_t group_count = fitter.groups.size();\n const float alpha_sum = vector_sum(dim, alphas);\n fitter.scores.resize(dim + 1);\n for (Value value = 0; value < dim; ++value) {\n vector_zero(fitter.scores[value].size(), fitter.scores[value].data());\n }\n float score_shift = 0;\n for (size_t groupid = 0; groupid < group_count; ++groupid) {\n const Group & group = fitter.groups[groupid];\n for (Value value = 0; value < dim; ++value) {\n float alpha = alphas[value];\n fitter.scores[value] +=\n fast_lgamma(alpha + group.counts[value]) - fast_lgamma(alpha);\n }\n score_shift +=\n fast_lgamma(alpha_sum) - fast_lgamma(alpha_sum + group.count_sum);\n }\n fitter.scores.back() = score_shift;\n}\n\nvoid fitter_set_param_alpha (\n Fitter & fitter,\n Value value,\n float alpha)\n{\n DIST_ASSERT1(value < dim, \"value out of bounds\");\n\n alphas[value] = alpha;\n\n const size_t group_count = fitter.groups.size();\n const float alpha_sum = vector_sum(dim, alphas);\n float score = 0;\n float score_shift = 0;\n for (size_t groupid = 0; groupid < group_count; ++groupid) {\n const Group & group = fitter.groups[groupid];\n score += fast_lgamma(alpha + group.counts[value]) - fast_lgamma(alpha);\n score_shift +=\n fast_lgamma(alpha_sum) - fast_lgamma(alpha_sum + group.count_sum);\n }\n fitter.scores[value] = score;\n fitter.scores.back() = score_shift;\n}\n\nfloat fitter_score (\n Fitter & fitter) const\n{\n return vector_sum(fitter.scores.size(), fitter.scores.data());\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Examples\n\nstatic DirichletDiscrete EXAMPLE ();\n\n}; \/\/ struct DirichletDiscrete\n\ntemplate\ninline DirichletDiscrete DirichletDiscrete::EXAMPLE ()\n{\n DirichletDiscrete model;\n model.dim = max_dim;\n for (int i = 0; i < max_dim; ++i) {\n model.alphas[i] = 0.5;\n }\n return model;\n}\n\n} \/\/ namespace distributions\nBetter error handling in protobuf parsing\/\/ Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ - Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ - Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ - Neither the name of Salesforce.com nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this\n\/\/ software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n\/\/ OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n\/\/ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n\/\/ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace distributions\n{\n\ntemplate\nstruct DirichletDiscrete\n{\n\nstatic const char * name () { return \"DirichletDiscrete\"; }\nstatic const char * short_name () { return \"dd\"; }\n\n\/\/----------------------------------------------------------------------------\n\/\/ Data\n\nint dim; \/\/ fixed parameter\nfloat alphas[max_dim]; \/\/ hyperparamter\n\n\/\/----------------------------------------------------------------------------\n\/\/ Datatypes\n\ntypedef uint32_t count_t;\n\ntypedef int Value;\n\nstruct Group\n{\n count_t count_sum;\n count_t counts[max_dim];\n};\n\nstruct Sampler\n{\n float ps[max_dim];\n};\n\nstruct Scorer\n{\n float alpha_sum;\n float alphas[max_dim];\n};\n\nstruct Classifier\n{\n std::vector groups;\n float alpha_sum;\n std::vector scores;\n VectorFloat scores_shift;\n};\n\nclass Fitter\n{\n std::vector groups;\n VectorFloat scores;\n};\n\n\/\/----------------------------------------------------------------------------\n\/\/ Mutation\n\nvoid group_init (\n Group & group,\n rng_t &) const\n{\n group.count_sum = 0;\n for (Value value = 0; value < dim; ++value) {\n group.counts[value] = 0;\n }\n}\n\nvoid group_add_value (\n Group & group,\n const Value & value,\n rng_t &) const\n{\n DIST_ASSERT1(value < dim, \"value out of bounds: \" << value);\n group.count_sum += 1;\n group.counts[value] += 1;\n}\n\nvoid group_remove_value (\n Group & group,\n const Value & value,\n rng_t &) const\n{\n DIST_ASSERT1(value < dim, \"value out of bounds: \" << value);\n group.count_sum -= 1;\n group.counts[value] -= 1;\n}\n\nvoid group_merge (\n Group & destin,\n const Group & source,\n rng_t &) const\n{\n DIST_ASSERT1(& destin != & source, \"cannot merge with self\");\n for (Value value = 0; value < dim; ++value) {\n destin.counts[value] += source.counts[value];\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Sampling\n\nvoid sampler_init (\n Sampler & sampler,\n const Group & group,\n rng_t & rng) const\n{\n for (Value value = 0; value < dim; ++value) {\n sampler.ps[value] = alphas[value] + group.counts[value];\n }\n\n sample_dirichlet(rng, dim, sampler.ps, sampler.ps);\n}\n\nValue sampler_eval (\n const Sampler & sampler,\n rng_t & rng) const\n{\n return sample_discrete(rng, dim, sampler.ps);\n}\n\nValue sample_value (\n const Group & group,\n rng_t & rng) const\n{\n Sampler sampler;\n sampler_init(sampler, group, rng);\n return sampler_eval(sampler, rng);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Scoring\n\nvoid scorer_init (\n Scorer & scorer,\n const Group & group,\n rng_t &) const\n{\n float alpha_sum = 0;\n for (Value value = 0; value < dim; ++value) {\n float alpha = alphas[value] + group.counts[value];\n scorer.alphas[value] = alpha;\n alpha_sum += alpha;\n }\n scorer.alpha_sum = alpha_sum;\n}\n\nfloat scorer_eval (\n const Scorer & scorer,\n const Value & value,\n rng_t &) const\n{\n DIST_ASSERT1(value < dim, \"value out of bounds: \" << value);\n return fast_log(scorer.alphas[value] \/ scorer.alpha_sum);\n}\n\nfloat score_value (\n const Group & group,\n const Value & value,\n rng_t & rng) const\n{\n DIST_ASSERT1(value < dim, \"value out of bounds: \" << value);\n Scorer scorer;\n scorer_init(scorer, group, rng);\n return scorer_eval(scorer, value, rng);\n}\n\nfloat score_group (\n const Group & group,\n rng_t &) const\n{\n float alpha_sum = 0;\n float score = 0;\n\n for (Value value = 0; value < dim; ++value) {\n float alpha = alphas[value];\n alpha_sum += alpha;\n score += fast_lgamma(alpha + group.counts[value]) - fast_lgamma(alpha);\n }\n\n score += fast_lgamma(alpha_sum) - fast_lgamma(alpha_sum + group.count_sum);\n\n return score;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Classification\n\nvoid classifier_init (\n Classifier & classifier,\n rng_t &) const\n{\n const size_t group_count = classifier.groups.size();\n classifier.scores_shift.resize(group_count);\n classifier.alpha_sum = 0;\n classifier.scores.resize(dim);\n for (Value value = 0; value < dim; ++value) {\n classifier.alpha_sum += alphas[value];\n classifier.scores[value].resize(group_count);\n }\n for (size_t groupid = 0; groupid < group_count; ++groupid) {\n const Group & group = classifier.groups[groupid];\n for (Value value = 0; value < dim; ++value) {\n classifier.scores[value][groupid] =\n alphas[value] + group.counts[value];\n }\n classifier.scores_shift[groupid] =\n classifier.alpha_sum + group.count_sum;\n }\n vector_log(group_count, classifier.scores_shift.data());\n for (Value value = 0; value < dim; ++value) {\n vector_log(group_count, classifier.scores[value].data());\n }\n}\n\nvoid classifier_add_group (\n Classifier & classifier,\n rng_t & rng) const\n{\n const size_t group_count = classifier.groups.size() + 1;\n classifier.groups.resize(group_count);\n group_init(classifier.groups.back(), rng);\n classifier.scores_shift.resize(group_count, 0);\n for (Value value = 0; value < dim; ++value) {\n classifier.scores[value].resize(group_count, 0);\n }\n}\n\nvoid classifier_remove_group (\n Classifier & classifier,\n size_t groupid) const\n{\n const size_t group_count = classifier.groups.size() - 1;\n if (groupid != group_count) {\n std::swap(classifier.groups[groupid], classifier.groups.back());\n classifier.scores_shift[groupid] = classifier.scores_shift.back();\n for (Value value = 0; value < dim; ++value) {\n VectorFloat & scores = classifier.scores[value];\n scores[groupid] = scores.back();\n }\n }\n classifier.groups.resize(group_count);\n classifier.scores_shift.resize(group_count);\n for (Value value = 0; value < dim; ++value) {\n classifier.scores[value].resize(group_count);\n }\n}\n\nvoid classifier_add_value (\n Classifier & classifier,\n size_t groupid,\n const Value & value,\n rng_t &) const\n{\n DIST_ASSERT1(groupid < classifier.groups.size(), \"groupid out of bounds\");\n DIST_ASSERT1(value < dim, \"value out of bounds: \" << value);\n Group & group = classifier.groups[groupid];\n count_t count_sum = group.count_sum += 1;\n count_t count = group.counts[value] += 1;\n classifier.scores[value][groupid] = fast_log(alphas[value] + count);\n classifier.scores_shift[groupid] =\n fast_log(classifier.alpha_sum + count_sum);\n}\n\nvoid classifier_remove_value (\n Classifier & classifier,\n size_t groupid,\n const Value & value,\n rng_t &) const\n{\n DIST_ASSERT1(groupid < classifier.groups.size(), \"groupid out of bounds\");\n DIST_ASSERT1(value < dim, \"value out of bounds: \" << value);\n Group & group = classifier.groups[groupid];\n count_t count_sum = group.count_sum -= 1;\n count_t count = group.counts[value] -= 1;\n classifier.scores[value][groupid] = fast_log(alphas[value] + count);\n classifier.scores_shift[groupid] =\n fast_log(classifier.alpha_sum + count_sum);\n}\n\nvoid classifier_score (\n const Classifier & classifier,\n const Value & value,\n VectorFloat & scores_accum,\n rng_t &) const\n{\n DIST_ASSERT1(value < dim, \"value out of bounds: \" << value);\n DIST_ASSERT2(\n scores_accum.size() == classifier.groups.size(),\n \"expected scores_accum.size() = \" << classifier.groups.size() <<\n \", actual \" << scores_accum.size());\n const size_t group_count = classifier.groups.size();\n vector_add_subtract(\n group_count,\n scores_accum.data(),\n classifier.scores[value].data(),\n classifier.scores_shift.data());\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Fitting\n\nvoid fitter_init (\n Fitter & fitter) const\n{\n const size_t group_count = fitter.groups.size();\n const float alpha_sum = vector_sum(dim, alphas);\n fitter.scores.resize(dim + 1);\n for (Value value = 0; value < dim; ++value) {\n vector_zero(fitter.scores[value].size(), fitter.scores[value].data());\n }\n float score_shift = 0;\n for (size_t groupid = 0; groupid < group_count; ++groupid) {\n const Group & group = fitter.groups[groupid];\n for (Value value = 0; value < dim; ++value) {\n float alpha = alphas[value];\n fitter.scores[value] +=\n fast_lgamma(alpha + group.counts[value]) - fast_lgamma(alpha);\n }\n score_shift +=\n fast_lgamma(alpha_sum) - fast_lgamma(alpha_sum + group.count_sum);\n }\n fitter.scores.back() = score_shift;\n}\n\nvoid fitter_set_param_alpha (\n Fitter & fitter,\n Value value,\n float alpha)\n{\n DIST_ASSERT1(value < dim, \"value out of bounds: \" << value);\n\n alphas[value] = alpha;\n\n const size_t group_count = fitter.groups.size();\n const float alpha_sum = vector_sum(dim, alphas);\n float score = 0;\n float score_shift = 0;\n for (size_t groupid = 0; groupid < group_count; ++groupid) {\n const Group & group = fitter.groups[groupid];\n score += fast_lgamma(alpha + group.counts[value]) - fast_lgamma(alpha);\n score_shift +=\n fast_lgamma(alpha_sum) - fast_lgamma(alpha_sum + group.count_sum);\n }\n fitter.scores[value] = score;\n fitter.scores.back() = score_shift;\n}\n\nfloat fitter_score (\n Fitter & fitter) const\n{\n return vector_sum(fitter.scores.size(), fitter.scores.data());\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Examples\n\nstatic DirichletDiscrete EXAMPLE ();\n\n}; \/\/ struct DirichletDiscrete\n\ntemplate\ninline DirichletDiscrete DirichletDiscrete::EXAMPLE ()\n{\n DirichletDiscrete model;\n model.dim = max_dim;\n for (int i = 0; i < max_dim; ++i) {\n model.alphas[i] = 0.5;\n }\n return model;\n}\n\n} \/\/ namespace distributions\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#ifndef itkSpectra1DImageFilter_hxx\n#define itkSpectra1DImageFilter_hxx\n\n#include \"itkSpectra1DImageFilter.h\"\n\n#include \"itkImageLinearConstIteratorWithIndex.h\"\n#include \"itkImageLinearIteratorWithIndex.h\"\n#include \"itkImageRegionConstIterator.h\"\n#include \"itkMetaDataObject.h\"\n\n#include \"itkSpectra1DSupportWindowImageFilter.h\"\n\nnamespace itk\n{\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::Spectra1DImageFilter()\n{\n this->AddRequiredInputName( \"SupportWindowImage\" );\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::GenerateOutputInformation()\n{\n Superclass::GenerateOutputInformation();\n\n const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n FFT1DSizeType fft1DSize = 32;\n ExposeMetaData< FFT1DSizeType >( dict, \"FFT1DSize\", fft1DSize );\n const FFT1DSizeType spectraComponents = fft1DSize \/ 2 - 1;\n\n OutputImageType * output = this->GetOutput();\n output->SetVectorLength( spectraComponents );\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::BeforeThreadedGenerateData()\n{\n const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n FFT1DSizeType fft1DSize = 32;\n ExposeMetaData< FFT1DSizeType >( dict, \"FFT1DSize\", fft1DSize );\n const FFT1DSizeType spectraComponents = fft1DSize \/ 2 - 1;\n\n const ThreadIdType numberOfThreads = this->GetNumberOfThreads();\n this->m_PerThreadDataContainer.resize( numberOfThreads );\n for( ThreadIdType threadId = 0; threadId < numberOfThreads; ++threadId )\n {\n PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n perThreadData.ComplexVector.set_size( fft1DSize );\n perThreadData.SpectraVector.set_size( spectraComponents );\n perThreadData.LineImageRegionSize.Fill( 1 );\n perThreadData.LineImageRegionSize[0] = fft1DSize;\n }\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::AddLineWindow( FFT1DSizeType length, LineWindowMapType & lineWindowMap )\n{\n if( lineWindowMap.count( length ) == 1 )\n {\n return;\n }\n \/\/ Currently using a Hamming Window\n SpectraVectorType window( length );\n ScalarType sum = NumericTraits< ScalarType >::ZeroValue();\n const ScalarType twopi = 2 * vnl_math::pi;\n for( FFT1DSizeType sample = 0; sample < length; ++sample )\n {\n window[sample] = 0.54 + 0.46 * std::cos( (twopi * sample) \/ (length - 1) );\n sum += window[sample];\n }\n for( FFT1DSizeType sample = 0; sample < length; ++sample )\n {\n window[sample] \/= sum;\n }\n lineWindowMap[length] = window;\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\ntypename Spectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >::SpectraLineType\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::ComputeSpectra( const IndexType & lineIndex, ThreadIdType threadId )\n{\n const InputImageType * input = this->GetInput();\n PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n\n const FFT1DSizeType fft1DSize = static_cast< FFT1DSizeType >( perThreadData.ComplexVector.size() );\n\n const typename InputImageType::RegionType lineRegion( lineIndex, perThreadData.LineImageRegionSize );\n InputImageIteratorType inputIt( input, lineRegion );\n inputIt.GoToBegin();\n perThreadData.ComplexVector.fill( 0 );\n typename ComplexVectorType::iterator complexVectorIt = perThreadData.ComplexVector.begin();\n typename SpectraVectorType::const_iterator windowIt = perThreadData.LineWindowMap[fft1DSize].begin();\n while( !inputIt.IsAtEnd() )\n {\n *complexVectorIt = inputIt.Value() * *windowIt;\n ++inputIt;\n ++complexVectorIt;\n ++windowIt;\n }\n FFT1DType fft1D( fft1DSize );\n fft1D.bwd_transform( perThreadData.ComplexVector );\n typename ComplexVectorType::const_iterator complexVectorConstIt = perThreadData.ComplexVector.begin();\n typename SpectraVectorType::iterator spectraVectorIt = perThreadData.SpectraVector.begin();\n \/\/ drop DC component\n ++complexVectorConstIt;\n const size_t highFreq = perThreadData.SpectraVector.size();\n for( size_t freq = 0; freq < highFreq; ++freq )\n {\n spectraVectorIt[freq] = std::real(*complexVectorConstIt * std::conj(*complexVectorConstIt));\n ++complexVectorConstIt;\n }\n return std::make_pair( lineIndex, perThreadData.SpectraVector );\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId )\n{\n OutputImageType * output = this->GetOutput();\n const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n\n typedef ImageLinearIteratorWithIndex< OutputImageType > OutputIteratorType;\n OutputIteratorType outputIt( output, outputRegionForThread );\n outputIt.SetDirection( 1 );\n\n const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n FFT1DSizeType fft1DSize = 32;\n ExposeMetaData< FFT1DSizeType >( dict, \"FFT1DSize\", fft1DSize );\n PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n this->AddLineWindow( fft1DSize, perThreadData.LineWindowMap );\n\n ComplexVectorType complexVector( fft1DSize );\n SpectraVectorType spectraVector( fft1DSize );\n typename InputImageType::SizeType lineImageRegionSize;\n lineImageRegionSize.Fill( 1 );\n lineImageRegionSize[0] = fft1DSize;\n vnl_fft_1d< ScalarType > fft1D( fft1DSize );\n SpectraLinesContainerType spectraLines;\n\n typedef ImageLinearConstIteratorWithIndex< SupportWindowImageType > SupportWindowIteratorType;\n SupportWindowIteratorType supportWindowIt( supportWindowImage, outputRegionForThread );\n supportWindowIt.SetDirection( 1 );\n\n for( outputIt.GoToBegin(), supportWindowIt.GoToBegin();\n !outputIt.IsAtEnd();\n outputIt.NextLine(), supportWindowIt.NextLine() )\n {\n spectraLines.clear();\n while( ! outputIt.IsAtEndOfLine() )\n {\n \/\/ Compute the per line spectra.\n const SupportWindowType & supportWindow = supportWindowIt.Value();\n if( spectraLines.size() == 0 ) \/\/ first window in this lateral direction\n {\n const typename SupportWindowType::const_iterator windowLineEnd = supportWindow.end();\n for( typename SupportWindowType::const_iterator windowLine = supportWindow.begin();\n windowLine != windowLineEnd;\n ++windowLine )\n {\n const IndexType & lineIndex = *windowLine;\n const SpectraLineType & spectraLine = this->ComputeSpectra( lineIndex, threadId );\n spectraLines.push_back( spectraLine );\n }\n }\n else \/\/ subsequent window along a line\n {\n const IndexValueType desiredFirstLine = supportWindow[0][1];\n while( spectraLines[0].first[1] < desiredFirstLine )\n {\n spectraLines.pop_front();\n }\n const typename SupportWindowType::const_iterator windowLineEnd = supportWindow.end();\n typename SpectraLinesContainerType::iterator spectraLinesIt = spectraLines.begin();\n const typename SpectraLinesContainerType::iterator spectraLinesEnd = spectraLines.end();\n for( typename SupportWindowType::const_iterator windowLine = supportWindow.begin();\n windowLine != windowLineEnd;\n ++windowLine )\n {\n const IndexType & lineIndex = *windowLine;\n if( spectraLinesIt == spectraLinesEnd ) \/\/ past the end of the previously processed lines\n {\n const SpectraLineType & spectraLine = this->ComputeSpectra( lineIndex, threadId );\n spectraLines.push_back( spectraLine );\n }\n else if( lineIndex[1] == (spectraLinesIt->first)[1] ) \/\/ one of the same lines that was previously computed\n {\n if( lineIndex[0] != (spectraLinesIt->first)[0] )\n {\n const SpectraLineType & spectraLine = this->ComputeSpectra( lineIndex, threadId );\n *spectraLinesIt = spectraLine;\n }\n ++spectraLinesIt;\n }\n else\n {\n itkExceptionMacro( \"Unexpected line\" );\n }\n }\n }\n\n const size_t spectraLinesCount = spectraLines.size();\n this->AddLineWindow( spectraLinesCount, perThreadData.LineWindowMap );\n typename OutputImageType::PixelType outputPixel;\n outputPixel.SetSize( fft1DSize );\n outputPixel.Fill( NumericTraits< ScalarType >::ZeroValue() );\n typename SpectraVectorType::const_iterator windowIt = perThreadData.LineWindowMap[spectraLinesCount].begin();\n for( size_t line = 0; line < spectraLinesCount; ++line )\n {\n typename SpectraVectorType::const_iterator spectraIt = spectraLines[line].second.begin();\n for( FFT1DSizeType sample = 0; sample < fft1DSize; ++sample )\n {\n outputPixel[sample] += *windowIt * *spectraIt;\n ++spectraIt;\n }\n ++windowIt;\n }\n outputIt.Set( outputPixel );\n\n ++outputIt;\n ++supportWindowIt;\n }\n }\n}\n\n\n} \/\/ end namespace itk\n\n#endif\nENH: Improve twopi specification\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#ifndef itkSpectra1DImageFilter_hxx\n#define itkSpectra1DImageFilter_hxx\n\n#include \"itkSpectra1DImageFilter.h\"\n\n#include \"itkImageLinearConstIteratorWithIndex.h\"\n#include \"itkImageLinearIteratorWithIndex.h\"\n#include \"itkImageRegionConstIterator.h\"\n#include \"itkMetaDataObject.h\"\n\n#include \"itkSpectra1DSupportWindowImageFilter.h\"\n\nnamespace itk\n{\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::Spectra1DImageFilter()\n{\n this->AddRequiredInputName( \"SupportWindowImage\" );\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::GenerateOutputInformation()\n{\n Superclass::GenerateOutputInformation();\n\n const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n FFT1DSizeType fft1DSize = 32;\n ExposeMetaData< FFT1DSizeType >( dict, \"FFT1DSize\", fft1DSize );\n const FFT1DSizeType spectraComponents = fft1DSize \/ 2 - 1;\n\n OutputImageType * output = this->GetOutput();\n output->SetVectorLength( spectraComponents );\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::BeforeThreadedGenerateData()\n{\n const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n FFT1DSizeType fft1DSize = 32;\n ExposeMetaData< FFT1DSizeType >( dict, \"FFT1DSize\", fft1DSize );\n const FFT1DSizeType spectraComponents = fft1DSize \/ 2 - 1;\n\n const ThreadIdType numberOfThreads = this->GetNumberOfThreads();\n this->m_PerThreadDataContainer.resize( numberOfThreads );\n for( ThreadIdType threadId = 0; threadId < numberOfThreads; ++threadId )\n {\n PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n perThreadData.ComplexVector.set_size( fft1DSize );\n perThreadData.SpectraVector.set_size( spectraComponents );\n perThreadData.LineImageRegionSize.Fill( 1 );\n perThreadData.LineImageRegionSize[0] = fft1DSize;\n }\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::AddLineWindow( FFT1DSizeType length, LineWindowMapType & lineWindowMap )\n{\n if( lineWindowMap.count( length ) == 1 )\n {\n return;\n }\n \/\/ Currently using a Hamming Window\n SpectraVectorType window( length );\n ScalarType sum = NumericTraits< ScalarType >::ZeroValue();\n for( FFT1DSizeType sample = 0; sample < length; ++sample )\n {\n window[sample] = 0.54 + 0.46 * std::cos( (Math::twopi * sample) \/ (length - 1) );\n sum += window[sample];\n }\n for( FFT1DSizeType sample = 0; sample < length; ++sample )\n {\n window[sample] \/= sum;\n }\n lineWindowMap[length] = window;\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\ntypename Spectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >::SpectraLineType\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::ComputeSpectra( const IndexType & lineIndex, ThreadIdType threadId )\n{\n const InputImageType * input = this->GetInput();\n PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n\n const FFT1DSizeType fft1DSize = static_cast< FFT1DSizeType >( perThreadData.ComplexVector.size() );\n\n const typename InputImageType::RegionType lineRegion( lineIndex, perThreadData.LineImageRegionSize );\n InputImageIteratorType inputIt( input, lineRegion );\n inputIt.GoToBegin();\n perThreadData.ComplexVector.fill( 0 );\n typename ComplexVectorType::iterator complexVectorIt = perThreadData.ComplexVector.begin();\n typename SpectraVectorType::const_iterator windowIt = perThreadData.LineWindowMap[fft1DSize].begin();\n while( !inputIt.IsAtEnd() )\n {\n *complexVectorIt = inputIt.Value() * *windowIt;\n ++inputIt;\n ++complexVectorIt;\n ++windowIt;\n }\n FFT1DType fft1D( fft1DSize );\n fft1D.bwd_transform( perThreadData.ComplexVector );\n typename ComplexVectorType::const_iterator complexVectorConstIt = perThreadData.ComplexVector.begin();\n typename SpectraVectorType::iterator spectraVectorIt = perThreadData.SpectraVector.begin();\n \/\/ drop DC component\n ++complexVectorConstIt;\n const size_t highFreq = perThreadData.SpectraVector.size();\n for( size_t freq = 0; freq < highFreq; ++freq )\n {\n spectraVectorIt[freq] = std::real(*complexVectorConstIt * std::conj(*complexVectorConstIt));\n ++complexVectorConstIt;\n }\n return std::make_pair( lineIndex, perThreadData.SpectraVector );\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId )\n{\n OutputImageType * output = this->GetOutput();\n const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n\n typedef ImageLinearIteratorWithIndex< OutputImageType > OutputIteratorType;\n OutputIteratorType outputIt( output, outputRegionForThread );\n outputIt.SetDirection( 1 );\n\n const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n FFT1DSizeType fft1DSize = 32;\n ExposeMetaData< FFT1DSizeType >( dict, \"FFT1DSize\", fft1DSize );\n PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n this->AddLineWindow( fft1DSize, perThreadData.LineWindowMap );\n\n ComplexVectorType complexVector( fft1DSize );\n SpectraVectorType spectraVector( fft1DSize );\n typename InputImageType::SizeType lineImageRegionSize;\n lineImageRegionSize.Fill( 1 );\n lineImageRegionSize[0] = fft1DSize;\n vnl_fft_1d< ScalarType > fft1D( fft1DSize );\n SpectraLinesContainerType spectraLines;\n\n typedef ImageLinearConstIteratorWithIndex< SupportWindowImageType > SupportWindowIteratorType;\n SupportWindowIteratorType supportWindowIt( supportWindowImage, outputRegionForThread );\n supportWindowIt.SetDirection( 1 );\n\n for( outputIt.GoToBegin(), supportWindowIt.GoToBegin();\n !outputIt.IsAtEnd();\n outputIt.NextLine(), supportWindowIt.NextLine() )\n {\n spectraLines.clear();\n while( ! outputIt.IsAtEndOfLine() )\n {\n \/\/ Compute the per line spectra.\n const SupportWindowType & supportWindow = supportWindowIt.Value();\n if( spectraLines.size() == 0 ) \/\/ first window in this lateral direction\n {\n const typename SupportWindowType::const_iterator windowLineEnd = supportWindow.end();\n for( typename SupportWindowType::const_iterator windowLine = supportWindow.begin();\n windowLine != windowLineEnd;\n ++windowLine )\n {\n const IndexType & lineIndex = *windowLine;\n const SpectraLineType & spectraLine = this->ComputeSpectra( lineIndex, threadId );\n spectraLines.push_back( spectraLine );\n }\n }\n else \/\/ subsequent window along a line\n {\n const IndexValueType desiredFirstLine = supportWindow[0][1];\n while( spectraLines[0].first[1] < desiredFirstLine )\n {\n spectraLines.pop_front();\n }\n const typename SupportWindowType::const_iterator windowLineEnd = supportWindow.end();\n typename SpectraLinesContainerType::iterator spectraLinesIt = spectraLines.begin();\n const typename SpectraLinesContainerType::iterator spectraLinesEnd = spectraLines.end();\n for( typename SupportWindowType::const_iterator windowLine = supportWindow.begin();\n windowLine != windowLineEnd;\n ++windowLine )\n {\n const IndexType & lineIndex = *windowLine;\n if( spectraLinesIt == spectraLinesEnd ) \/\/ past the end of the previously processed lines\n {\n const SpectraLineType & spectraLine = this->ComputeSpectra( lineIndex, threadId );\n spectraLines.push_back( spectraLine );\n }\n else if( lineIndex[1] == (spectraLinesIt->first)[1] ) \/\/ one of the same lines that was previously computed\n {\n if( lineIndex[0] != (spectraLinesIt->first)[0] )\n {\n const SpectraLineType & spectraLine = this->ComputeSpectra( lineIndex, threadId );\n *spectraLinesIt = spectraLine;\n }\n ++spectraLinesIt;\n }\n else\n {\n itkExceptionMacro( \"Unexpected line\" );\n }\n }\n }\n\n const size_t spectraLinesCount = spectraLines.size();\n this->AddLineWindow( spectraLinesCount, perThreadData.LineWindowMap );\n typename OutputImageType::PixelType outputPixel;\n outputPixel.SetSize( fft1DSize );\n outputPixel.Fill( NumericTraits< ScalarType >::ZeroValue() );\n typename SpectraVectorType::const_iterator windowIt = perThreadData.LineWindowMap[spectraLinesCount].begin();\n for( size_t line = 0; line < spectraLinesCount; ++line )\n {\n typename SpectraVectorType::const_iterator spectraIt = spectraLines[line].second.begin();\n for( FFT1DSizeType sample = 0; sample < fft1DSize; ++sample )\n {\n outputPixel[sample] += *windowIt * *spectraIt;\n ++spectraIt;\n }\n ++windowIt;\n }\n outputIt.Set( outputPixel );\n\n ++outputIt;\n ++supportWindowIt;\n }\n }\n}\n\n\n} \/\/ end namespace itk\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \/\/ get(xxx)\n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nvector V[100010];\nbool visited[100010];\n\ntypedef tuple state;\n\nint main () {\n int N;\n cin >> N;\n for (auto i = 0; i < N-1; ++i) {\n int a, b;\n a--;\n b--;\n V[a].push_back(b);\n V[b].push_back(a);\n }\n stack S;\n S.push(state(0, 0));\n int parent;\n int D;\n fill(visited, visited+N, false);\n while (!S.empty()) {\n int now = get<0>(S.top());\n int d = get<1>(S.top());\n S.pop();\n if (!visited[now]) {\n visited[now] = true;\n if (now == N-1) {\n D = d;\n parent = now;\n break;\n }\n for (auto x : V[now]) {\n if (!visited[x]) {\n S.push(state(x, d+1));\n }\n }\n }\n }\n stack SS;\n SS.push(state(N-1, 0));\n int cnt = 0;\n fill(visited, visited+N, false); \n while (!SS.empty()) {\n int now = get<0>(SS.top());\n int d = get<1>(SS.top());\n S.pop();\n if (!visited[now]) {\n visited[now] = true;\n cnt++;\n for (auto x : V[now]) {\n if (!visited[x] && x != parent) {\n SS.push(state(x, d+1));\n }\n }\n } \n }\n int su = (D-1)\/2 + cnt - 1;\n int fa = N - 2 - fa;\n if (fa > su) {\n cout << \"Fennec\" << endl;\n } else {\n cout << \"Snuke\" << endl;\n }\n}\ntried D.cpp to 'D'#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \/\/ get(xxx)\n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nvector V[100010];\nbool visited[100010];\n\ntypedef tuple state;\n\nint main () {\n int N;\n cin >> N;\n for (auto i = 0; i < N-1; ++i) {\n int a, b;\n a--;\n b--;\n V[a].push_back(b);\n V[b].push_back(a);\n }\n stack S;\n S.push(state(0, 0));\n int parent;\n int D;\n fill(visited, visited+N, false);\n cerr << \"aaa\" << endl;\n while (!S.empty()) {\n int now = get<0>(S.top());\n int d = get<1>(S.top());\n S.pop();\n if (!visited[now]) {\n visited[now] = true;\n if (now == N-1) {\n D = d;\n parent = now;\n break;\n }\n for (auto x : V[now]) {\n if (!visited[x]) {\n S.push(state(x, d+1));\n }\n }\n }\n }\n stack SS;\n SS.push(state(N-1, 0));\n int cnt = 0;\n fill(visited, visited+N, false);\n cerr << \"aaa\" << endl;\n while (!SS.empty()) {\n int now = get<0>(SS.top());\n int d = get<1>(SS.top());\n S.pop();\n if (!visited[now]) {\n visited[now] = true;\n cnt++;\n for (auto x : V[now]) {\n if (!visited[x] && x != parent) {\n SS.push(state(x, d+1));\n }\n }\n } \n }\n int su = (D-1)\/2 + cnt - 1;\n int fa = N - 2 - fa;\n if (fa > su) {\n cout << \"Fennec\" << endl;\n } else {\n cout << \"Snuke\" << endl;\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \/\/ get(xxx)\n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \/\/ atoi(xxx)\n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint main () {\n auto start = std::chrono::system_clock::now();\n random_device rd;\n mt19937 mt(rd());\n int N;\n cin >> N;\n vector a(N+1, 0);\n for (auto i = 1; i <= N; ++i) {\n cin >> a[i];\n }\n for (auto i = N; i > N\/3; --i) {\n ll val = 0;\n for (auto j = 1; i*j <= N; ++j) {\n val += a[i*j];\n }\n if (val < 0) {\n for (auto j = 1; i*j <= N; ++j) {\n a[i*j] = 0;\n } \n }\n }\n \/*\n cerr << \"a : \";\n for (auto x : a) {\n cerr << x << \" \";\n }\n cerr << endl;\n *\/\n ll M = (1 << N\/3);\n uniform_int_distribution<> rand(0, (1 << M) - 1);\n ll ans = 0;\n while (true) {\n ll i = rand(mt);\n vector x = a;\n for (auto j = 0; j < M; ++j) {\n if (((i >> j) & 1) == 1) {\n int k = j+1;\n for (auto l = 1; k*l <= N; ++l) {\n x[k*l] = 0;\n } \n }\n }\n ll ret = 0;\n for (auto j = 1; j <= N; ++j) {\n ret += x[j];\n }\n if (ans < ret) {\n ans = ret;\n }\n auto end = std::chrono::system_clock::now();\n double timer = std::chrono::duration_cast(end-start).count();\n if (timer > 1900) break;\n }\n cout << ans << endl;\n}\nsubmit E.cpp to 'E - MUL' (arc085) [C++14 (GCC 5.4.1)]#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \/\/ get(xxx)\n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \/\/ atoi(xxx)\nusing namespace std;\n \n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if by my emacs. #if DEBUG == 1 ... #end\n \ntypedef long long ll;\n \n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n \n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n \nint main () {\n int N;\n cin >> N;\n vector a(N+1, 0);\n for (auto i = 1; i <= N; ++i) {\n cin >> a[i];\n }\n for (auto i = N; i > N\/3; --i) {\n ll val = 0;\n for (auto j = 1; i*j <= N; ++j) {\n val += a[i*j];\n }\n if (val < 0) {\n for (auto j = 1; i*j <= N; ++j) {\n a[i*j] = 0;\n } \n }\n }\n \/*\n cerr << \"a : \";\n for (auto x : a) {\n cerr << x << \" \";\n }\n cerr << endl;\n *\/\n int M = N\/6 + 1;\n \/\/cerr << \"M = \" << M << endl;\n ll ans = 0;\n for (auto i = 0; i < (1 << M); ++i) {\n vector x = a;\n for (auto j = 0; j < M; ++j) {\n if (((i >> j) & 1) == 1) {\n int k = j+1;\n for (auto l = 1; k*l <= N; ++l) {\n x[k*l] = 0;\n } \n }\n }\n \/*\n cerr << \"i = \" << i << \", x : \";\n for (auto y : x) {\n cerr << y << \" \";\n }\n cerr << endl;\n *\/\n for (auto j = N\/3; j >= M+1; --j) {\n ll val = 0;\n for (auto l = 1; l*j <= N; ++l) {\n val += x[l*j];\n }\n if (val < 0) {\n for (auto l = 1; l*j <= N; ++l) {\n x[l*j] = 0;\n } \n }\n }\n ll ret = 0;\n for (auto j = 1; j <= N; ++j) {\n ret += x[j];\n }\n ans = max(ans, ret);\n }\n cout << ans << endl;\n}\n<|endoftext|>"} {"text":"#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \/\/ get(xxx)\n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, K;\nint cnt[2000][2000][2];\nint sum[2000][2000][2];\n\nint main () {\n fill(&cnt[0][0][0], &cnt[0][0][0]+2000*2000*2, 0);\n cin >> N >> K;\n int white = 0;\n for (auto i = 0; i < N; ++i) {\n int x, y;\n char c;\n cin >> x >> y >> c;\n bool color = (c == 'W');\n int area = ((x\/K) + (y\/K))%2;\n x %= K;\n y %= K;\n if (color) {\n white++;\n cnt[x + K * area][y][0]++;\n cnt[x + K * (1-area)][y + K][0]++;\n } else {\n cnt[x + K * area][y][1]++; \n cnt[x + K * (1-area)][y + K][1]++; \n }\n }\n \/*\n for (auto k = 0; k < 2; ++k) {\n cerr << \"k = \" << k << endl;\n for (auto i = 0; i < 2 * K; ++i) {\n for (auto j = 0; j < 2 * K; ++j) {\n cerr << cnt[i][j][k] << \" \";\n }\n cerr << endl;\n } \n }\n *\/\n for (auto k = 0; k < 2; ++k) {\n for (auto i = 0; i < 2 * K; ++i) {\n for (auto j = 0; j < 2 * K; ++j) {\n sum[i][j][k] = cnt[i][j][k];\n }\n }\n for (auto i = 0; i < 2 * K; ++i) {\n for (auto j = 0; j < 2 * K-1; ++j) {\n sum[i][j+1][k] += sum[i][j][k];\n }\n }\n for (auto j = 0; j < 2 * K; ++j) {\n for (auto i = 0; i < 2 * K-1; ++i) {\n sum[i+1][j][k] += sum[i][j][k];\n }\n }\n }\n \/*\n for (auto k = 0; k < 2; ++k) {\n cerr << \"k = \" << k << endl;\n for (auto i = 0; i < 2 * K; ++i) {\n for (auto j = 0; j < 2 * K; ++j) {\n cerr << sum[i][j][k] << \" \";\n }\n cerr << endl;\n } \n }\n *\/\n int ans = 0;\n for (auto i = 0; i < K; ++i) {\n for (auto j = 0; j < K; ++j) {\n int x = i + K;\n int y = j + K;\n int w = sum[x][y][0] - sum[i][y][0] - sum[x][j][0] + sum[i][j][0];\n int b = sum[x][y][1] - sum[i][y][1] - sum[x][j][1] + sum[i][j][1];\n \/\/cerr << \"(\" << x << \", \" << y << \") = (\"\n \/\/ << w << \", \" << b << \")\" << endl;\n int c = white - w + b;\n ans = max(ans, c);\n }\n }\n cout << ans << endl;\n}\nsubmit D.cpp to 'D - Checker' (arc089) [C++14 (GCC 5.4.1)]#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \/\/ get(xxx)\n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, K;\nint cnt[2000][2000][2];\nint sum[2000][2000][2];\n\nint main () {\n fill(&cnt[0][0][0], &cnt[0][0][0]+2000*2000*2, 0);\n cin >> N >> K;\n int white = 0;\n for (auto i = 0; i < N; ++i) {\n int x, y;\n char c;\n cin >> x >> y >> c;\n bool color = (c == 'W');\n int area = ((x\/K) + (y\/K))%2;\n x %= K;\n y %= K;\n if (color) {\n white++;\n cnt[x + K * area][y][0]++;\n cnt[x + K * (1-area)][y + K][0]++;\n } else {\n cnt[x + K * area][y][1]++; \n cnt[x + K * (1-area)][y + K][1]++; \n }\n }\n#if DEBUG == 1\n for (auto k = 0; k < 2; ++k) {\n cerr << \"k = \" << k << endl;\n for (auto i = 0; i < 2 * K; ++i) {\n for (auto j = 0; j < 2 * K; ++j) {\n cerr << cnt[i][j][k] << \" \";\n }\n cerr << endl;\n } \n } \n#endif\n for (auto k = 0; k < 2; ++k) {\n for (auto i = 0; i < 2 * K; ++i) {\n for (auto j = 0; j < 2 * K; ++j) {\n sum[i][j][k] = cnt[i][j][k];\n }\n }\n for (auto i = 0; i < 2 * K; ++i) {\n for (auto j = 0; j < 2 * K-1; ++j) {\n sum[i][j+1][k] += sum[i][j][k];\n }\n }\n for (auto j = 0; j < 2 * K; ++j) {\n for (auto i = 0; i < 2 * K-1; ++i) {\n sum[i+1][j][k] += sum[i][j][k];\n }\n }\n }\n#if DEBUG == 1\n for (auto k = 0; k < 2; ++k) {\n cerr << \"k = \" << k << endl;\n for (auto i = 0; i < 2 * K; ++i) {\n for (auto j = 0; j < 2 * K; ++j) {\n cerr << sum[i][j][k] << \" \";\n }\n cerr << endl;\n } \n } \n#endif\n int ans = 0;\n for (auto i = 0; i < K; ++i) {\n for (auto j = 0; j < K; ++j) {\n int x = i + K;\n int y = j + K;\n int w = sum[x][y][0] - sum[i][y][0] - sum[x][j][0] + sum[i][j][0];\n int b = sum[x][y][1] - sum[i][y][1] - sum[x][j][1] + sum[i][j][1];\n#if DEBUG == 1\n cerr << \"(\" << x << \", \" << y << \") = (\"\n << w << \", \" << b << \")\" << endl;\n#endif\n int c = white - w + b;\n c = max(N-c, c);\n ans = max(ans, c);\n }\n }\n cout << ans << endl;\n}\n<|endoftext|>"} {"text":"\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-14 21:58:19\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint H, W;\nstring S[20];\ntypedef tuple P;\nvector> pairs;\n\nvoid dfs(vector

temp, vector used, int R)\n{\n if (R%2 == 1)\n {\n for (auto i = 0; i < H; i++)\n {\n if (!used[i])\n {\n vector n_used = used;\n n_used[i] = true;\n vector

n_temp = temp;\n n_temp.push_back(P(i, i));\n dfs(n_temp, n_used, R - 1);\n }\n }\n return;\n }\n if (R == 0)\n {\n reverse(temp.begin(), temp.end());\n pairs.push_back(temp);\n return;\n }\n assert(R >= 2);\n int first = -1;\n for (auto i = 0; i < H; i++)\n {\n if (!used[i])\n {\n first = i;\n used[i] = true;\n break;\n }\n }\n assert(first >= 0);\n for (auto i = 0; i < H; i++)\n {\n if (!used[i])\n {\n vector n_used = used;\n n_used[i] = true;\n vector

n_temp = temp;\n n_temp.push_back(P(first, i));\n dfs(n_temp, n_used, R - 2);\n }\n }\n}\n\nvector make_strings(vector

& V)\n{\n vector X;\n int N = V.size();\n for (auto i = 0; i < N; i++)\n {\n X.push_back(get<0>(V[i]));\n }\n for (auto i = N-1; i >= 0; i--)\n {\n if (i == N-1 && get<0>(V[i]) == get<1>(V[i]))\n {\n continue;\n }\n X.push_back(get<1>(V[i]));\n }\n vector res;\n for (auto j = 0; j < W; j++)\n {\n string str = \"\";\n for (auto i : X)\n {\n string t = {S[i][j]};\n str += t;\n }\n res.push_back(str);\n }\n return res;\n}\n\nvector reverse_strings(const vector& V)\n{\n vector res;\n for (auto x : V)\n {\n reverse(x.begin(), x.end());\n res.push_back(x);\n }\n return res;\n}\n\nint main()\n{\n cin >> H >> W;\n for (auto i = 0; i < H; i++)\n {\n cin >> S[i];\n }\n vector

emp_P;\n vector emp_used = vector(H, false);\n dfs(emp_P, emp_used, H);\n#if DEBUG == 1\n cerr << \"pairs.size() = \" << pairs.size() << endl;\n if (pairs.size() < 5)\n {\n for (auto V : pairs)\n {\n for (auto e : V)\n {\n cerr << \"[\" << get<0>(e) << \", \" << get<1>(e) << \"] \";\n }\n cerr << endl;\n }\n }\n#endif\n for (auto e : pairs)\n {\n vector V1 = make_strings(e);\n vector V2 = reverse_strings(V1);\n assert((int)V1.size() == W && (int)V2.size() == W);\n#if DEBUG == 1\n if (pairs.size() < 5)\n {\n for (auto x : V1)\n {\n cerr << x << \" \";\n }\n cerr << endl;\n for (auto x : V2)\n {\n cerr << x << \" \";\n }\n cerr << endl;\n }\n#endif\n vector used = vector(W, false);\n bool found = true;\n bool has_center = (W%2 == 0);\n for (auto i = 0; i < W; i++)\n {\n if (used[i])\n {\n continue;\n }\n found = false;\n used[i] = true;\n for (auto j = i + 1; j < W; j++)\n {\n if (!used[j] && V1[i] == V2[j])\n {\n used[j] = true;\n found = true;\n break;\n }\n }\n if (!has_center && V1[i] == V2[i])\n {\n has_center = true;\n found = true;\n }\n if (!found)\n {\n break;\n }\n }\n if (found)\n {\n cout << \"YES\" << endl;\n return 0;\n }\n }\n cout << \"NO\" << endl;\n}submit E.cpp to 'E - Symmetric Grid' (arc095) [C++14 (GCC 5.4.1)]\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-14 21:58:19\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint H, W;\nstring S[20];\ntypedef tuple P;\nvector> pairs;\n\nvoid dfs(vector

temp, vector used, int R)\n{\n if (R%2 == 1)\n {\n for (auto i = 0; i < H; i++)\n {\n if (!used[i])\n {\n vector n_used = used;\n n_used[i] = true;\n vector

n_temp = temp;\n n_temp.push_back(P(i, i));\n dfs(n_temp, n_used, R - 1);\n }\n }\n return;\n }\n if (R == 0)\n {\n reverse(temp.begin(), temp.end());\n pairs.push_back(temp);\n return;\n }\n assert(R >= 2);\n int first = -1;\n for (auto i = 0; i < H; i++)\n {\n if (!used[i])\n {\n first = i;\n used[i] = true;\n break;\n }\n }\n assert(first >= 0);\n for (auto i = 0; i < H; i++)\n {\n if (!used[i])\n {\n vector n_used = used;\n n_used[i] = true;\n vector

n_temp = temp;\n n_temp.push_back(P(first, i));\n dfs(n_temp, n_used, R - 2);\n }\n }\n}\n\nvector make_strings(vector

& V)\n{\n vector X;\n int N = V.size();\n for (auto i = 0; i < N; i++)\n {\n X.push_back(get<0>(V[i]));\n }\n for (auto i = N-1; i >= 0; i--)\n {\n if (i == N-1 && get<0>(V[i]) == get<1>(V[i]))\n {\n continue;\n }\n X.push_back(get<1>(V[i]));\n }\n vector res;\n for (auto j = 0; j < W; j++)\n {\n string str = \"\";\n for (auto i : X)\n {\n string t = {S[i][j]};\n str += t;\n }\n res.push_back(str);\n }\n return res;\n}\n\nvector reverse_strings(const vector& V)\n{\n vector res;\n for (auto x : V)\n {\n reverse(x.begin(), x.end());\n res.push_back(x);\n }\n return res;\n}\n\nint main()\n{\n cin >> H >> W;\n for (auto i = 0; i < H; i++)\n {\n cin >> S[i];\n }\n vector

emp_P;\n vector emp_used = vector(H, false);\n dfs(emp_P, emp_used, H);\n#if DEBUG == 1\n cerr << \"pairs.size() = \" << pairs.size() << endl;\n if (pairs.size() < 5)\n {\n for (auto V : pairs)\n {\n for (auto e : V)\n {\n cerr << \"[\" << get<0>(e) << \", \" << get<1>(e) << \"] \";\n }\n cerr << endl;\n }\n }\n#endif\n for (auto e : pairs)\n {\n vector V1 = make_strings(e);\n vector V2 = reverse_strings(V1);\n assert((int)V1.size() == W && (int)V2.size() == W);\n#if DEBUG == 1\n if (pairs.size() < 5)\n {\n for (auto x : V1)\n {\n cerr << x << \" \";\n }\n cerr << endl;\n for (auto x : V2)\n {\n cerr << x << \" \";\n }\n cerr << endl;\n }\n#endif\n vector used = vector(W, false);\n int cnt = 0;\n for (auto i = 0; i < W; i++)\n {\n if (used[i])\n {\n continue;\n }\n for (auto j = i + 1; j < W; j++)\n {\n if (!used[j] && V1[i] == V2[j])\n {\n used[i] = true;\n used[j] = true;\n cnt += 2;\n break;\n }\n }\n }\n if (W - cnt == 1)\n {\n for (auto i = 0; i < W; i++)\n {\n if (!used[i] && V1[i] == V2[i]) {\n used[i] = true;\n cnt++;\n break;\n }\n }\n }\n if (W == cnt)\n {\n cout << \"YES\" << endl;\n return 0;\n }\n }\n cout << \"NO\" << endl;\n}<|endoftext|>"} {"text":"\/**\n * File : A.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-15 20:56:39\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, T;\nint a[1010];\n\nint main()\n{\n cin >> N >> T;\n for (auto i = 0; i < N; i++)\n {\n cin >> a[i];\n }\n int now = 0;\n int ans = 0;\n while (now < N)\n {\n if (ans - a[now] > 0 && (ans - a[now])%T == 0)\n {\n now++;\n }\n ans++;\n }\n cout << ans << endl;\n}tried A.cpp to 'A'\/**\n * File : A.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-15 20:56:39\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, T;\nint a[1010];\n\nint main()\n{\n cin >> N >> T;\n for (auto i = 0; i < N; i++)\n {\n cin >> a[i];\n }\n int now = 0;\n int ans = 0;\n while (now < N)\n {\n if (ans - a[now] >= 0 && (ans - a[now]) % T == 0)\n {\n now++;\n }\n ans++;\n }\n cout << ans << endl;\n}<|endoftext|>"} {"text":"\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2018-5-26 21:42:14\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast(end_time-start_time).count();\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nclass BIT\n{ \/\/ index starts at 1.\npublic:\n int N;\n ll *data;\n\n BIT(int n) : N(n)\n {\n data = new ll[N + 1];\n for (auto i = 1; i <= N; ++i)\n {\n data[i] = 0;\n }\n }\n\n ~BIT()\n {\n delete[] data;\n }\n\n ll sum(int i)\n { \/\/ [1, i]\n ll s = 0;\n while (i > 0)\n {\n s += data[i];\n i -= i & -i;\n }\n return s;\n }\n\n ll sum(int a, int b)\n { \/\/ [a, b)\n return sum(b - 1) - sum(a - 1);\n }\n\n void add(int i, ll x)\n {\n while (i <= N)\n {\n data[i] += x;\n i += i & -i;\n }\n }\n\n void add(int i)\n {\n add(i, 1);\n }\n};\n\ntypedef pair P;\n\nint N;\nint K;\nint Q;\nint A[2010];\nvector

V;\nbool visited[2010];\n\nint main()\n{\n cin >> N >> K >> Q;\n for (auto i = 0; i < N; i++)\n {\n cin >> A[i];\n V.push_back(P(A[i], i));\n }\n sort(V.begin(), V.end());\n reverse(V.begin(), V.end());\n int ans = 1000000007;\n fill(visited, visited + 2010, false);\n for (auto i = 0; i < N; i++)\n {\n int k = V[i].second;\n visited[k] = true;\n int left[2010];\n int right[2010];\n int t = -1;\n for (auto j = 0; j < N; j++)\n {\n if (!visited[i])\n {\n t = i;\n }\n left[i] = t;\n }\n t = N;\n for (auto j = N; j >= 0; j--)\n {\n if (!visited[i])\n {\n t = i;\n }\n right[i] = t;\n }\n BIT bit(N + 1);\n int cnt[2010];\n for (auto j = 0; j <= i; j++)\n {\n k = V[k].second;\n bit.add(k);\n cnt[k] = bit.sum(left[k] + 1, right[k]);\n }\n int Y = V[i].first;\n int sel = 0;\n for (auto j = i; j >= 0; j--)\n {\n k = V[k].second;\n if (cnt[k] >= K)\n {\n sel++;\n if (sel == Q)\n {\n int X = V[j].first;\n ans = min(ans, X - Y);\n break;\n }\n }\n }\n }\n cout << ans << endl;\n}tried E.cpp to 'E'\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2018-5-26 21:42:14\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast(end_time-start_time).count();\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nclass BIT\n{ \/\/ index starts at 1.\npublic:\n int N;\n ll *data;\n\n BIT(int n) : N(n)\n {\n data = new ll[N + 1];\n for (auto i = 1; i <= N; ++i)\n {\n data[i] = 0;\n }\n }\n\n ~BIT()\n {\n delete[] data;\n }\n\n ll sum(int i)\n { \/\/ [1, i]\n ll s = 0;\n while (i > 0)\n {\n s += data[i];\n i -= i & -i;\n }\n return s;\n }\n\n ll sum(int a, int b)\n { \/\/ [a, b)\n return sum(b - 1) - sum(a - 1);\n }\n\n void add(int i, ll x)\n {\n while (i <= N)\n {\n data[i] += x;\n i += i & -i;\n }\n }\n\n void add(int i)\n {\n add(i, 1);\n }\n};\n\ntypedef pair P;\n\nint N;\nint K;\nint Q;\nint A[2010];\nvector

V;\nbool visited[2010];\n\nint main()\n{\n cin >> N >> K >> Q;\n for (auto i = 0; i < N; i++)\n {\n cin >> A[i];\n V.push_back(P(A[i], i));\n }\n sort(V.begin(), V.end());\n reverse(V.begin(), V.end());\n int ans = 1000000007;\n fill(visited, visited + 2010, false);\n for (auto i = 0; i < N; i++)\n {\n int k = V[i].second;\n visited[k] = true;\n int left[2010];\n int right[2010];\n int t = -1;\n for (auto j = 0; j < N; j++)\n {\n if (!visited[j])\n {\n t = j;\n }\n left[j] = t;\n }\n t = N;\n for (auto j = N; j >= 0; j--)\n {\n if (!visited[j])\n {\n t = j;\n }\n right[j] = t;\n }\n BIT bit(N + 1);\n int cnt[2010];\n for (auto j = 0; j <= i; j++)\n {\n k = V[k].second;\n bit.add(k);\n cnt[k] = bit.sum(left[k] + 1, right[k]);\n }\n int Y = V[i].first;\n int sel = 0;\n for (auto j = i; j >= 0; j--)\n {\n k = V[k].second;\n if (cnt[k] >= K)\n {\n sel++;\n if (sel == Q)\n {\n int X = V[j].first;\n ans = min(ans, X - Y);\n break;\n }\n }\n }\n }\n cout << ans << endl;\n}<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 5\/16\/2020, 6:32:30 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n int M, K;\n cin >> M >> K;\n if (M == 0)\n {\n cout << \"0 0\" << endl;\n }\n else if (M == 1)\n {\n if (K == 0)\n {\n cout << \"0 0 1 1\" << endl;\n }\n else\n {\n cout << \"-1\" << endl;\n }\n }\n else if (K >= (1 << M))\n {\n cout << \"-1\" << endl;\n }\n else\n {\n vector A;\n for (auto i = 0; i < (1 << M); ++i)\n {\n if (i == K)\n {\n continue;\n }\n A.push_back(i);\n }\n auto B{A};\n reverse(B.begin(), B.end());\n vector ans;\n copy(A.begin(), A.end(), back_inserter(ans));\n ans.push_back(K);\n copy(B.begin(), B.end(), back_inserter(ans));\n ans.push_back(K);\n for (auto it = ans.begin(); it != ans.end(); ++it)\n {\n cout << *it;\n if (it + 1 != ans.end())\n {\n cout << \" \";\n }\n else\n {\n cout << endl;\n }\n }\n }\n}\nsubmit F.cpp to 'F - XOR Matching' (abc126) [C++14 (GCC 5.4.1)]#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 5\/16\/2020, 6:32:30 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n int M, K;\n cin >> M >> K;\n if (K >= (1 << M))\n {\n cout << \"-1\" << endl;\n }\n else if (M == 0)\n {\n cout << \"0 0\" << endl;\n }\n else if (M == 1)\n {\n if (K == 0)\n {\n cout << \"0 0 1 1\" << endl;\n }\n else\n {\n cout << \"-1\" << endl;\n }\n }\n else\n {\n vector A;\n for (auto i = 0; i < (1 << M); ++i)\n {\n if (i == K)\n {\n continue;\n }\n A.push_back(i);\n }\n auto B{A};\n reverse(B.begin(), B.end());\n vector ans;\n copy(A.begin(), A.end(), back_inserter(ans));\n ans.push_back(K);\n copy(B.begin(), B.end(), back_inserter(ans));\n ans.push_back(K);\n for (auto it = ans.begin(); it != ans.end(); ++it)\n {\n cout << *it;\n if (it + 1 != ans.end())\n {\n cout << \" \";\n }\n else\n {\n cout << endl;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"#define DEBUG 1\n\n\/**\n * File : A.cpp\n * Author : Kazune Takahashi\n * Created : 2019-6-2 20:42:31\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntypedef long long ll;\n\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\n\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/*\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n*\/\n\n\/\/ const ll MOD = 1000000007;\n\nstring S;\nint A, B, C, D, N;\n\nbool solve(int X, int Y)\n{\n for (auto i = X; i < Y; i++)\n {\n if (S[i] == '#' && S[i + 1] == '#')\n {\n return false;\n }\n }\n return true;\n}\n\nbool solve2(int X, int Y, int Z, int W)\n{\n for (auto i = Z; i < W - 1; i++)\n {\n if ((i == 0 || S[i - 1] == '.') && S[i] == '.' && S[i + 1] == '.')\n {\n S[i] = '#';\n break;\n }\n }\n return solve(X, Y);\n}\n\nint main()\n{\n cin >> N >> A >> B >> C >> D >> S;\n A--;\n B--;\n C--;\n D--;\n if (C < B)\n {\n if (solve(A, B) && solve(C, D))\n {\n Yes();\n }\n No();\n }\n if (solve(C, D) && solve2(A, B, C, D))\n {\n Yes();\n }\n No();\n}tried A.cpp to 'A'#define DEBUG 1\n\n\/**\n * File : A.cpp\n * Author : Kazune Takahashi\n * Created : 2019-6-2 20:42:31\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntypedef long long ll;\n\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\n\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/*\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n*\/\n\n\/\/ const ll MOD = 1000000007;\n\nstring S;\nint A, B, C, D, N;\n\nbool solve(int X, int Y)\n{\n for (auto i = X; i < Y; i++)\n {\n if (S[i] == '#' && S[i + 1] == '#')\n {\n return false;\n }\n }\n return true;\n}\n\nbool solve2(int X, int Y, int Z, int W)\n{\n bool ok = false;\n for (auto i = Z; i < W - 1; i++)\n {\n if ((i == 0 || S[i - 1] == '.') && S[i] == '.' && S[i + 1] == '.')\n {\n S[i] = '#';\n ok = true;\n break;\n }\n }\n if (!ok)\n {\n return false;\n }\n return solve(X, Y);\n}\n\nint main()\n{\n cin >> N >> A >> B >> C >> D >> S;\n A--;\n B--;\n C--;\n D--;\n if (C < B)\n {\n if (solve(A, B) && solve(C, D))\n {\n Yes();\n }\n No();\n }\n if (solve(C, D) && solve2(A, B, C, D))\n {\n Yes();\n }\n No();\n}<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 5\/19\/2020, 3:57:45 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- LCA -----\n\ntemplate \nclass LCA\n{\n int N, root, L;\n vector> to;\n vector> co;\n vector dep;\n vector costs;\n vector> par;\n\npublic:\n LCA(int n) : N{n}, L{0}, to(n), co(n), dep(n), costs(n)\n {\n while ((1 << L) < N)\n {\n ++L;\n }\n par = vector>(N + 1, vector(L, N));\n }\n\n void add_edge(int a, int b, T c = 0)\n {\n to[a].push_back(b);\n co[a].push_back(c);\n to[b].push_back(a);\n co[b].push_back(c);\n }\n\n void init(int _root)\n {\n root = _root;\n dfs(root);\n for (auto i = 0; i < L - 1; i++)\n {\n for (auto v = 0; v < N; v++)\n {\n if (par[v][i] != -1)\n {\n par[v][i + 1] = par[par[v][i]][i];\n }\n }\n }\n }\n\n \/\/ LCA\n int operator()(int a, int b)\n {\n if (dep[a] > dep[b])\n {\n swap(a, b);\n }\n int gap = dep[b] - dep[a];\n for (auto i = L - 1; i >= 0; i--)\n {\n int len = 1 << i;\n if (gap >= len)\n {\n gap -= len;\n b = par[b][i];\n }\n }\n if (a == b)\n {\n return a;\n }\n for (auto i = L - 1; i >= 0; i--)\n {\n int na = par[a][i];\n int nb = par[b][i];\n if (na != nb)\n {\n a = na;\n b = nb;\n }\n }\n return par[a][0];\n }\n\n int depth(int a, int b)\n {\n int c = (*this)(a, b);\n return dep[a] + dep[b] - 2 * dep[c];\n }\n\n T cost(int a, int b)\n {\n int c = (*this)(a, b);\n return costs[a] + costs[b] - 2 * costs[c];\n }\n\nprivate:\n void dfs(int v, int d = 0, T c = 0, int p = -1)\n {\n if (p != -1)\n {\n par[v][0] = p;\n }\n dep[v] = d;\n costs[v] = c;\n for (auto i = 0u; i < to[v].size(); i++)\n {\n int u = to[v][i];\n if (u == p)\n {\n continue;\n }\n dfs(u, d + 1, c + co[v][i], v);\n }\n }\n};\n\n\/\/ ----- main() -----\n\nstruct Query\n{\n int id, color, y, coefficient;\n};\n\nstruct Edge\n{\n int src, dst, color, cost;\n};\n\nclass Solve\n{\n int N, Q;\n vector> V;\n vector> W;\n LCA lca;\n vector ans;\n vector sum, cnt;\n\npublic:\n Solve(int N, int Q) : N{N}, Q{Q}, V(N), W(Q), lca{N}, ans(Q), sum(N, 0), cnt(N, 0)\n {\n for (auto i = 0; i < N - 1; ++i)\n {\n int a, b, c, d;\n cin >> a >> b >> c >> d;\n --a;\n --b;\n V[a].push_back({a, b, c, d});\n V[b].push_back({b, a, c, d});\n lca.add_edge(a, b, d);\n }\n lca.init(0);\n for (auto i = 0; i < Q; ++i)\n {\n int x, y, u, v;\n cin >> x >> y >> u >> v;\n --x;\n --y;\n --u;\n --v;\n W[u].push_back({i, x, y, 1});\n W[v].push_back({i, x, y, 1});\n W[lca(u, v)].push_back({i, x, y, -2});\n ans[i] = lca.cost(u, v);\n }\n }\n\n void flush()\n {\n#if DEBUG == 1\n cerr << \"aaa\" << endl;\n#endif\n dfs();\n for (auto i = 0; i < Q; ++i)\n {\n cout << ans[i] << endl;\n }\n }\n\nprivate:\n void dfs(int u = 0, int p = -1)\n {\n#if DEBUG == 1\n cerr << \"u = \" << u << endl;\n#endif\n for (auto const &q : W[u])\n {\n ans[q.id] += q.coefficient * (-sum[q.color] + cnt[q.color] * q.y);\n }\n for (auto const &e : V[u])\n {\n if (e.dst == p)\n {\n continue;\n }\n sum[e.color] += e.cost;\n cnt[e.color]++;\n dfs(e.dst, u);\n sum[e.color] -= e.cost;\n cnt[e.color]--;\n }\n }\n};\n\nint main()\n{\n int N, Q;\n cin >> N >> Q;\n Solve solve(N, Q);\n solve.flush();\n}\ntried F.cpp to 'F'#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 5\/19\/2020, 3:57:45 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- LCA -----\n\ntemplate \nclass LCA\n{\n int N, root, L;\n vector> to;\n vector> co;\n vector dep;\n vector costs;\n vector> par;\n\npublic:\n LCA(int n) : N{n}, L{0}, to(n), co(n), dep(n), costs(n)\n {\n while ((1 << L) < N)\n {\n ++L;\n }\n par = vector>(N + 1, vector(L, N));\n }\n\n void add_edge(int a, int b, T c = 0)\n {\n to[a].push_back(b);\n co[a].push_back(c);\n to[b].push_back(a);\n co[b].push_back(c);\n }\n\n void init(int _root)\n {\n root = _root;\n dfs(root);\n for (auto i = 0; i < L - 1; i++)\n {\n for (auto v = 0; v < N; v++)\n {\n if (par[v][i] != -1)\n {\n par[v][i + 1] = par[par[v][i]][i];\n }\n }\n }\n }\n\n \/\/ LCA\n int operator()(int a, int b)\n {\n if (dep[a] > dep[b])\n {\n swap(a, b);\n }\n int gap = dep[b] - dep[a];\n for (auto i = L - 1; i >= 0; i--)\n {\n int len = 1 << i;\n if (gap >= len)\n {\n gap -= len;\n b = par[b][i];\n }\n }\n if (a == b)\n {\n return a;\n }\n for (auto i = L - 1; i >= 0; i--)\n {\n int na = par[a][i];\n int nb = par[b][i];\n if (na != nb)\n {\n a = na;\n b = nb;\n }\n }\n return par[a][0];\n }\n\n int depth(int a, int b)\n {\n int c = (*this)(a, b);\n return dep[a] + dep[b] - 2 * dep[c];\n }\n\n T cost(int a, int b)\n {\n int c = (*this)(a, b);\n return costs[a] + costs[b] - 2 * costs[c];\n }\n\nprivate:\n void dfs(int v, int d = 0, T c = 0, int p = -1)\n {\n if (p != -1)\n {\n par[v][0] = p;\n }\n dep[v] = d;\n costs[v] = c;\n for (auto i = 0u; i < to[v].size(); i++)\n {\n int u = to[v][i];\n if (u == p)\n {\n continue;\n }\n dfs(u, d + 1, c + co[v][i], v);\n }\n }\n};\n\n\/\/ ----- main() -----\n\nstruct Query\n{\n int id, color, y, coefficient;\n};\n\nstruct Edge\n{\n int src, dst, color, cost;\n};\n\nclass Solve\n{\n int N, Q;\n vector> V;\n vector> W;\n LCA lca;\n vector ans;\n vector sum, cnt;\n\npublic:\n Solve(int N, int Q) : N{N}, Q{Q}, V(N), W(Q), lca{N}, ans(Q), sum(N - 1, 0), cnt(N - 1, 0)\n {\n for (auto i = 0; i < N - 1; ++i)\n {\n int a, b, c, d;\n cin >> a >> b >> c >> d;\n --a;\n --b;\n V[a].push_back({a, b, c, d});\n V[b].push_back({b, a, c, d});\n lca.add_edge(a, b, d);\n }\n lca.init(0);\n for (auto i = 0; i < Q; ++i)\n {\n int x, y, u, v;\n cin >> x >> y >> u >> v;\n --x;\n --y;\n --u;\n --v;\n W[u].push_back({i, x, y, 1});\n W[v].push_back({i, x, y, 1});\n W[lca(u, v)].push_back({i, x, y, -2});\n ans[i] = lca.cost(u, v);\n#if DEBUG == 1\n cerr << \"ans[\" << i << \"] = \" << ans[i] << endl;\n#endif\n }\n }\n\n void flush()\n {\n#if DEBUG == 1\n cerr << \"aaa\" << endl;\n#endif\n dfs();\n for (auto i = 0; i < Q; ++i)\n {\n cout << ans[i] << endl;\n }\n }\n\nprivate:\n void dfs(int u = 0, int p = -1)\n {\n#if DEBUG == 1\n cerr << \"u = \" << u << endl;\n#endif\n for (auto const &q : W[u])\n {\n ans[q.id] += q.coefficient * (-sum[q.color] + cnt[q.color] * q.y);\n }\n for (auto const &e : V[u])\n {\n if (e.dst == p)\n {\n continue;\n }\n sum[e.color] += e.cost;\n cnt[e.color]++;\n dfs(e.dst, u);\n sum[e.color] -= e.cost;\n cnt[e.color]--;\n }\n }\n};\n\nint main()\n{\n int N, Q;\n cin >> N >> Q;\n Solve solve(N, Q);\n solve.flush();\n}\n<|endoftext|>"} {"text":"\/\/===-- X86AsmInstrumentation.cpp - Instrument X86 inline assembly 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 \"MCTargetDesc\/X86BaseInfo.h\"\n#include \"X86AsmInstrumentation.h\"\n#include \"X86Operand.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCInst.h\"\n#include \"llvm\/MC\/MCInstBuilder.h\"\n#include \"llvm\/MC\/MCInstrInfo.h\"\n#include \"llvm\/MC\/MCParser\/MCParsedAsmOperand.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCSubtargetInfo.h\"\n#include \"llvm\/MC\/MCTargetOptions.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n\nnamespace llvm {\nnamespace {\n\nstatic cl::opt ClAsanInstrumentAssembly(\n \"asan-instrument-assembly\",\n cl::desc(\"instrument assembly with AddressSanitizer checks\"), cl::Hidden,\n cl::init(false));\n\nbool IsStackReg(unsigned Reg) {\n return Reg == X86::RSP || Reg == X86::ESP || Reg == X86::SP;\n}\n\nstd::string FuncName(unsigned AccessSize, bool IsWrite) {\n return std::string(\"__sanitizer_sanitize_\") + (IsWrite ? \"store\" : \"load\") +\n (utostr(AccessSize));\n}\n\nclass X86AddressSanitizer : public X86AsmInstrumentation {\npublic:\n X86AddressSanitizer(const MCSubtargetInfo &STI) : STI(STI) {}\n virtual ~X86AddressSanitizer() {}\n\n \/\/ X86AsmInstrumentation implementation:\n virtual void InstrumentInstruction(\n const MCInst &Inst, SmallVectorImpl &Operands,\n MCContext &Ctx, const MCInstrInfo &MII, MCStreamer &Out) override {\n InstrumentMOV(Inst, Operands, Ctx, MII, Out);\n }\n\n \/\/ Should be implemented differently in x86_32 and x86_64 subclasses.\n virtual void InstrumentMemOperandImpl(X86Operand *Op, unsigned AccessSize,\n bool IsWrite, MCContext &Ctx,\n MCStreamer &Out) = 0;\n\n void InstrumentMemOperand(MCParsedAsmOperand *Op, unsigned AccessSize,\n bool IsWrite, MCContext &Ctx, MCStreamer &Out);\n void InstrumentMOV(const MCInst &Inst,\n SmallVectorImpl &Operands,\n MCContext &Ctx, const MCInstrInfo &MII, MCStreamer &Out);\n void EmitInstruction(MCStreamer &Out, const MCInst &Inst) {\n Out.EmitInstruction(Inst, STI);\n }\n\nprotected:\n const MCSubtargetInfo &STI;\n};\n\nvoid X86AddressSanitizer::InstrumentMemOperand(\n MCParsedAsmOperand *Op, unsigned AccessSize, bool IsWrite, MCContext &Ctx,\n MCStreamer &Out) {\n assert(Op && Op->isMem() && \"Op should be a memory operand.\");\n assert((AccessSize & (AccessSize - 1)) == 0 && AccessSize <= 16 &&\n \"AccessSize should be a power of two, less or equal than 16.\");\n\n X86Operand *MemOp = static_cast(Op);\n \/\/ FIXME: get rid of this limitation.\n if (IsStackReg(MemOp->getMemBaseReg()) || IsStackReg(MemOp->getMemIndexReg()))\n return;\n\n InstrumentMemOperandImpl(MemOp, AccessSize, IsWrite, Ctx, Out);\n}\n\nvoid X86AddressSanitizer::InstrumentMOV(\n const MCInst &Inst, SmallVectorImpl &Operands,\n MCContext &Ctx, const MCInstrInfo &MII, MCStreamer &Out) {\n \/\/ Access size in bytes.\n unsigned AccessSize = 0;\n\n switch (Inst.getOpcode()) {\n case X86::MOV8mi:\n case X86::MOV8mr:\n case X86::MOV8rm:\n AccessSize = 1;\n break;\n case X86::MOV16mi:\n case X86::MOV16mr:\n case X86::MOV16rm:\n AccessSize = 2;\n break;\n case X86::MOV32mi:\n case X86::MOV32mr:\n case X86::MOV32rm:\n AccessSize = 4;\n break;\n case X86::MOV64mi32:\n case X86::MOV64mr:\n case X86::MOV64rm:\n AccessSize = 8;\n break;\n case X86::MOVAPDmr:\n case X86::MOVAPSmr:\n case X86::MOVAPDrm:\n case X86::MOVAPSrm:\n AccessSize = 16;\n break;\n default:\n return;\n }\n\n const bool IsWrite = MII.get(Inst.getOpcode()).mayStore();\n for (unsigned Ix = 0; Ix < Operands.size(); ++Ix) {\n MCParsedAsmOperand *Op = Operands[Ix];\n if (Op && Op->isMem())\n InstrumentMemOperand(Op, AccessSize, IsWrite, Ctx, Out);\n }\n}\n\nclass X86AddressSanitizer32 : public X86AddressSanitizer {\npublic:\n X86AddressSanitizer32(const MCSubtargetInfo &STI)\n : X86AddressSanitizer(STI) {}\n virtual ~X86AddressSanitizer32() {}\n\n virtual void InstrumentMemOperandImpl(X86Operand *Op, unsigned AccessSize,\n bool IsWrite, MCContext &Ctx,\n MCStreamer &Out) override;\n};\n\nvoid X86AddressSanitizer32::InstrumentMemOperandImpl(\n X86Operand *Op, unsigned AccessSize, bool IsWrite, MCContext &Ctx,\n MCStreamer &Out) {\n \/\/ FIXME: emit .cfi directives for correct stack unwinding.\n EmitInstruction(Out, MCInstBuilder(X86::PUSH32r).addReg(X86::EAX));\n {\n MCInst Inst;\n Inst.setOpcode(X86::LEA32r);\n Inst.addOperand(MCOperand::CreateReg(X86::EAX));\n Op->addMemOperands(Inst, 5);\n EmitInstruction(Out, Inst);\n }\n EmitInstruction(Out, MCInstBuilder(X86::PUSH32r).addReg(X86::EAX));\n {\n const std::string Func = FuncName(AccessSize, IsWrite);\n const MCSymbol *FuncSym = Ctx.GetOrCreateSymbol(StringRef(Func));\n const MCSymbolRefExpr *FuncExpr =\n MCSymbolRefExpr::Create(FuncSym, MCSymbolRefExpr::VK_PLT, Ctx);\n EmitInstruction(Out, MCInstBuilder(X86::CALLpcrel32).addExpr(FuncExpr));\n }\n EmitInstruction(Out, MCInstBuilder(X86::ADD32ri).addReg(X86::ESP)\n .addReg(X86::ESP).addImm(4));\n EmitInstruction(Out, MCInstBuilder(X86::POP32r).addReg(X86::EAX));\n}\n\nclass X86AddressSanitizer64 : public X86AddressSanitizer {\npublic:\n X86AddressSanitizer64(const MCSubtargetInfo &STI)\n : X86AddressSanitizer(STI) {}\n virtual ~X86AddressSanitizer64() {}\n\n virtual void InstrumentMemOperandImpl(X86Operand *Op, unsigned AccessSize,\n bool IsWrite, MCContext &Ctx,\n MCStreamer &Out) override;\n};\n\nvoid X86AddressSanitizer64::InstrumentMemOperandImpl(X86Operand *Op,\n unsigned AccessSize,\n bool IsWrite,\n MCContext &Ctx,\n MCStreamer &Out) {\n \/\/ FIXME: emit .cfi directives for correct stack unwinding.\n\n \/\/ Set %rsp below current red zone (128 bytes wide) using LEA instruction to\n \/\/ preserve flags.\n {\n MCInst Inst;\n Inst.setOpcode(X86::LEA64r);\n Inst.addOperand(MCOperand::CreateReg(X86::RSP));\n\n const MCExpr *Disp = MCConstantExpr::Create(-128, Ctx);\n std::unique_ptr Op(\n X86Operand::CreateMem(0, Disp, X86::RSP, 0, 1, SMLoc(), SMLoc()));\n Op->addMemOperands(Inst, 5);\n EmitInstruction(Out, Inst);\n }\n EmitInstruction(Out, MCInstBuilder(X86::PUSH64r).addReg(X86::RDI));\n {\n MCInst Inst;\n Inst.setOpcode(X86::LEA64r);\n Inst.addOperand(MCOperand::CreateReg(X86::RDI));\n Op->addMemOperands(Inst, 5);\n EmitInstruction(Out, Inst);\n }\n {\n const std::string Func = FuncName(AccessSize, IsWrite);\n const MCSymbol *FuncSym = Ctx.GetOrCreateSymbol(StringRef(Func));\n const MCSymbolRefExpr *FuncExpr =\n MCSymbolRefExpr::Create(FuncSym, MCSymbolRefExpr::VK_PLT, Ctx);\n EmitInstruction(Out, MCInstBuilder(X86::CALL64pcrel32).addExpr(FuncExpr));\n }\n EmitInstruction(Out, MCInstBuilder(X86::POP64r).addReg(X86::RDI));\n\n \/\/ Restore old %rsp value.\n {\n MCInst Inst;\n Inst.setOpcode(X86::LEA64r);\n Inst.addOperand(MCOperand::CreateReg(X86::RSP));\n\n const MCExpr *Disp = MCConstantExpr::Create(128, Ctx);\n std::unique_ptr Op(\n X86Operand::CreateMem(0, Disp, X86::RSP, 0, 1, SMLoc(), SMLoc()));\n Op->addMemOperands(Inst, 5);\n EmitInstruction(Out, Inst);\n }\n}\n\n} \/\/ End anonymous namespace\n\nX86AsmInstrumentation::X86AsmInstrumentation() {}\nX86AsmInstrumentation::~X86AsmInstrumentation() {}\n\nvoid X86AsmInstrumentation::InstrumentInstruction(\n const MCInst &Inst, SmallVectorImpl &Operands,\n MCContext &Ctx, const MCInstrInfo &MII, MCStreamer &Out) {}\n\nX86AsmInstrumentation *\nCreateX86AsmInstrumentation(const MCTargetOptions &MCOptions,\n const MCContext &Ctx, const MCSubtargetInfo &STI) {\n Triple T(STI.getTargetTriple());\n const bool hasCompilerRTSupport = T.isOSLinux();\n if (ClAsanInstrumentAssembly && hasCompilerRTSupport &&\n MCOptions.SanitizeAddress) {\n if ((STI.getFeatureBits() & X86::Mode32Bit) != 0)\n return new X86AddressSanitizer32(STI);\n if ((STI.getFeatureBits() & X86::Mode64Bit) != 0)\n return new X86AddressSanitizer64(STI);\n }\n return new X86AsmInstrumentation();\n}\n\n} \/\/ End llvm namespace\n[asan] Fix x86-32 asm instrumentation to preserve flags.\/\/===-- X86AsmInstrumentation.cpp - Instrument X86 inline assembly 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 \"MCTargetDesc\/X86BaseInfo.h\"\n#include \"X86AsmInstrumentation.h\"\n#include \"X86Operand.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCInst.h\"\n#include \"llvm\/MC\/MCInstBuilder.h\"\n#include \"llvm\/MC\/MCInstrInfo.h\"\n#include \"llvm\/MC\/MCParser\/MCParsedAsmOperand.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCSubtargetInfo.h\"\n#include \"llvm\/MC\/MCTargetOptions.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n\nnamespace llvm {\nnamespace {\n\nstatic cl::opt ClAsanInstrumentAssembly(\n \"asan-instrument-assembly\",\n cl::desc(\"instrument assembly with AddressSanitizer checks\"), cl::Hidden,\n cl::init(false));\n\nbool IsStackReg(unsigned Reg) {\n return Reg == X86::RSP || Reg == X86::ESP || Reg == X86::SP;\n}\n\nstd::string FuncName(unsigned AccessSize, bool IsWrite) {\n return std::string(\"__sanitizer_sanitize_\") + (IsWrite ? \"store\" : \"load\") +\n (utostr(AccessSize));\n}\n\nclass X86AddressSanitizer : public X86AsmInstrumentation {\npublic:\n X86AddressSanitizer(const MCSubtargetInfo &STI) : STI(STI) {}\n virtual ~X86AddressSanitizer() {}\n\n \/\/ X86AsmInstrumentation implementation:\n virtual void InstrumentInstruction(\n const MCInst &Inst, SmallVectorImpl &Operands,\n MCContext &Ctx, const MCInstrInfo &MII, MCStreamer &Out) override {\n InstrumentMOV(Inst, Operands, Ctx, MII, Out);\n }\n\n \/\/ Should be implemented differently in x86_32 and x86_64 subclasses.\n virtual void InstrumentMemOperandImpl(X86Operand *Op, unsigned AccessSize,\n bool IsWrite, MCContext &Ctx,\n MCStreamer &Out) = 0;\n\n void InstrumentMemOperand(MCParsedAsmOperand *Op, unsigned AccessSize,\n bool IsWrite, MCContext &Ctx, MCStreamer &Out);\n void InstrumentMOV(const MCInst &Inst,\n SmallVectorImpl &Operands,\n MCContext &Ctx, const MCInstrInfo &MII, MCStreamer &Out);\n void EmitInstruction(MCStreamer &Out, const MCInst &Inst) {\n Out.EmitInstruction(Inst, STI);\n }\n\nprotected:\n const MCSubtargetInfo &STI;\n};\n\nvoid X86AddressSanitizer::InstrumentMemOperand(\n MCParsedAsmOperand *Op, unsigned AccessSize, bool IsWrite, MCContext &Ctx,\n MCStreamer &Out) {\n assert(Op && Op->isMem() && \"Op should be a memory operand.\");\n assert((AccessSize & (AccessSize - 1)) == 0 && AccessSize <= 16 &&\n \"AccessSize should be a power of two, less or equal than 16.\");\n\n X86Operand *MemOp = static_cast(Op);\n \/\/ FIXME: get rid of this limitation.\n if (IsStackReg(MemOp->getMemBaseReg()) || IsStackReg(MemOp->getMemIndexReg()))\n return;\n\n InstrumentMemOperandImpl(MemOp, AccessSize, IsWrite, Ctx, Out);\n}\n\nvoid X86AddressSanitizer::InstrumentMOV(\n const MCInst &Inst, SmallVectorImpl &Operands,\n MCContext &Ctx, const MCInstrInfo &MII, MCStreamer &Out) {\n \/\/ Access size in bytes.\n unsigned AccessSize = 0;\n\n switch (Inst.getOpcode()) {\n case X86::MOV8mi:\n case X86::MOV8mr:\n case X86::MOV8rm:\n AccessSize = 1;\n break;\n case X86::MOV16mi:\n case X86::MOV16mr:\n case X86::MOV16rm:\n AccessSize = 2;\n break;\n case X86::MOV32mi:\n case X86::MOV32mr:\n case X86::MOV32rm:\n AccessSize = 4;\n break;\n case X86::MOV64mi32:\n case X86::MOV64mr:\n case X86::MOV64rm:\n AccessSize = 8;\n break;\n case X86::MOVAPDmr:\n case X86::MOVAPSmr:\n case X86::MOVAPDrm:\n case X86::MOVAPSrm:\n AccessSize = 16;\n break;\n default:\n return;\n }\n\n const bool IsWrite = MII.get(Inst.getOpcode()).mayStore();\n for (unsigned Ix = 0; Ix < Operands.size(); ++Ix) {\n MCParsedAsmOperand *Op = Operands[Ix];\n if (Op && Op->isMem())\n InstrumentMemOperand(Op, AccessSize, IsWrite, Ctx, Out);\n }\n}\n\nclass X86AddressSanitizer32 : public X86AddressSanitizer {\npublic:\n X86AddressSanitizer32(const MCSubtargetInfo &STI)\n : X86AddressSanitizer(STI) {}\n virtual ~X86AddressSanitizer32() {}\n\n virtual void InstrumentMemOperandImpl(X86Operand *Op, unsigned AccessSize,\n bool IsWrite, MCContext &Ctx,\n MCStreamer &Out) override;\n};\n\nvoid X86AddressSanitizer32::InstrumentMemOperandImpl(\n X86Operand *Op, unsigned AccessSize, bool IsWrite, MCContext &Ctx,\n MCStreamer &Out) {\n \/\/ FIXME: emit .cfi directives for correct stack unwinding.\n EmitInstruction(Out, MCInstBuilder(X86::PUSH32r).addReg(X86::EAX));\n {\n MCInst Inst;\n Inst.setOpcode(X86::LEA32r);\n Inst.addOperand(MCOperand::CreateReg(X86::EAX));\n Op->addMemOperands(Inst, 5);\n EmitInstruction(Out, Inst);\n }\n EmitInstruction(Out, MCInstBuilder(X86::PUSH32r).addReg(X86::EAX));\n {\n const std::string Func = FuncName(AccessSize, IsWrite);\n const MCSymbol *FuncSym = Ctx.GetOrCreateSymbol(StringRef(Func));\n const MCSymbolRefExpr *FuncExpr =\n MCSymbolRefExpr::Create(FuncSym, MCSymbolRefExpr::VK_PLT, Ctx);\n EmitInstruction(Out, MCInstBuilder(X86::CALLpcrel32).addExpr(FuncExpr));\n }\n EmitInstruction(Out, MCInstBuilder(X86::POP32r).addReg(X86::EAX));\n EmitInstruction(Out, MCInstBuilder(X86::POP32r).addReg(X86::EAX));\n}\n\nclass X86AddressSanitizer64 : public X86AddressSanitizer {\npublic:\n X86AddressSanitizer64(const MCSubtargetInfo &STI)\n : X86AddressSanitizer(STI) {}\n virtual ~X86AddressSanitizer64() {}\n\n virtual void InstrumentMemOperandImpl(X86Operand *Op, unsigned AccessSize,\n bool IsWrite, MCContext &Ctx,\n MCStreamer &Out) override;\n};\n\nvoid X86AddressSanitizer64::InstrumentMemOperandImpl(X86Operand *Op,\n unsigned AccessSize,\n bool IsWrite,\n MCContext &Ctx,\n MCStreamer &Out) {\n \/\/ FIXME: emit .cfi directives for correct stack unwinding.\n\n \/\/ Set %rsp below current red zone (128 bytes wide) using LEA instruction to\n \/\/ preserve flags.\n {\n MCInst Inst;\n Inst.setOpcode(X86::LEA64r);\n Inst.addOperand(MCOperand::CreateReg(X86::RSP));\n\n const MCExpr *Disp = MCConstantExpr::Create(-128, Ctx);\n std::unique_ptr Op(\n X86Operand::CreateMem(0, Disp, X86::RSP, 0, 1, SMLoc(), SMLoc()));\n Op->addMemOperands(Inst, 5);\n EmitInstruction(Out, Inst);\n }\n EmitInstruction(Out, MCInstBuilder(X86::PUSH64r).addReg(X86::RDI));\n {\n MCInst Inst;\n Inst.setOpcode(X86::LEA64r);\n Inst.addOperand(MCOperand::CreateReg(X86::RDI));\n Op->addMemOperands(Inst, 5);\n EmitInstruction(Out, Inst);\n }\n {\n const std::string Func = FuncName(AccessSize, IsWrite);\n const MCSymbol *FuncSym = Ctx.GetOrCreateSymbol(StringRef(Func));\n const MCSymbolRefExpr *FuncExpr =\n MCSymbolRefExpr::Create(FuncSym, MCSymbolRefExpr::VK_PLT, Ctx);\n EmitInstruction(Out, MCInstBuilder(X86::CALL64pcrel32).addExpr(FuncExpr));\n }\n EmitInstruction(Out, MCInstBuilder(X86::POP64r).addReg(X86::RDI));\n\n \/\/ Restore old %rsp value.\n {\n MCInst Inst;\n Inst.setOpcode(X86::LEA64r);\n Inst.addOperand(MCOperand::CreateReg(X86::RSP));\n\n const MCExpr *Disp = MCConstantExpr::Create(128, Ctx);\n std::unique_ptr Op(\n X86Operand::CreateMem(0, Disp, X86::RSP, 0, 1, SMLoc(), SMLoc()));\n Op->addMemOperands(Inst, 5);\n EmitInstruction(Out, Inst);\n }\n}\n\n} \/\/ End anonymous namespace\n\nX86AsmInstrumentation::X86AsmInstrumentation() {}\nX86AsmInstrumentation::~X86AsmInstrumentation() {}\n\nvoid X86AsmInstrumentation::InstrumentInstruction(\n const MCInst &Inst, SmallVectorImpl &Operands,\n MCContext &Ctx, const MCInstrInfo &MII, MCStreamer &Out) {}\n\nX86AsmInstrumentation *\nCreateX86AsmInstrumentation(const MCTargetOptions &MCOptions,\n const MCContext &Ctx, const MCSubtargetInfo &STI) {\n Triple T(STI.getTargetTriple());\n const bool hasCompilerRTSupport = T.isOSLinux();\n if (ClAsanInstrumentAssembly && hasCompilerRTSupport &&\n MCOptions.SanitizeAddress) {\n if ((STI.getFeatureBits() & X86::Mode32Bit) != 0)\n return new X86AddressSanitizer32(STI);\n if ((STI.getFeatureBits() & X86::Mode64Bit) != 0)\n return new X86AddressSanitizer64(STI);\n }\n return new X86AsmInstrumentation();\n}\n\n} \/\/ End llvm namespace\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 6\/2\/2020, 1:13:26 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nll MOD;\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\nclass Combination\n{\npublic:\n vector inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nCombination C;\n\nvector delta(int i)\n{\n vector ans(MOD, 0);\n ans[0] = 1;\n mint base{-i};\n for (auto j = 0; j < MOD; ++j)\n {\n ans[MOD - 1 - j] -= C(MOD - 1, j) * base.power(j);\n }\n return ans;\n}\n\nint main()\n{\n cin >> MOD;\n C = Combination();\n vector A(MOD);\n#if DEBUG == 1\n cerr << \"Here\" << endl;\n#endif\n for (auto i = 0; i < MOD; ++i)\n {\n cin >> A[i];\n }\n vector B(MOD, 0);\n for (auto i = 0; i < MOD; ++i)\n {\n auto V{delta(i)};\n for (auto j = 0; j < MOD; ++j)\n {\n B[j] += A[i] * V[j];\n }\n }\n for (auto i = 0; i < MOD; ++i)\n {\n cout << B[i];\n if (i < MOD - 1)\n {\n cout << \" \";\n }\n else\n {\n cout << endl;\n }\n }\n}\ntried F.cpp to 'F'#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 6\/2\/2020, 1:13:26 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nll MOD;\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\nclass Combination\n{\npublic:\n vector inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nCombination C;\n\nvector delta(int i)\n{\n vector ans(MOD, 0);\n ans[0] = 1;\n mint base{-i};\n for (auto j = 0; j < MOD; ++j)\n {\n ans[MOD - 1 - j] -= C(MOD - 1, j) * base.power(j);\n }\n return ans;\n}\n\nint main()\n{\n cin >> MOD;\n#if DEBUG == 1\n cerr << \"Here\" << endl;\n#endif\n C = Combination();\n#if DEBUG == 1\n cerr << \"Here\" << endl;\n#endif\n vector A(MOD);\n for (auto i = 0; i < MOD; ++i)\n {\n cin >> A[i];\n }\n vector B(MOD, 0);\n for (auto i = 0; i < MOD; ++i)\n {\n auto V{delta(i)};\n for (auto j = 0; j < MOD; ++j)\n {\n B[j] += A[i] * V[j];\n }\n }\n for (auto i = 0; i < MOD; ++i)\n {\n cout << B[i];\n if (i < MOD - 1)\n {\n cout << \" \";\n }\n else\n {\n cout << endl;\n }\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: DBTypeWizDlgSetup.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: pjunck $ $Date: 2004-10-27 13:10:02 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _DBU_REGHELPER_HXX_\n#include \"dbu_reghelper.hxx\"\n#endif\n#ifndef DBAUI_DBTYPEWIZDLGSETUP_HXX\n#include \"DBTypeWizDlgSetup.hxx\"\n#endif\n#ifndef DBAUI_DBWIZSETUP_HXX\n#include \"dbwizsetup.hxx\"\n#endif\n\nusing namespace dbaui;\n\nextern \"C\" void SAL_CALL createRegistryInfo_ODBTypeWizDialogSetup()\n{\n static OMultiInstanceAutoRegistration< ODBTypeWizDialogSetup > aAutoRegistration;\n}\n\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::beans;\n\n\/\/=========================================================================\n\/\/-------------------------------------------------------------------------\nODBTypeWizDialogSetup::ODBTypeWizDialogSetup(const Reference< XMultiServiceFactory >& _rxORB)\n :ODatabaseAdministrationDialog(_rxORB)\n{\n}\n\/\/-------------------------------------------------------------------------\nSequence SAL_CALL ODBTypeWizDialogSetup::getImplementationId( ) throw(RuntimeException)\n{\n static ::cppu::OImplementationId aId;\n return aId.getImplementationId();\n}\n\n\/\/-------------------------------------------------------------------------\nReference< XInterface > SAL_CALL ODBTypeWizDialogSetup::Create(const Reference< XMultiServiceFactory >& _rxFactory)\n{\n Reference < XInterface > xDBContext = _rxFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.sdb.DatabaseDocument\")));\n Sequence aSequence(1);\n PropertyValue aPropertyValue;\n Any aTmp;\n aTmp <<= xDBContext;\n aPropertyValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"InitialSelection\"));\n aPropertyValue.Value = aTmp;\n aSequence[0] <<= aPropertyValue;\n Reference < XInterface > xDBWizard = *(new ODBTypeWizDialogSetup(_rxFactory));\n Reference < XInitialization > xDBWizardInit(xDBWizard, UNO_QUERY);\n\n xDBWizardInit->initialize(aSequence);\n Reference xDBWizardExecute( xDBWizard, UNO_QUERY );\n xDBWizardExecute->execute();\n return xDBWizard;\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString SAL_CALL ODBTypeWizDialogSetup::getImplementationName() throw(RuntimeException)\n{\n return getImplementationName_Static();\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString ODBTypeWizDialogSetup::getImplementationName_Static() throw(RuntimeException)\n{\n return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"org.openoffice.comp.dbu.ODBTypeWizDialogSetup\"));\n}\n\n\/\/-------------------------------------------------------------------------\n::comphelper::StringSequence SAL_CALL ODBTypeWizDialogSetup::getSupportedServiceNames() throw(RuntimeException)\n{\n return getSupportedServiceNames_Static();\n}\n\n\/\/-------------------------------------------------------------------------\n::comphelper::StringSequence ODBTypeWizDialogSetup::getSupportedServiceNames_Static() throw(RuntimeException)\n{\n ::comphelper::StringSequence aSupported(1);\n aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.sdb.DatabaseWizardDialog\"));\n return aSupported;\n}\n\n\/\/-------------------------------------------------------------------------\nReference SAL_CALL ODBTypeWizDialogSetup::getPropertySetInfo() throw(RuntimeException)\n{\n Reference xInfo( createPropertySetInfo( getInfoHelper() ) );\n return xInfo;\n}\n\n\/\/-------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper& ODBTypeWizDialogSetup::getInfoHelper()\n{\n return *const_cast(this)->getArrayHelper();\n}\n\n\/\/------------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper* ODBTypeWizDialogSetup::createArrayHelper( ) const\n{\n Sequence< Property > aProps;\n describeProperties(aProps);\n return new ::cppu::OPropertyArrayHelper(aProps);\n}\n\/\/------------------------------------------------------------------------------\nDialog* ODBTypeWizDialogSetup::createDialog(Window* _pParent)\n{\n ODbTypeWizDialogSetup* pDlg = new ODbTypeWizDialogSetup(_pParent, m_pDatasourceItems, m_xORB, m_aInitialSelection);\n return pDlg;\n}\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n\nINTEGRATION: CWS imprec01 (1.2.40); FILE MERGED 2005\/01\/11 13:59:36 oj 1.2.40.1: #i39228# send document events\/*************************************************************************\n *\n * $RCSfile: DBTypeWizDlgSetup.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-02-02 14:00:23 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _DBU_REGHELPER_HXX_\n#include \"dbu_reghelper.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_\n#include \n#endif\n#ifndef DBAUI_DBTYPEWIZDLGSETUP_HXX\n#include \"DBTypeWizDlgSetup.hxx\"\n#endif\n#ifndef DBAUI_DBWIZSETUP_HXX\n#include \"dbwizsetup.hxx\"\n#endif\n\nusing namespace dbaui;\n\nextern \"C\" void SAL_CALL createRegistryInfo_ODBTypeWizDialogSetup()\n{\n static OMultiInstanceAutoRegistration< ODBTypeWizDialogSetup > aAutoRegistration;\n}\n\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::beans;\n\n\/\/=========================================================================\n\/\/-------------------------------------------------------------------------\nODBTypeWizDialogSetup::ODBTypeWizDialogSetup(const Reference< XMultiServiceFactory >& _rxORB)\n :ODatabaseAdministrationDialog(_rxORB)\n{\n}\n\/\/-------------------------------------------------------------------------\nSequence SAL_CALL ODBTypeWizDialogSetup::getImplementationId( ) throw(RuntimeException)\n{\n static ::cppu::OImplementationId aId;\n return aId.getImplementationId();\n}\n\n\/\/-------------------------------------------------------------------------\nReference< XInterface > SAL_CALL ODBTypeWizDialogSetup::Create(const Reference< XMultiServiceFactory >& _rxFactory)\n{\n Reference < XInterface > xDBContext = _rxFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.sdb.DatabaseDocument\")));\n Sequence aSequence(1);\n PropertyValue aPropertyValue;\n Any aTmp;\n aTmp <<= xDBContext;\n aPropertyValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"InitialSelection\"));\n aPropertyValue.Value = aTmp;\n aSequence[0] <<= aPropertyValue;\n Reference < XInterface > xDBWizard = *(new ODBTypeWizDialogSetup(_rxFactory));\n Reference < XInitialization > xDBWizardInit(xDBWizard, UNO_QUERY);\n\n xDBWizardInit->initialize(aSequence);\n\n try\n {\n Reference< ::com::sun::star::document::XEventListener > xDocEventBroadcaster(_rxFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.frame.GlobalEventBroadcaster\"))),\n UNO_QUERY);\n if ( xDocEventBroadcaster.is() )\n {\n ::com::sun::star::document::EventObject aEvent(xDBContext, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"OnNew\")) );\n xDocEventBroadcaster->notifyEvent(aEvent);\n }\n }\n catch(Exception)\n {\n OSL_ENSURE(0,\"Could not create GlobalEventBroadcaster!\");\n }\n Reference xDBWizardExecute( xDBWizard, UNO_QUERY );\n xDBWizardExecute->execute();\n return xDBWizard;\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString SAL_CALL ODBTypeWizDialogSetup::getImplementationName() throw(RuntimeException)\n{\n return getImplementationName_Static();\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString ODBTypeWizDialogSetup::getImplementationName_Static() throw(RuntimeException)\n{\n return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"org.openoffice.comp.dbu.ODBTypeWizDialogSetup\"));\n}\n\n\/\/-------------------------------------------------------------------------\n::comphelper::StringSequence SAL_CALL ODBTypeWizDialogSetup::getSupportedServiceNames() throw(RuntimeException)\n{\n return getSupportedServiceNames_Static();\n}\n\n\/\/-------------------------------------------------------------------------\n::comphelper::StringSequence ODBTypeWizDialogSetup::getSupportedServiceNames_Static() throw(RuntimeException)\n{\n ::comphelper::StringSequence aSupported(1);\n aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.sdb.DatabaseWizardDialog\"));\n return aSupported;\n}\n\n\/\/-------------------------------------------------------------------------\nReference SAL_CALL ODBTypeWizDialogSetup::getPropertySetInfo() throw(RuntimeException)\n{\n Reference xInfo( createPropertySetInfo( getInfoHelper() ) );\n return xInfo;\n}\n\n\/\/-------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper& ODBTypeWizDialogSetup::getInfoHelper()\n{\n return *const_cast(this)->getArrayHelper();\n}\n\n\/\/------------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper* ODBTypeWizDialogSetup::createArrayHelper( ) const\n{\n Sequence< Property > aProps;\n describeProperties(aProps);\n return new ::cppu::OPropertyArrayHelper(aProps);\n}\n\/\/------------------------------------------------------------------------------\nDialog* ODBTypeWizDialogSetup::createDialog(Window* _pParent)\n{\n ODbTypeWizDialogSetup* pDlg = new ODbTypeWizDialogSetup(_pParent, m_pDatasourceItems, m_xORB, m_aInitialSelection);\n return pDlg;\n}\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 2019\/9\/21 21:33:29\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\nusing ll = long long;\nclass mint\n{\npublic:\n static ll MOD;\n ll x;\n mint() : x(0) {}\n mint(ll x) : x(x % MOD) {}\n mint operator-() const { return x ? MOD - x : 0; }\n mint &operator+=(const mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n mint &operator-=(const mint &a) { return *this += -a; }\n mint &operator*=(const mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint &operator\/=(const mint &a)\n {\n mint b{a};\n return *this *= b.power(MOD - 2);\n }\n mint operator+(const mint &a) const { return mint(*this) += a; }\n mint operator-(const mint &a) const { return mint(*this) -= a; }\n mint operator*(const mint &a) const { return mint(*this) *= a; }\n mint operator\/(const mint &a) const { return mint(*this) \/= a; }\n bool operator<(const mint &a) const { return x < a.x; }\n bool operator==(const mint &a) const { return x == a.x; }\n const mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\nll mint::MOD = 1e9 + 7;\nistream &operator>>(istream &stream, mint &a) { return stream >> a.x; }\nostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }\nclass combination\n{\npublic:\n vector inv, fact, factinv;\n static int MAX_SIZE;\n combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[mint::MOD % i]) * (mint::MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1; i < MAX_SIZE; i++)\n {\n fact[i] = mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n};\nint combination::MAX_SIZE = 3000010;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ constexpr double epsilon = 1e-10;\n\/\/ constexpr ll infty = 1000000000000000LL;\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\nclass UnionFind\n{\n vector par;\n\npublic:\n UnionFind() {}\n UnionFind(int n) : par(n, -1) {}\n\n bool is_same(int x, int y)\n {\n return root(x) == root(y);\n }\n\n bool merge(int x, int y)\n {\n x = root(x);\n y = root(y);\n if (x == y)\n {\n return false;\n }\n if (par[x] > par[y])\n {\n swap(x, y);\n }\n par[x] += par[y];\n par[y] = x;\n return true;\n }\n\n long long size(int x)\n {\n return -par[root(x)];\n }\n\n bool is_root(int x)\n {\n return (par[x] < 0);\n }\n\n void all_root()\n {\n for (auto i = 0u; i < par.size(); i++)\n {\n root(i);\n }\n }\n\n void view()\n {\n for (auto i = 0u; i < par.size(); i++)\n {\n cerr << \"par[\" << i << \"] = \" << par[i] << endl;\n }\n }\n\nprivate:\n int root(int x)\n {\n if (par[x] < 0)\n {\n return x;\n }\n return par[x] = root(par[x]);\n }\n};\n\nll N, M, Q;\nint A[100010];\nint B[100010];\nint C[100010];\nusing edge = tuple;\nset S[2];\n\nint main()\n{\n cin >> N >> M >> Q;\n for (auto i = 0; i < Q; i++)\n {\n cin >> A[i] >> B[i] >> C[i];\n }\n if (M == N - 1)\n {\n for (auto i = 0; i < Q; i++)\n {\n if (C[i] == 1)\n {\n No();\n }\n }\n Yes();\n }\n for (auto i = 0; i < Q; i++)\n {\n if (A[i] > B[i])\n {\n swap(A[i], B[i]);\n edge e{A[i], B[i]};\n if (S[1 - C[i]].find(e) != S[1 - C[i]].end())\n {\n No();\n }\n S[C[i]].insert(e);\n#if DEBUG == 1\n cerr << get<0>(e) << \", \" << get<1>(e) << endl;\n#endif\n }\n }\n UnionFind uf(N);\n for (auto const &e : S[0])\n {\n uf.merge(get<0>(e), get<1>(e));\n }\n uf.all_root();\n#if DEBUG == 1\n uf.view();\n#endif\n ll K{0};\n ll X{0};\n for (auto i = 0; i < N; i++)\n {\n if (uf.is_root(i))\n {\n X += uf.size(i) - 1;\n ++K;\n }\n }\n ll mini{X + K};\n ll maxi{X + K * (K - 1) \/ 2};\n assert(mini == N);\n if (K >= 3 && mini <= M && M <= maxi)\n {\n Yes();\n }\n No();\n}tried D.cpp to 'D'#define DEBUG 1\n\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 2019\/9\/21 21:33:29\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\nusing ll = long long;\nclass mint\n{\npublic:\n static ll MOD;\n ll x;\n mint() : x(0) {}\n mint(ll x) : x(x % MOD) {}\n mint operator-() const { return x ? MOD - x : 0; }\n mint &operator+=(const mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n mint &operator-=(const mint &a) { return *this += -a; }\n mint &operator*=(const mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint &operator\/=(const mint &a)\n {\n mint b{a};\n return *this *= b.power(MOD - 2);\n }\n mint operator+(const mint &a) const { return mint(*this) += a; }\n mint operator-(const mint &a) const { return mint(*this) -= a; }\n mint operator*(const mint &a) const { return mint(*this) *= a; }\n mint operator\/(const mint &a) const { return mint(*this) \/= a; }\n bool operator<(const mint &a) const { return x < a.x; }\n bool operator==(const mint &a) const { return x == a.x; }\n const mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\nll mint::MOD = 1e9 + 7;\nistream &operator>>(istream &stream, mint &a) { return stream >> a.x; }\nostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }\nclass combination\n{\npublic:\n vector inv, fact, factinv;\n static int MAX_SIZE;\n combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[mint::MOD % i]) * (mint::MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1; i < MAX_SIZE; i++)\n {\n fact[i] = mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n};\nint combination::MAX_SIZE = 3000010;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ constexpr double epsilon = 1e-10;\n\/\/ constexpr ll infty = 1000000000000000LL;\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\nclass UnionFind\n{\n vector par;\n\npublic:\n UnionFind() {}\n UnionFind(int n) : par(n, -1) {}\n\n bool is_same(int x, int y)\n {\n return root(x) == root(y);\n }\n\n bool merge(int x, int y)\n {\n x = root(x);\n y = root(y);\n if (x == y)\n {\n return false;\n }\n if (par[x] > par[y])\n {\n swap(x, y);\n }\n par[x] += par[y];\n par[y] = x;\n return true;\n }\n\n long long size(int x)\n {\n return -par[root(x)];\n }\n\n bool is_root(int x)\n {\n return (par[x] < 0);\n }\n\n void all_root()\n {\n for (auto i = 0u; i < par.size(); i++)\n {\n root(i);\n }\n }\n\n void view()\n {\n for (auto i = 0u; i < par.size(); i++)\n {\n cerr << \"par[\" << i << \"] = \" << par[i] << endl;\n }\n }\n\nprivate:\n int root(int x)\n {\n if (par[x] < 0)\n {\n return x;\n }\n return par[x] = root(par[x]);\n }\n};\n\nll N, M, Q;\nint A[100010];\nint B[100010];\nint C[100010];\nusing edge = tuple;\nset S[2];\n\nint main()\n{\n cin >> N >> M >> Q;\n for (auto i = 0; i < Q; i++)\n {\n cin >> A[i] >> B[i] >> C[i];\n }\n if (M == N - 1)\n {\n for (auto i = 0; i < Q; i++)\n {\n if (C[i] == 1)\n {\n No();\n }\n }\n Yes();\n }\n#if DEBUG == 1\n cerr << \"aaa\" << endl;\n#endif\n for (auto i = 0; i < Q; i++)\n {\n if (A[i] > B[i])\n {\n swap(A[i], B[i]);\n edge e{A[i], B[i]};\n if (S[1 - C[i]].find(e) != S[1 - C[i]].end())\n {\n No();\n }\n S[C[i]].insert(e);\n#if DEBUG == 1\n cerr << get<0>(e) << \", \" << get<1>(e) << endl;\n#endif\n }\n }\n UnionFind uf(N);\n for (auto const &e : S[0])\n {\n uf.merge(get<0>(e), get<1>(e));\n }\n uf.all_root();\n#if DEBUG == 1\n uf.view();\n#endif\n ll K{0};\n ll X{0};\n for (auto i = 0; i < N; i++)\n {\n if (uf.is_root(i))\n {\n X += uf.size(i) - 1;\n ++K;\n }\n }\n ll mini{X + K};\n ll maxi{X + K * (K - 1) \/ 2};\n assert(mini == N);\n if (K >= 3 && mini <= M && M <= maxi)\n {\n Yes();\n }\n No();\n}<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015, Yahoo Inc. All rights reserved.\n * Copyrights licensed under the New BSD License.\n * See the accompanying LICENSE file for terms.\n *\/\n\n#include \n#include \n#include \n\n#include \"vm-printer.h\"\n\nnamespace http {\nnamespace filters {\nnamespace vm {\nvoid Printer::print(const Code & co, const Memory & m) const {\n print(co, m, std::cout);\n}\n\nvoid Printer::print(const Code & co, const Memory & m,\n std::ostream & o) const {\n\n typedef std::pair< uint32_t, int > Pair;\n typedef std::vector< Pair > Entries;\n int z = 1;\n\n Entries entries1,\n entries2;\n\n for (uint32_t i = 0; i < co.size; i += kSize) {\n const uint32_t op = co[i];\n if (op == Opcodes::kExecute\n || op == Opcodes::kExecuteSingle) {\n const uint32_t b = co[i + 2];\n entries1.push_back(std::make_pair(b * kSize, z));\n entries2.push_back(std::make_pair(i, z));\n ++z;\n }\n }\n\n const Entries::const_iterator END1 = entries1.end(),\n END2 = entries2.end();\n\n Entries::const_iterator it1 = entries1.begin(),\n it2 = entries2.begin();\n\n ASSERT(entries1.size() == entries2.size());\n\n for (uint32_t i = 0; i < co.size; i += kSize) {\n const uint32_t op = co[i];\n const uint32_t a = co[i + 1];\n const uint32_t b = co[i + 2];\n const uint32_t c = co[i + 3];\n\n if (it1 != END1 && it1->first == i) {\n o << \"\\n\" \" -- Entry \" << it1->second << \" --\" \"\\n\";\n ++it1;\n }\n\n o << std::resetiosflags(std::ios::left) << std::setiosflags(std::ios::right)\n << std::setw(6) << std::dec << (i \/ kSize) << \" \"\n << std::resetiosflags(std::ios::right) << std::setiosflags(std::ios::left)\n << \"0x\" << std::setw(6) << std::hex << std::setfill('0') << (i * sizeof(uint32_t)) << std::setfill(' ') << \" \"\n << std::setw(30) << opcode(static_cast< Opcodes::OPCODES >(op))\n << \"0x\" << std::setw(8) << a\n << \"0x\" << std::setw(8) << b\n << \"0x\" << std::setw(8) << c;\n\n std::stringstream comments;\n\n if (op == Opcodes::kExecute || op == Opcodes::kExecuteSingle) {\n switch(a) {\n case ExecutionMode::kNone:\n comments << ( ! comments.str().empty() ? \", \" : \"\") << \" kNone\";\n break;\n case ExecutionMode::kAnd:\n comments << ( ! comments.str().empty() ? \", \" : \"\") << \" kAnd\";\n break;\n case ExecutionMode::kOr:\n comments << ( ! comments.str().empty() ? \", \" : \"\") << \" kOr\";\n break;\n default: ASSERT(false); break; \/\/unreacheable\n }\n }\n\n if (it2 != END2 && it2->first == i) {\n ASSERT(op == Opcodes::kExecute\n || op == Opcodes::kExecuteSingle);\n comments << ( ! comments.str().empty() ? \", \" : \"\") << \"Entry \" << it2->second;\n ++it2;\n }\n\n if ( ! comments.str().empty()) {\n o << \" \/\/\" << comments.str();\n comments.str().clear();\n }\n\n o << \"\\n\";\n\n switch (op) {\n case Opcodes::kContainsCookie:\n case Opcodes::kContainsDomain:\n case Opcodes::kContainsHeader:\n case Opcodes::kContainsPath:\n case Opcodes::kContainsQueryParameter:\n case Opcodes::kEqualCookie:\n case Opcodes::kEqualDomain:\n case Opcodes::kEqualHeader:\n case Opcodes::kEqualPath:\n case Opcodes::kEqualQueryParameter:\n case Opcodes::kExistsCookie:\n case Opcodes::kExistsHeader:\n case Opcodes::kExistsQueryParameter:\n case Opcodes::kGreaterThanAfterCookie:\n case Opcodes::kGreaterThanAfterHeader:\n case Opcodes::kGreaterThanAfterQueryParameter:\n case Opcodes::kGreaterThanCookie:\n case Opcodes::kGreaterThanHeader:\n case Opcodes::kGreaterThanQueryParameter:\n case Opcodes::kIsMethod:\n case Opcodes::kIsScheme:\n case Opcodes::kLessThanAfterCookie:\n case Opcodes::kLessThanAfterHeader:\n case Opcodes::kLessThanAfterQueryParameter:\n case Opcodes::kLessThanCookie:\n case Opcodes::kLessThanHeader:\n case Opcodes::kLessThanQueryParameter:\n case Opcodes::kNotEqualDomain:\n case Opcodes::kNotEqualPath:\n case Opcodes::kNotEqualCookie:\n case Opcodes::kNotEqualHeader:\n case Opcodes::kNotEqualQueryParameter:\n case Opcodes::kPrintDebug:\n case Opcodes::kPrintError:\n if (a != 0) {\n ASSERT(a < m.size);\n o << \" -> \\\"\" << m.t + a << \"\\\"\\n\";\n }\n break;\n\n default:\n break;\n }\n\n switch (op) {\n case Opcodes::kContainsCookie:\n case Opcodes::kContainsHeader:\n case Opcodes::kContainsQueryParameter:\n case Opcodes::kEqualCookie:\n case Opcodes::kEqualHeader:\n case Opcodes::kEqualQueryParameter:\n case Opcodes::kGreaterThanAfterCookie:\n case Opcodes::kGreaterThanAfterHeader:\n case Opcodes::kGreaterThanAfterQueryParameter:\n case Opcodes::kLessThanAfterCookie:\n case Opcodes::kLessThanAfterHeader:\n case Opcodes::kLessThanAfterQueryParameter:\n case Opcodes::kLessThanQueryParameter:\n case Opcodes::kNotEqualCookie:\n case Opcodes::kNotEqualHeader:\n case Opcodes::kNotEqualQueryParameter:\n case Opcodes::kPrintDebug:\n case Opcodes::kPrintError:\n if (b != 0) {\n ASSERT(b < m.size);\n o << \" -> \\\"\" << m.t + b << \"\\\"\\n\";\n }\n break;\n\n default:\n break;\n }\n }\n\n o << std::flush;\n}\n\nconst char * Printer::opcode(Opcodes::OPCODES op) {\n switch (op) {\n case Opcodes::kNull:\n return \"kNull\"; break;\n\n case Opcodes::kSkip:\n return \"kSkip\"; break;\n case Opcodes::kExecute:\n return \"kExecute\"; break;\n case Opcodes::kExecuteSingle:\n return \"kExecuteSingle\"; break;\n case Opcodes::kReturn:\n return \"kReturn\"; break;\n case Opcodes::kHalt:\n return \"kHalt\"; break;\n\n case Opcodes::kNone:\n return \"kNone\"; break;\n case Opcodes::kAnd:\n return \"kAnd\"; break;\n case Opcodes::kOr:\n return \"kOr\"; break;\n case Opcodes::kNot:\n return \"kNot\"; break;\n\n case Opcodes::kFalse:\n return \"kFalse\"; break;\n case Opcodes::kTrue:\n return \"kTrue\"; break;\n\n case Opcodes::kPrintError:\n return \"kPrintError\"; break;\n case Opcodes::kPrintDebug:\n return \"kPrintDebug\"; break;\n\n case Opcodes::kIsMethod:\n return \"kIsMethod\"; break;\n case Opcodes::kIsScheme:\n return \"kIsScheme\"; break;\n\n case Opcodes::kContainsDomain:\n return \"kContainsDomain\"; break;\n case Opcodes::kEqualDomain:\n return \"kEqualDomain\"; break;\n case Opcodes::kNotEqualDomain:\n return \"kNotEqualDomain\"; break;\n case Opcodes::kStartsWithDomain:\n return \"kStartsWithDomain\"; break;\n\n case Opcodes::kContainsPath:\n return \"kContainsPath\"; break;\n case Opcodes::kEqualPath:\n return \"kEqualPath\"; break;\n case Opcodes::kNotEqualPath:\n return \"kNotEqualPath\"; break;\n case Opcodes::kStartsWithPath:\n return \"kStartsWithPath\"; break;\n\n case Opcodes::kContainsQueryParameter:\n return \"kContainsQueryParameter\"; break;\n case Opcodes::kEqualQueryParameter:\n return \"kEqualQueryParameter\"; break;\n case Opcodes::kExistsQueryParameter:\n return \"kExistsQueryParameter\"; break;\n case Opcodes::kGreaterThanQueryParameter:\n return \"kGreaterThanQueryParameter\"; break;\n case Opcodes::kGreaterThanAfterQueryParameter:\n return \"kGreaterThanAfterQueryParameter\"; break;\n case Opcodes::kLessThanQueryParameter:\n return \"kLessThanQueryParameter\"; break;\n case Opcodes::kLessThanAfterQueryParameter:\n return \"kLessThanAfterQueryParameter\"; break;\n case Opcodes::kNotEqualQueryParameter:\n return \"kNotEqualQueryParameter\"; break;\n case Opcodes::kStartsWithQueryParameter:\n return \"kStartsWithQueryParameter\"; break;\n\n case Opcodes::kContainsHeader:\n return \"kContainsHeader\"; break;\n case Opcodes::kEqualHeader:\n return \"kEqualHeader\"; break;\n case Opcodes::kExistsHeader:\n return \"kExistsHeader\"; break;\n case Opcodes::kGreaterThanHeader:\n return \"kGreaterThanHeader\"; break;\n case Opcodes::kGreaterThanAfterHeader:\n return \"kGreaterThanAfterHeader\"; break;\n case Opcodes::kLessThanHeader:\n return \"kLessThanHeader\"; break;\n case Opcodes::kLessThanAfterHeader:\n return \"kLessThanAfterHeader\"; break;\n case Opcodes::kNotEqualHeader:\n return \"kNotEqualHeader\"; break;\n case Opcodes::kStartsWithHeader:\n return \"kStartsWithHeader\"; break;\n\n case Opcodes::kContainsCookie:\n return \"kContainsCookie\"; break;\n case Opcodes::kEqualCookie:\n return \"kEqualCookie\"; break;\n case Opcodes::kExistsCookie:\n return \"kExistsCookie\"; break;\n case Opcodes::kGreaterThanCookie:\n return \"kGreaterThanCookie\"; break;\n case Opcodes::kGreaterThanAfterCookie:\n return \"kGreaterThanAfterCookie\"; break;\n case Opcodes::kLessThanCookie:\n return \"kLessThanCookie\"; break;\n case Opcodes::kLessThanAfterCookie:\n return \"kLessThanAfterCookie\"; break;\n case Opcodes::kNotEqualCookie:\n return \"kNotEqualCookie\"; break;\n case Opcodes::kStartsWithCookie:\n return \"kStartsWithCookie\"; break;\n\n case Opcodes::kUpperBound:\n return \"kUpperBound\"; break;\n\n default: return \"(Unknown)\"; break;\n }\n}\n} \/\/end of vm namespace\n} \/\/end of filters namespace\n} \/\/end of http namespace\nenhancing printing for StartsWith ops\/*\n * Copyright (c) 2015, Yahoo Inc. All rights reserved.\n * Copyrights licensed under the New BSD License.\n * See the accompanying LICENSE file for terms.\n *\/\n\n#include \n#include \n#include \n\n#include \"vm-printer.h\"\n\nnamespace http {\nnamespace filters {\nnamespace vm {\nvoid Printer::print(const Code & co, const Memory & m) const {\n print(co, m, std::cout);\n}\n\nvoid Printer::print(const Code & co, const Memory & m,\n std::ostream & o) const {\n\n typedef std::pair< uint32_t, int > Pair;\n typedef std::vector< Pair > Entries;\n int z = 1;\n\n Entries entries1,\n entries2;\n\n for (uint32_t i = 0; i < co.size; i += kSize) {\n const uint32_t op = co[i];\n if (op == Opcodes::kExecute\n || op == Opcodes::kExecuteSingle) {\n const uint32_t b = co[i + 2];\n entries1.push_back(std::make_pair(b * kSize, z));\n entries2.push_back(std::make_pair(i, z));\n ++z;\n }\n }\n\n const Entries::const_iterator END1 = entries1.end(),\n END2 = entries2.end();\n\n Entries::const_iterator it1 = entries1.begin(),\n it2 = entries2.begin();\n\n ASSERT(entries1.size() == entries2.size());\n\n for (uint32_t i = 0; i < co.size; i += kSize) {\n const uint32_t op = co[i];\n const uint32_t a = co[i + 1];\n const uint32_t b = co[i + 2];\n const uint32_t c = co[i + 3];\n\n if (it1 != END1 && it1->first == i) {\n o << \"\\n\" \" -- Entry \" << it1->second << \" --\" \"\\n\";\n ++it1;\n }\n\n o << std::resetiosflags(std::ios::left) << std::setiosflags(std::ios::right)\n << std::setw(6) << std::dec << (i \/ kSize) << \" \"\n << std::resetiosflags(std::ios::right) << std::setiosflags(std::ios::left)\n << \"0x\" << std::setw(6) << std::hex << std::setfill('0') << (i * sizeof(uint32_t)) << std::setfill(' ') << \" \"\n << std::setw(30) << opcode(static_cast< Opcodes::OPCODES >(op))\n << \"0x\" << std::setw(8) << a\n << \"0x\" << std::setw(8) << b\n << \"0x\" << std::setw(8) << c;\n\n std::stringstream comments;\n\n if (op == Opcodes::kExecute || op == Opcodes::kExecuteSingle) {\n switch(a) {\n case ExecutionMode::kNone:\n comments << ( ! comments.str().empty() ? \", \" : \"\") << \" kNone\";\n break;\n case ExecutionMode::kAnd:\n comments << ( ! comments.str().empty() ? \", \" : \"\") << \" kAnd\";\n break;\n case ExecutionMode::kOr:\n comments << ( ! comments.str().empty() ? \", \" : \"\") << \" kOr\";\n break;\n default: ASSERT(false); break; \/\/unreacheable\n }\n }\n\n if (it2 != END2 && it2->first == i) {\n ASSERT(op == Opcodes::kExecute\n || op == Opcodes::kExecuteSingle);\n comments << ( ! comments.str().empty() ? \", \" : \"\") << \"Entry \" << it2->second;\n ++it2;\n }\n\n if ( ! comments.str().empty()) {\n o << \" \/\/\" << comments.str();\n comments.str().clear();\n }\n\n o << \"\\n\";\n\n switch (op) {\n case Opcodes::kContainsCookie:\n case Opcodes::kContainsDomain:\n case Opcodes::kContainsHeader:\n case Opcodes::kContainsPath:\n case Opcodes::kContainsQueryParameter:\n case Opcodes::kEqualCookie:\n case Opcodes::kEqualDomain:\n case Opcodes::kEqualHeader:\n case Opcodes::kEqualPath:\n case Opcodes::kEqualQueryParameter:\n case Opcodes::kExistsCookie:\n case Opcodes::kExistsHeader:\n case Opcodes::kExistsQueryParameter:\n case Opcodes::kGreaterThanAfterCookie:\n case Opcodes::kGreaterThanAfterHeader:\n case Opcodes::kGreaterThanAfterQueryParameter:\n case Opcodes::kGreaterThanCookie:\n case Opcodes::kGreaterThanHeader:\n case Opcodes::kGreaterThanQueryParameter:\n case Opcodes::kIsMethod:\n case Opcodes::kIsScheme:\n case Opcodes::kLessThanAfterCookie:\n case Opcodes::kLessThanAfterHeader:\n case Opcodes::kLessThanAfterQueryParameter:\n case Opcodes::kLessThanCookie:\n case Opcodes::kLessThanHeader:\n case Opcodes::kLessThanQueryParameter:\n case Opcodes::kNotEqualDomain:\n case Opcodes::kNotEqualPath:\n case Opcodes::kNotEqualCookie:\n case Opcodes::kNotEqualHeader:\n case Opcodes::kNotEqualQueryParameter:\n case Opcodes::kPrintDebug:\n case Opcodes::kPrintError:\n case Opcodes::kStartsWithCookie:\n case Opcodes::kStartsWithDomain:\n case Opcodes::kStartsWithHeader:\n case Opcodes::kStartsWithPath:\n case Opcodes::kStartsWithQueryParameter:\n if (a != 0) {\n ASSERT(a < m.size);\n o << \" -> \\\"\" << m.t + a << \"\\\"\\n\";\n }\n break;\n\n default:\n break;\n }\n\n switch (op) {\n case Opcodes::kContainsCookie:\n case Opcodes::kContainsHeader:\n case Opcodes::kContainsQueryParameter:\n case Opcodes::kEqualCookie:\n case Opcodes::kEqualHeader:\n case Opcodes::kEqualQueryParameter:\n case Opcodes::kGreaterThanAfterCookie:\n case Opcodes::kGreaterThanAfterHeader:\n case Opcodes::kGreaterThanAfterQueryParameter:\n case Opcodes::kLessThanAfterCookie:\n case Opcodes::kLessThanAfterHeader:\n case Opcodes::kLessThanAfterQueryParameter:\n case Opcodes::kLessThanQueryParameter:\n case Opcodes::kNotEqualCookie:\n case Opcodes::kNotEqualHeader:\n case Opcodes::kNotEqualQueryParameter:\n case Opcodes::kPrintDebug:\n case Opcodes::kPrintError:\n case Opcodes::kStartsWithCookie:\n case Opcodes::kStartsWithDomain:\n case Opcodes::kStartsWithHeader:\n case Opcodes::kStartsWithPath:\n case Opcodes::kStartsWithQueryParameter:\n if (b != 0) {\n ASSERT(b < m.size);\n o << \" -> \\\"\" << m.t + b << \"\\\"\\n\";\n }\n break;\n\n default:\n break;\n }\n }\n\n o << std::flush;\n}\n\nconst char * Printer::opcode(Opcodes::OPCODES op) {\n switch (op) {\n case Opcodes::kNull:\n return \"kNull\"; break;\n\n case Opcodes::kSkip:\n return \"kSkip\"; break;\n case Opcodes::kExecute:\n return \"kExecute\"; break;\n case Opcodes::kExecuteSingle:\n return \"kExecuteSingle\"; break;\n case Opcodes::kReturn:\n return \"kReturn\"; break;\n case Opcodes::kHalt:\n return \"kHalt\"; break;\n\n case Opcodes::kNone:\n return \"kNone\"; break;\n case Opcodes::kAnd:\n return \"kAnd\"; break;\n case Opcodes::kOr:\n return \"kOr\"; break;\n case Opcodes::kNot:\n return \"kNot\"; break;\n\n case Opcodes::kFalse:\n return \"kFalse\"; break;\n case Opcodes::kTrue:\n return \"kTrue\"; break;\n\n case Opcodes::kPrintError:\n return \"kPrintError\"; break;\n case Opcodes::kPrintDebug:\n return \"kPrintDebug\"; break;\n\n case Opcodes::kIsMethod:\n return \"kIsMethod\"; break;\n case Opcodes::kIsScheme:\n return \"kIsScheme\"; break;\n\n case Opcodes::kContainsDomain:\n return \"kContainsDomain\"; break;\n case Opcodes::kEqualDomain:\n return \"kEqualDomain\"; break;\n case Opcodes::kNotEqualDomain:\n return \"kNotEqualDomain\"; break;\n case Opcodes::kStartsWithDomain:\n return \"kStartsWithDomain\"; break;\n\n case Opcodes::kContainsPath:\n return \"kContainsPath\"; break;\n case Opcodes::kEqualPath:\n return \"kEqualPath\"; break;\n case Opcodes::kNotEqualPath:\n return \"kNotEqualPath\"; break;\n case Opcodes::kStartsWithPath:\n return \"kStartsWithPath\"; break;\n\n case Opcodes::kContainsQueryParameter:\n return \"kContainsQueryParameter\"; break;\n case Opcodes::kEqualQueryParameter:\n return \"kEqualQueryParameter\"; break;\n case Opcodes::kExistsQueryParameter:\n return \"kExistsQueryParameter\"; break;\n case Opcodes::kGreaterThanQueryParameter:\n return \"kGreaterThanQueryParameter\"; break;\n case Opcodes::kGreaterThanAfterQueryParameter:\n return \"kGreaterThanAfterQueryParameter\"; break;\n case Opcodes::kLessThanQueryParameter:\n return \"kLessThanQueryParameter\"; break;\n case Opcodes::kLessThanAfterQueryParameter:\n return \"kLessThanAfterQueryParameter\"; break;\n case Opcodes::kNotEqualQueryParameter:\n return \"kNotEqualQueryParameter\"; break;\n case Opcodes::kStartsWithQueryParameter:\n return \"kStartsWithQueryParameter\"; break;\n\n case Opcodes::kContainsHeader:\n return \"kContainsHeader\"; break;\n case Opcodes::kEqualHeader:\n return \"kEqualHeader\"; break;\n case Opcodes::kExistsHeader:\n return \"kExistsHeader\"; break;\n case Opcodes::kGreaterThanHeader:\n return \"kGreaterThanHeader\"; break;\n case Opcodes::kGreaterThanAfterHeader:\n return \"kGreaterThanAfterHeader\"; break;\n case Opcodes::kLessThanHeader:\n return \"kLessThanHeader\"; break;\n case Opcodes::kLessThanAfterHeader:\n return \"kLessThanAfterHeader\"; break;\n case Opcodes::kNotEqualHeader:\n return \"kNotEqualHeader\"; break;\n case Opcodes::kStartsWithHeader:\n return \"kStartsWithHeader\"; break;\n\n case Opcodes::kContainsCookie:\n return \"kContainsCookie\"; break;\n case Opcodes::kEqualCookie:\n return \"kEqualCookie\"; break;\n case Opcodes::kExistsCookie:\n return \"kExistsCookie\"; break;\n case Opcodes::kGreaterThanCookie:\n return \"kGreaterThanCookie\"; break;\n case Opcodes::kGreaterThanAfterCookie:\n return \"kGreaterThanAfterCookie\"; break;\n case Opcodes::kLessThanCookie:\n return \"kLessThanCookie\"; break;\n case Opcodes::kLessThanAfterCookie:\n return \"kLessThanAfterCookie\"; break;\n case Opcodes::kNotEqualCookie:\n return \"kNotEqualCookie\"; break;\n case Opcodes::kStartsWithCookie:\n return \"kStartsWithCookie\"; break;\n\n case Opcodes::kUpperBound:\n return \"kUpperBound\"; break;\n\n default: return \"(Unknown)\"; break;\n }\n}\n} \/\/end of vm namespace\n} \/\/end of filters namespace\n} \/\/end of http namespace\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: ZipPackageEntry.cxx,v $\n *\n * $Revision: 1.25 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 21:09:49 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_PACKAGE_ENTRY_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_PACKAGE_ZIP_ZIPCONSTANTS_HPP_\n#include \n#endif\n#ifndef _VOS_DIAGNOSE_H_\n#include \n#endif\n#ifndef _IMPL_VALID_CHARACTERS_HXX_\n#include \n#endif\n#ifndef _ZIP_PACKAGE_FOLDER_HXX\n#include \n#endif\n#ifndef _ZIP_PACKAGE_STREAM_HXX\n#include \n#endif\n#ifndef _CONTENT_INFO_HXX_\n#include \n#endif\n\nusing namespace rtl;\nusing namespace com::sun::star;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::packages::zip;\nusing namespace com::sun::star::packages::zip::ZipConstants;\n\nZipPackageEntry::ZipPackageEntry ( bool bNewFolder )\n: pParent ( NULL )\n, mbIsFolder ( bNewFolder )\n{\n}\n\nZipPackageEntry::~ZipPackageEntry()\n{\n \/\/ When the entry is destroyed it must be already disconnected from the parent\n OSL_ENSURE( !pParent, \"The parent must be disconnected already! Memory corruption is possible!\\n\" );\n}\n\n\/\/ XChild\nOUString SAL_CALL ZipPackageEntry::getName( )\n throw(RuntimeException)\n{\n return aEntry.sName;\n}\nvoid SAL_CALL ZipPackageEntry::setName( const OUString& aName )\n throw(RuntimeException)\n{\n if ( pParent && pParent->hasByName ( aEntry.sName ) )\n pParent->removeByName ( aEntry.sName );\n\n const sal_Unicode *pChar = aName.getStr();\n VOS_ENSURE ( Impl_IsValidChar (pChar, static_cast < sal_Int16 > ( aName.getLength() ), sal_False), \"Invalid character in new zip package entry name!\");\n\n aEntry.sName = aName;\n\n if ( pParent )\n pParent->doInsertByName ( this, sal_False );\n}\nReference< XInterface > SAL_CALL ZipPackageEntry::getParent( )\n throw(RuntimeException)\n{\n \/\/ return Reference< XInterface >( xParent, UNO_QUERY );\n return Reference< XInterface >( static_cast< ::cppu::OWeakObject* >( pParent ), UNO_QUERY );\n}\n\nvoid ZipPackageEntry::doSetParent ( ZipPackageFolder * pNewParent, sal_Bool bInsert )\n{\n \/\/ xParent = pParent = pNewParent;\n pParent = pNewParent;\n if ( bInsert && !pNewParent->hasByName ( aEntry.sName ) )\n pNewParent->doInsertByName ( this, sal_False );\n}\n\nvoid SAL_CALL ZipPackageEntry::setParent( const Reference< XInterface >& xNewParent )\n throw(NoSupportException, RuntimeException)\n{\n sal_Int64 nTest;\n Reference < XUnoTunnel > xTunnel ( xNewParent, UNO_QUERY );\n if ( !xNewParent.is() || ( nTest = xTunnel->getSomething ( ZipPackageFolder::static_getImplementationId () ) ) == 0 )\n throw NoSupportException();\n\n ZipPackageFolder *pNewParent = reinterpret_cast < ZipPackageFolder * > ( nTest );\n\n if ( pNewParent != pParent )\n {\n if ( pParent && pParent->hasByName ( aEntry.sName ) )\n pParent->removeByName( aEntry.sName );\n doSetParent ( pNewParent, sal_True );\n }\n}\n \/\/XPropertySet\nReference< beans::XPropertySetInfo > SAL_CALL ZipPackageEntry::getPropertySetInfo( )\n throw(RuntimeException)\n{\n return Reference < beans::XPropertySetInfo > ();\n}\nvoid SAL_CALL ZipPackageEntry::addPropertyChangeListener( const OUString& aPropertyName, const Reference< beans::XPropertyChangeListener >& xListener )\n throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)\n{\n}\nvoid SAL_CALL ZipPackageEntry::removePropertyChangeListener( const OUString& aPropertyName, const Reference< beans::XPropertyChangeListener >& aListener )\n throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)\n{\n}\nvoid SAL_CALL ZipPackageEntry::addVetoableChangeListener( const OUString& PropertyName, const Reference< beans::XVetoableChangeListener >& aListener )\n throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)\n{\n}\nvoid SAL_CALL ZipPackageEntry::removeVetoableChangeListener( const OUString& PropertyName, const Reference< beans::XVetoableChangeListener >& aListener )\n throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)\n{\n}\nINTEGRATION: CWS mav18 (1.25.44); FILE MERGED 2005\/05\/27 14:52:21 mav 1.25.44.1: #i49755# fix incoplete commit problem\/*************************************************************************\n *\n * $RCSfile: ZipPackageEntry.cxx,v $\n *\n * $Revision: 1.26 $\n *\n * last change: $Author: kz $ $Date: 2005-07-12 12:31:07 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_PACKAGE_ENTRY_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_PACKAGE_ZIP_ZIPCONSTANTS_HPP_\n#include \n#endif\n#ifndef _VOS_DIAGNOSE_H_\n#include \n#endif\n#ifndef _IMPL_VALID_CHARACTERS_HXX_\n#include \n#endif\n#ifndef _ZIP_PACKAGE_FOLDER_HXX\n#include \n#endif\n#ifndef _ZIP_PACKAGE_STREAM_HXX\n#include \n#endif\n#ifndef _CONTENT_INFO_HXX_\n#include \n#endif\n\nusing namespace rtl;\nusing namespace com::sun::star;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::packages::zip;\nusing namespace com::sun::star::packages::zip::ZipConstants;\n\nZipPackageEntry::ZipPackageEntry ( bool bNewFolder )\n: pParent ( NULL )\n, mbIsFolder ( bNewFolder )\n, mbAllowRemoveOnInsert( sal_True )\n{\n}\n\nZipPackageEntry::~ZipPackageEntry()\n{\n \/\/ When the entry is destroyed it must be already disconnected from the parent\n OSL_ENSURE( !pParent, \"The parent must be disconnected already! Memory corruption is possible!\\n\" );\n}\n\n\/\/ XChild\nOUString SAL_CALL ZipPackageEntry::getName( )\n throw(RuntimeException)\n{\n return aEntry.sName;\n}\nvoid SAL_CALL ZipPackageEntry::setName( const OUString& aName )\n throw(RuntimeException)\n{\n if ( pParent && pParent->hasByName ( aEntry.sName ) )\n pParent->removeByName ( aEntry.sName );\n\n const sal_Unicode *pChar = aName.getStr();\n VOS_ENSURE ( Impl_IsValidChar (pChar, static_cast < sal_Int16 > ( aName.getLength() ), sal_False), \"Invalid character in new zip package entry name!\");\n\n aEntry.sName = aName;\n\n if ( pParent )\n pParent->doInsertByName ( this, sal_False );\n}\nReference< XInterface > SAL_CALL ZipPackageEntry::getParent( )\n throw(RuntimeException)\n{\n \/\/ return Reference< XInterface >( xParent, UNO_QUERY );\n return Reference< XInterface >( static_cast< ::cppu::OWeakObject* >( pParent ), UNO_QUERY );\n}\n\nvoid ZipPackageEntry::doSetParent ( ZipPackageFolder * pNewParent, sal_Bool bInsert )\n{\n \/\/ xParent = pParent = pNewParent;\n pParent = pNewParent;\n if ( bInsert && !pNewParent->hasByName ( aEntry.sName ) )\n pNewParent->doInsertByName ( this, sal_False );\n}\n\nvoid SAL_CALL ZipPackageEntry::setParent( const Reference< XInterface >& xNewParent )\n throw(NoSupportException, RuntimeException)\n{\n sal_Int64 nTest;\n Reference < XUnoTunnel > xTunnel ( xNewParent, UNO_QUERY );\n if ( !xNewParent.is() || ( nTest = xTunnel->getSomething ( ZipPackageFolder::static_getImplementationId () ) ) == 0 )\n throw NoSupportException();\n\n ZipPackageFolder *pNewParent = reinterpret_cast < ZipPackageFolder * > ( nTest );\n\n if ( pNewParent != pParent )\n {\n if ( pParent && pParent->hasByName ( aEntry.sName ) && mbAllowRemoveOnInsert )\n pParent->removeByName( aEntry.sName );\n doSetParent ( pNewParent, sal_True );\n }\n}\n \/\/XPropertySet\nReference< beans::XPropertySetInfo > SAL_CALL ZipPackageEntry::getPropertySetInfo( )\n throw(RuntimeException)\n{\n return Reference < beans::XPropertySetInfo > ();\n}\nvoid SAL_CALL ZipPackageEntry::addPropertyChangeListener( const OUString& aPropertyName, const Reference< beans::XPropertyChangeListener >& xListener )\n throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)\n{\n}\nvoid SAL_CALL ZipPackageEntry::removePropertyChangeListener( const OUString& aPropertyName, const Reference< beans::XPropertyChangeListener >& aListener )\n throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)\n{\n}\nvoid SAL_CALL ZipPackageEntry::addVetoableChangeListener( const OUString& PropertyName, const Reference< beans::XVetoableChangeListener >& aListener )\n throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)\n{\n}\nvoid SAL_CALL ZipPackageEntry::removeVetoableChangeListener( const OUString& PropertyName, const Reference< beans::XVetoableChangeListener >& aListener )\n throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)\n{\n}\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : B.cpp\n * Author : Kazune Takahashi\n * Created : 12\/28\/2019, 10:05:50 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n\/\/ ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{x % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nclass Solve\n{\n ll N, M, V, P;\n vector A;\n vector sum;\n\npublic:\n Solve(ll N, ll M, ll V, ll P, vector A) : N{N}, M{M}, V{V}, P{P}, A(A), sum(N + 1, 0LL)\n {\n sum[P - 1] = A[P - 1];\n for (auto i = P; i < N; i++)\n {\n sum[P] = A[P] + sum[P - 1];\n }\n }\n\n ll answer()\n {\n if (V <= P)\n {\n return answer0();\n }\n else\n {\n return answer1();\n }\n }\n\nprivate:\n ll answer0()\n {\n ll ans{0};\n for (auto i = P; i < N; i++)\n {\n if (A[P - 1] <= A[i] + M)\n {\n ans++;\n }\n }\n return ans + P;\n }\n\n ll answer1()\n {\n ll ok{P - 1};\n ll ng{N};\n if (abs(ok - ng) > 1)\n {\n ll t{(ok + ng) \/ 2};\n if (test(t))\n {\n ok = t;\n }\n else\n {\n ng = t;\n }\n }\n return ok + 1;\n }\n\n bool test(ll i)\n {\n ll K{V - (P - 1) - (N - i)};\n if (K <= 0)\n {\n return A[i] + M >= A[P - 1];\n }\n return (A[i] + M) * (i - (P - 1)) >= sum[i - 1] + K * M;\n }\n};\n\nint main()\n{\n ll N, M, V, P;\n cin >> N >> M >> V >> P;\n vector A(N);\n for (auto i = 0; i < N; i++)\n {\n cin >> A[i];\n }\n sort(A.rbegin(), A.rend());\n Solve solve(N, M, V, P, A);\n cout << solve.answer() << endl;\n}\ntried B.cpp to 'B'#define DEBUG 1\n\/**\n * File : B.cpp\n * Author : Kazune Takahashi\n * Created : 12\/28\/2019, 10:05:50 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n\/\/ ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{x % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nclass Solve\n{\n ll N, M, V, P;\n vector A;\n vector sum;\n\npublic:\n Solve(ll N, ll M, ll V, ll P, vector A) : N{N}, M{M}, V{V}, P{P}, A(A), sum(N + 1, 0LL)\n {\n sum[P - 1] = A[P - 1];\n for (auto i = P; i < N; i++)\n {\n sum[P] = A[P] + sum[P - 1];\n }\n }\n\n ll answer()\n {\n if (V <= P)\n {\n return answer0();\n }\n else\n {\n return answer1();\n }\n }\n\nprivate:\n ll answer0()\n {\n ll ans{0};\n for (auto i = P; i < N; i++)\n {\n if (A[P - 1] <= A[i] + M)\n {\n ans++;\n }\n }\n return ans + P;\n }\n\n ll answer1()\n {\n ll ok{P - 1};\n ll ng{N};\n if (abs(ok - ng) > 1)\n {\n ll t{(ok + ng) \/ 2};\n if (test(t))\n {\n ok = t;\n }\n else\n {\n ng = t;\n }\n }\n return ok + 1;\n }\n\n bool test(ll i)\n {\n ll K{V - (P - 1) - (N - i)};\n if (K <= 0)\n {\n#if DEBUG == 1\n cerr << \"i = \" << i << endl;\n cerr << \"A[\" << i << \"] = \" << A[i] << endl;\n cerr << \"M = \" << M << endl;\n cerr << \"P - 1 = \" << P - 1 << endl;\n cerr << \"A[\" << P - 1 << \"] = \" << A[P - 1] << endl;\n#endif\n return A[i] + M >= A[P - 1];\n }\n return (A[i] + M) * (i - (P - 1)) >= sum[i - 1] + K * M;\n }\n};\n\nint main()\n{\n ll N, M, V, P;\n cin >> N >> M >> V >> P;\n vector A(N);\n for (auto i = 0; i < N; i++)\n {\n cin >> A[i];\n }\n sort(A.rbegin(), A.rend());\n Solve solve(N, M, V, P, A);\n cout << solve.answer() << endl;\n}\n<|endoftext|>"} {"text":"\/\/******************************************************************\n\/\/\n\/\/ Copyright 2016 Samsung Electronics All Rights Reserved.\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"NSProviderInterface.h\"\n#include \"NSConsumerSimulator.h\"\n#include \"NSCommon.h\"\n\nnamespace\n{\n std::atomic_bool g_isStartedStack(false);\n\n std::chrono::milliseconds g_waitForResponse(500);\n\n std::condition_variable responseCon;\n std::mutex mutexForCondition;\n\n NSConsumerSimulator g_consumerSimul;\n NSConsumer * g_consumer;\n}\n\nclass TestWithMock: public testing::Test\n{\npublic:\n MockRepository mocks;\n\nprotected:\n virtual ~TestWithMock() noexcept(noexcept(std::declval().~Test())) {}\n\n virtual void TearDown() {\n try\n {\n mocks.VerifyAll();\n }\n catch (...)\n {\n mocks.reset();\n throw;\n }\n }\n};\n\nclass NotificationProviderTest : public TestWithMock\n{\npublic:\n NotificationProviderTest() = default;\n ~NotificationProviderTest() = default;\n\n static void NSRequestedSubscribeCallbackEmpty(NSConsumer *)\n {\n std::cout << __func__ << std::endl;\n }\n\n static void NSSyncCallbackEmpty(NSSyncInfo *)\n {\n std::cout << __func__ << std::endl;\n }\n\n static void NSMessageCallbackFromConsumerEmpty(\n const int &, const std::string &, const std::string &, const std::string &)\n {\n std::cout << __func__ << std::endl;\n }\n\n static void NSSyncCallbackFromConsumerEmpty(int, int)\n {\n std::cout << __func__ << std::endl;\n }\n\nprotected:\n\n void SetUp()\n {\n TestWithMock::SetUp();\n\n if (g_isStartedStack == false)\n {\n OC::PlatformConfig cfg\n {\n OC::ServiceType::InProc,\n OC::ModeType::Both,\n \"0.0.0.0\",\n 0,\n OC::QualityOfService::HighQos\n };\n OC::OCPlatform::Configure(cfg);\n\n try\n {\n OC::OCPlatform::stopPresence();\n }\n catch (...)\n {\n\n }\n\n g_isStartedStack = true;\n }\n\n }\n\n void TearDown()\n {\n TestWithMock::TearDown();\n }\n\n};\n\nTEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyTrue)\n{\n NSProviderConfig config;\n config.subRequestCallback = NSRequestedSubscribeCallbackEmpty;\n config.syncInfoCallback = NSSyncCallbackEmpty;\n config.policy = true;\n config.userInfo = NULL;\n\n NSResult ret = NSStartProvider(config);\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, g_waitForResponse);\n\n EXPECT_EQ(ret, NS_OK);\n}\n\nTEST_F(NotificationProviderTest, StopProviderPositive)\n{\n NSResult ret = NSStopProvider();\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, g_waitForResponse);\n\n EXPECT_EQ(ret, NS_OK);\n}\n\nTEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyFalse)\n{\n NSProviderConfig config;\n config.subRequestCallback = NSRequestedSubscribeCallbackEmpty;\n config.syncInfoCallback = NSSyncCallbackEmpty;\n config.policy = false;\n config.userInfo = NULL;\n\n NSResult ret = NSStartProvider(config);\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(3000));\n g_consumerSimul.findProvider();\n\n responseCon.wait_for(lock, std::chrono::milliseconds(3000));\n NSStopProvider();\n EXPECT_EQ(ret, NS_OK);\n}\n\nTEST_F(NotificationProviderTest, ExpectCallbackWhenReceiveSubscribeRequestWithAccepterProvider)\n{\n mocks.ExpectCallFunc(NSRequestedSubscribeCallbackEmpty).Do(\n [](NSConsumer * consumer)\n {\n std::cout << \"NSRequestedSubscribeCallback\" << std::endl;\n g_consumer = (NSConsumer *)malloc(sizeof(NSConsumer));\n strncpy(g_consumer->consumerId , consumer->consumerId, 37);\n responseCon.notify_all();\n });\n\n NSProviderConfig config;\n config.subRequestCallback = NSRequestedSubscribeCallbackEmpty;\n config.syncInfoCallback = NSSyncCallbackEmpty;\n config.policy = true;\n config.userInfo = NULL;\n\n NSStartProvider(config);\n\n {\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, g_waitForResponse);\n }\n\n g_consumerSimul.setCallback(NSMessageCallbackFromConsumerEmpty,\n NSSyncCallbackFromConsumerEmpty);\n g_consumerSimul.findProvider();\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(1000));\n}\n\nTEST_F(NotificationProviderTest, NeverCallNotifyOnConsumerByAcceptIsFalse)\n{\n bool expectTrue = true;\n int msgID;\n\n mocks.OnCallFunc(NSMessageCallbackFromConsumerEmpty).Do(\n [& expectTrue, &msgID](const int &id, const std::string&, const std::string&, const std::string&)\n {\n if (id == msgID)\n {\n std::cout << \"This function never call\" << std::endl;\n expectTrue = false;\n }\n });\n\n NSAcceptSubscription(g_consumer, false);\n\n NSMessage * msg = NSCreateMessage();\n msgID = (int)msg->messageId;\n msg->title = strdup(std::string(\"Title\").c_str());\n msg->contentText = strdup(std::string(\"ContentText\").c_str());\n msg->sourceName = strdup(std::string(\"OCF\").c_str());\n\n NSSendMessage(msg);\n {\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, g_waitForResponse);\n }\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(1000));\n\n EXPECT_EQ(expectTrue, true);\n\n NSAcceptSubscription(g_consumer, true);\n}\n\nTEST_F(NotificationProviderTest, ExpectCallNotifyOnConsumerByAcceptIsTrue)\n{\n int msgID;\n\n mocks.ExpectCallFunc(NSMessageCallbackFromConsumerEmpty).Do(\n [&msgID](const int &id, const std::string&, const std::string&, const std::string&)\n {\n std::cout << \"id : \" << id << std::endl;\n if (id == msgID)\n {\n std::cout << \"ExpectCallNotifyOnConsumerByAcceptIsTrue\" << std::endl;\n }\n responseCon.notify_all();\n });\n\n NSAcceptSubscription(g_consumer, true);\n\n NSMessage * msg = new NSMessage();\n msgID = 10;\n msg->title = strdup(std::string(\"Title\").c_str());\n msg->contentText = strdup(std::string(\"ContentText\").c_str());\n msg->sourceName = strdup(std::string(\"OCF\").c_str());\n NSSendMessage(msg);\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait(lock);\n}\n\nTEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadToConsumer)\n{\n int id;\n\n mocks.ExpectCallFunc(NSSyncCallbackFromConsumerEmpty).Do(\n [& id](int & type, int &syncId)\n {\n std::cout << \"NSSyncCallbackEmpty\" << std::endl;\n if (syncId == id &&\n type == NS_SYNC_READ)\n {\n std::cout << \"ExpectCallbackSyncOnReadFromConsumer\" << std::endl;\n responseCon.notify_all();\n }\n });\n\n NSMessage * msg = NSCreateMessage();\n id = (int)msg->messageId;\n msg->title = strdup(std::string(\"Title\").c_str());\n msg->contentText = strdup(std::string(\"ContentText\").c_str());\n msg->sourceName = strdup(std::string(\"OCF\").c_str());\n\n NSProviderSendSyncInfo(msg->messageId, NS_SYNC_READ);\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(5000));\n}\n\nTEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadFromConsumer)\n{\n int type = NS_SYNC_READ;\n int id;\n mocks.ExpectCallFunc(NSSyncCallbackEmpty).Do(\n [& id](NSSyncInfo * sync)\n {\n std::cout << \"NSSyncCallbackEmpty\" << std::endl;\n if ((int)sync->messageId == id && sync->state == NS_SYNC_READ)\n {\n std::cout << \"ExpectCallbackSyncOnReadFromConsumer\" << std::endl;\n responseCon.notify_all();\n }\n });\n\n NSMessage * msg = NSCreateMessage();\n id = (int)msg->messageId;\n msg->title = strdup(std::string(\"Title\").c_str());\n msg->contentText = strdup(std::string(\"ContentText\").c_str());\n msg->sourceName = strdup(std::string(\"OCF\").c_str());\n\n g_consumerSimul.syncToProvider(type, id, msg->providerId);\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(5000));\n}\n\nTEST_F(NotificationProviderTest, CancelObserves)\n{\n bool ret = g_consumerSimul.cancelObserves();\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(5000));\n\n EXPECT_EQ(ret, true);\n}\nBug fixes unittest for ExpectCallNotifyOnConsumerByAcceptIsTrue.\/\/******************************************************************\n\/\/\n\/\/ Copyright 2016 Samsung Electronics All Rights Reserved.\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"NSProviderInterface.h\"\n#include \"NSConsumerSimulator.h\"\n#include \"NSCommon.h\"\n\nnamespace\n{\n std::atomic_bool g_isStartedStack(false);\n\n std::chrono::milliseconds g_waitForResponse(500);\n\n std::condition_variable responseCon;\n std::mutex mutexForCondition;\n\n NSConsumerSimulator g_consumerSimul;\n NSConsumer * g_consumer;\n}\n\nclass TestWithMock: public testing::Test\n{\npublic:\n MockRepository mocks;\n\nprotected:\n virtual ~TestWithMock() noexcept(noexcept(std::declval().~Test())) {}\n\n virtual void TearDown() {\n try\n {\n mocks.VerifyAll();\n }\n catch (...)\n {\n mocks.reset();\n throw;\n }\n }\n};\n\nclass NotificationProviderTest : public TestWithMock\n{\npublic:\n NotificationProviderTest() = default;\n ~NotificationProviderTest() = default;\n\n static void NSRequestedSubscribeCallbackEmpty(NSConsumer *)\n {\n std::cout << __func__ << std::endl;\n }\n\n static void NSSyncCallbackEmpty(NSSyncInfo *)\n {\n std::cout << __func__ << std::endl;\n }\n\n static void NSMessageCallbackFromConsumerEmpty(\n const int &, const std::string &, const std::string &, const std::string &)\n {\n std::cout << __func__ << std::endl;\n }\n\n static void NSSyncCallbackFromConsumerEmpty(int, int)\n {\n std::cout << __func__ << std::endl;\n }\n\nprotected:\n\n void SetUp()\n {\n TestWithMock::SetUp();\n\n if (g_isStartedStack == false)\n {\n OC::PlatformConfig cfg\n {\n OC::ServiceType::InProc,\n OC::ModeType::Both,\n \"0.0.0.0\",\n 0,\n OC::QualityOfService::HighQos\n };\n OC::OCPlatform::Configure(cfg);\n\n try\n {\n OC::OCPlatform::stopPresence();\n }\n catch (...)\n {\n\n }\n\n g_isStartedStack = true;\n }\n\n }\n\n void TearDown()\n {\n TestWithMock::TearDown();\n }\n\n};\n\nTEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyTrue)\n{\n NSProviderConfig config;\n config.subRequestCallback = NSRequestedSubscribeCallbackEmpty;\n config.syncInfoCallback = NSSyncCallbackEmpty;\n config.policy = true;\n config.userInfo = NULL;\n\n NSResult ret = NSStartProvider(config);\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, g_waitForResponse);\n\n EXPECT_EQ(ret, NS_OK);\n}\n\nTEST_F(NotificationProviderTest, StopProviderPositive)\n{\n NSResult ret = NSStopProvider();\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, g_waitForResponse);\n\n EXPECT_EQ(ret, NS_OK);\n}\n\nTEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyFalse)\n{\n NSProviderConfig config;\n config.subRequestCallback = NSRequestedSubscribeCallbackEmpty;\n config.syncInfoCallback = NSSyncCallbackEmpty;\n config.policy = false;\n config.userInfo = NULL;\n\n NSResult ret = NSStartProvider(config);\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(3000));\n g_consumerSimul.findProvider();\n\n responseCon.wait_for(lock, std::chrono::milliseconds(3000));\n NSStopProvider();\n EXPECT_EQ(ret, NS_OK);\n}\n\nTEST_F(NotificationProviderTest, ExpectCallbackWhenReceiveSubscribeRequestWithAccepterProvider)\n{\n mocks.ExpectCallFunc(NSRequestedSubscribeCallbackEmpty).Do(\n [](NSConsumer * consumer)\n {\n std::cout << \"NSRequestedSubscribeCallback\" << std::endl;\n g_consumer = (NSConsumer *)malloc(sizeof(NSConsumer));\n strncpy(g_consumer->consumerId , consumer->consumerId, 37);\n responseCon.notify_all();\n });\n\n NSProviderConfig config;\n config.subRequestCallback = NSRequestedSubscribeCallbackEmpty;\n config.syncInfoCallback = NSSyncCallbackEmpty;\n config.policy = true;\n config.userInfo = NULL;\n\n NSStartProvider(config);\n\n {\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, g_waitForResponse);\n }\n\n g_consumerSimul.setCallback(NSMessageCallbackFromConsumerEmpty,\n NSSyncCallbackFromConsumerEmpty);\n g_consumerSimul.findProvider();\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(1000));\n}\n\nTEST_F(NotificationProviderTest, NeverCallNotifyOnConsumerByAcceptIsFalse)\n{\n bool expectTrue = true;\n int msgID;\n\n mocks.OnCallFunc(NSMessageCallbackFromConsumerEmpty).Do(\n [& expectTrue, &msgID](const int &id, const std::string&, const std::string&, const std::string&)\n {\n if (id == msgID)\n {\n std::cout << \"This function never call\" << std::endl;\n expectTrue = false;\n }\n });\n\n NSAcceptSubscription(g_consumer, false);\n\n NSMessage * msg = NSCreateMessage();\n msgID = (int)msg->messageId;\n msg->title = strdup(std::string(\"Title\").c_str());\n msg->contentText = strdup(std::string(\"ContentText\").c_str());\n msg->sourceName = strdup(std::string(\"OCF\").c_str());\n\n NSSendMessage(msg);\n {\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, g_waitForResponse);\n }\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(1000));\n\n EXPECT_EQ(expectTrue, true);\n\n NSAcceptSubscription(g_consumer, true);\n}\n\nTEST_F(NotificationProviderTest, ExpectCallNotifyOnConsumerByAcceptIsTrue)\n{\n int msgID;\n\n mocks.ExpectCallFunc(NSMessageCallbackFromConsumerEmpty).Do(\n [&msgID](const int &id, const std::string&, const std::string&, const std::string&)\n {\n std::cout << \"id : \" << id << std::endl;\n if (id == msgID)\n {\n std::cout << \"ExpectCallNotifyOnConsumerByAcceptIsTrue\" << std::endl;\n responseCon.notify_all();\n }\n });\n\n NSAcceptSubscription(g_consumer, true);\n\n NSMessage * msg = NSCreateMessage();\n msgID = (int)msg->messageId;\n msg->title = strdup(std::string(\"Title\").c_str());\n msg->contentText = strdup(std::string(\"ContentText\").c_str());\n msg->sourceName = strdup(std::string(\"OCF\").c_str());\n NSSendMessage(msg);\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait(lock);\n}\n\nTEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadToConsumer)\n{\n int id;\n\n mocks.ExpectCallFunc(NSSyncCallbackFromConsumerEmpty).Do(\n [& id](int & type, int &syncId)\n {\n std::cout << \"NSSyncCallbackEmpty\" << std::endl;\n if (syncId == id &&\n type == NS_SYNC_READ)\n {\n std::cout << \"ExpectCallbackSyncOnReadFromConsumer\" << std::endl;\n responseCon.notify_all();\n }\n });\n\n NSMessage * msg = NSCreateMessage();\n id = (int)msg->messageId;\n msg->title = strdup(std::string(\"Title\").c_str());\n msg->contentText = strdup(std::string(\"ContentText\").c_str());\n msg->sourceName = strdup(std::string(\"OCF\").c_str());\n\n NSProviderSendSyncInfo(msg->messageId, NS_SYNC_READ);\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(5000));\n}\n\nTEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadFromConsumer)\n{\n int type = NS_SYNC_READ;\n int id;\n mocks.ExpectCallFunc(NSSyncCallbackEmpty).Do(\n [& id](NSSyncInfo * sync)\n {\n std::cout << \"NSSyncCallbackEmpty\" << std::endl;\n if ((int)sync->messageId == id && sync->state == NS_SYNC_READ)\n {\n std::cout << \"ExpectCallbackSyncOnReadFromConsumer\" << std::endl;\n responseCon.notify_all();\n }\n });\n\n NSMessage * msg = NSCreateMessage();\n id = (int)msg->messageId;\n msg->title = strdup(std::string(\"Title\").c_str());\n msg->contentText = strdup(std::string(\"ContentText\").c_str());\n msg->sourceName = strdup(std::string(\"OCF\").c_str());\n\n g_consumerSimul.syncToProvider(type, id, msg->providerId);\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(5000));\n}\n\nTEST_F(NotificationProviderTest, CancelObserves)\n{\n bool ret = g_consumerSimul.cancelObserves();\n\n std::unique_lock< std::mutex > lock{ mutexForCondition };\n responseCon.wait_for(lock, std::chrono::milliseconds(5000));\n\n EXPECT_EQ(ret, true);\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"util.h\"\n#include \"scrypt.h\"\n\nBOOST_AUTO_TEST_SUITE(scrypt_tests)\n\nBOOST_AUTO_TEST_CASE(scrypt_hashtest)\n{\n \/\/ Test Scrypt hash with known inputs against expected outputs\n #define HASHCOUNT 5\n const char* inputhex[HASHCOUNT] = { \"020000004c1271c211717198227392b029a64a7971931d351b387bb80db027f270411e398a07046f7d4a08dd815412a8712f874a7ebf0507e3878bd24e20a3b73fd750a667d2f451eac7471b00de6659\", \"0200000011503ee6a855e900c00cfdd98f5f55fffeaee9b6bf55bea9b852d9de2ce35828e204eef76acfd36949ae56d1fbe81c1ac9c0209e6331ad56414f9072506a77f8c6faf551eac7471b00389d01\", \"02000000a72c8a177f523946f42f22c3e86b8023221b4105e8007e59e81f6beb013e29aaf635295cb9ac966213fb56e046dc71df5b3f7f67ceaeab24038e743f883aff1aaafaf551eac7471b0166249b\", \"010000007824bc3a8a1b4628485eee3024abd8626721f7f870f8ad4d2f33a27155167f6a4009d1285049603888fe85a84b6c803a53305a8d497965a5e896e1a00568359589faf551eac7471b0065434e\", \"0200000050bfd4e4a307a8cb6ef4aef69abc5c0f2d579648bd80d7733e1ccc3fbc90ed664a7f74006cb11bde87785f229ecd366c2d4e44432832580e0608c579e4cb76f383f7f551eac7471b00c36982\" };\n const char* expected[HASHCOUNT] = { \"00000000002bef4107f882f6115e0b01f348d21195dacd3582aa2dabd7985806\" , \"00000000003a0d11bdd5eb634e08b7feddcfbbf228ed35d250daf19f1c88fc94\", \"00000000000b40f895f288e13244728a6c2d9d59d8aff29c65f8dd5114a8ca81\", \"00000000003007005891cd4923031e99d8e8d72f6e8e7edc6a86181897e105fe\", \"000000000018f0b426a4afc7130ccb47fa02af730d345b4fe7c7724d3800ec8c\" };\n uint256 scrypthash;\n std::vector inputbytes;\n\n for (int i = 0; i < HASHCOUNT; i++) {\n inputbytes = ParseHex(inputhex[i]);\n scrypt_1024_1_1_256((const char*)&inputbytes[0], BEGIN(scrypthash));\n BOOST_CHECK_EQUAL(scrypthash.ToString().c_str(), expected[i]);\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nLitecoin: SSE2 scrypt unit test coverage#include \n\n#include \"util.h\"\n#include \"scrypt.h\"\n\nBOOST_AUTO_TEST_SUITE(scrypt_tests)\n\nBOOST_AUTO_TEST_CASE(scrypt_hashtest)\n{\n \/\/ Test Scrypt hash with known inputs against expected outputs\n #define HASHCOUNT 5\n const char* inputhex[HASHCOUNT] = { \"020000004c1271c211717198227392b029a64a7971931d351b387bb80db027f270411e398a07046f7d4a08dd815412a8712f874a7ebf0507e3878bd24e20a3b73fd750a667d2f451eac7471b00de6659\", \"0200000011503ee6a855e900c00cfdd98f5f55fffeaee9b6bf55bea9b852d9de2ce35828e204eef76acfd36949ae56d1fbe81c1ac9c0209e6331ad56414f9072506a77f8c6faf551eac7471b00389d01\", \"02000000a72c8a177f523946f42f22c3e86b8023221b4105e8007e59e81f6beb013e29aaf635295cb9ac966213fb56e046dc71df5b3f7f67ceaeab24038e743f883aff1aaafaf551eac7471b0166249b\", \"010000007824bc3a8a1b4628485eee3024abd8626721f7f870f8ad4d2f33a27155167f6a4009d1285049603888fe85a84b6c803a53305a8d497965a5e896e1a00568359589faf551eac7471b0065434e\", \"0200000050bfd4e4a307a8cb6ef4aef69abc5c0f2d579648bd80d7733e1ccc3fbc90ed664a7f74006cb11bde87785f229ecd366c2d4e44432832580e0608c579e4cb76f383f7f551eac7471b00c36982\" };\n const char* expected[HASHCOUNT] = { \"00000000002bef4107f882f6115e0b01f348d21195dacd3582aa2dabd7985806\" , \"00000000003a0d11bdd5eb634e08b7feddcfbbf228ed35d250daf19f1c88fc94\", \"00000000000b40f895f288e13244728a6c2d9d59d8aff29c65f8dd5114a8ca81\", \"00000000003007005891cd4923031e99d8e8d72f6e8e7edc6a86181897e105fe\", \"000000000018f0b426a4afc7130ccb47fa02af730d345b4fe7c7724d3800ec8c\" };\n uint256 scrypthash;\n std::vector inputbytes;\n char scratchpad[SCRYPT_SCRATCHPAD_SIZE];\n for (int i = 0; i < HASHCOUNT; i++) {\n inputbytes = ParseHex(inputhex[i]);\n#if defined(USE_SSE2)\n \/\/ Test SSE2 scrypt\n scrypt_1024_1_1_256_sp_sse2((const char*)&inputbytes[0], BEGIN(scrypthash), scratchpad);\n#endif\n \/\/ Test generic scrypt\n scrypt_1024_1_1_256_sp_generic((const char*)&inputbytes[0], BEGIN(scrypthash), scratchpad);\n BOOST_CHECK_EQUAL(scrypthash.ToString().c_str(), expected[i]);\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 6\/16\/2020, 3:58:35 AM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nbool ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n return true;\n }\n return false;\n}\ntemplate \nbool ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n return true;\n }\n return false;\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, Mint const &rhs) { return rhs + lhs; }\ntemplate \nMint operator-(ll lhs, Mint const &rhs) { return -rhs + lhs; }\ntemplate \nMint operator*(ll lhs, Mint const &rhs) { return rhs * lhs; }\ntemplate \nMint operator\/(ll lhs, Mint const &rhs) { return Mint{lhs} \/ rhs; }\ntemplate \nistream &operator>>(istream &stream, Mint &a) { return stream >> a.x; }\ntemplate \nostream &operator<<(ostream &stream, Mint const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- Infty -----\ntemplate \nconstexpr T Infty() { return numeric_limits::max(); }\ntemplate \nconstexpr T mInfty() { return numeric_limits::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\nconstexpr int dx[4] = {1, 0, -1, 0};\nconstexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- WarshallFloyd -----\n\ntemplate \nvoid WarshallFloyd(vector> &V, T infinity = numeric_limits::max())\n{\n \/\/ It is valid to apply this method for\n \/\/ - a directed\/undirected graph,\n \/\/ - a graph whose edge may be negative.\n \/\/ - Negative cycle can be detected by V[i][i] < 0 if we initialize V[i][i] = 0.\n auto N{static_cast(V.size())};\n for (auto k{0}; k < N; ++k)\n {\n for (auto i{0}; i < N; ++i)\n {\n for (auto j{0}; j < N; ++j)\n {\n if (V[i][k] == infinity || V[k][j] == infinity)\n {\n continue;\n }\n ch_min(V[i][j], V[i][k] + V[k][j]);\n }\n }\n }\n}\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n int H, W, K;\n vector S;\n vector> toID;\n\npublic:\n Solve(int H, int W) : H{H}, W{W}, S(H), toID(H, vector(W, -1))\n {\n for (auto i{0}; i < H; ++i)\n {\n cin >> S[i];\n }\n int id{0};\n for (auto i{0}; i < H; ++i)\n {\n for (auto j{0}; j < W; ++j)\n {\n if (S[i][j] == '.')\n {\n toID[i][j] = id++;\n }\n }\n }\n K = id;\n }\n\n void flush()\n {\n vector> D(K, vector(K, Infty()));\n for (auto i{0}; i < H; ++i)\n {\n for (auto j{0}; j < W; ++j)\n {\n for (auto k{0}; k < 4; ++k)\n {\n int nx{i + dx[k]};\n int ny{j + dy[k]};\n if (0 <= nx && nx < H && 0 <= ny && ny < W && toID[nx][ny] != -1)\n {\n int s{toID[i][j]};\n int t{toID[nx][ny]};\n#if DEBUG == 1\n cerr << \"s = \" << s << \", t = \" << t << endl;\n#endif\n D[s][t] = 1;\n D[t][s] = 1;\n }\n }\n }\n }\n WarshallFloyd(D);\n int ans{0};\n for (auto i{0}; i < K; ++i)\n {\n for (auto j{i + 1}; j < K; ++j)\n {\n ch_max(ans, D[i][j]);\n }\n }\n cout << ans << endl;\n }\n\nprivate:\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n int H, W;\n cin >> H >> W;\n Solve solve(H, W);\n solve.flush();\n}\nsubmit D.cpp to 'D - Maze Master' (abc151) [C++14 (GCC 5.4.1)]#define DEBUG 1\n\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 6\/16\/2020, 3:58:35 AM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nbool ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n return true;\n }\n return false;\n}\ntemplate \nbool ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n return true;\n }\n return false;\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, Mint const &rhs) { return rhs + lhs; }\ntemplate \nMint operator-(ll lhs, Mint const &rhs) { return -rhs + lhs; }\ntemplate \nMint operator*(ll lhs, Mint const &rhs) { return rhs * lhs; }\ntemplate \nMint operator\/(ll lhs, Mint const &rhs) { return Mint{lhs} \/ rhs; }\ntemplate \nistream &operator>>(istream &stream, Mint &a) { return stream >> a.x; }\ntemplate \nostream &operator<<(ostream &stream, Mint const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- Infty -----\ntemplate \nconstexpr T Infty() { return numeric_limits::max(); }\ntemplate \nconstexpr T mInfty() { return numeric_limits::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\nconstexpr int dx[4] = {1, 0, -1, 0};\nconstexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- WarshallFloyd -----\n\ntemplate \nvoid WarshallFloyd(vector> &V, T infinity = numeric_limits::max())\n{\n \/\/ It is valid to apply this method for\n \/\/ - a directed\/undirected graph,\n \/\/ - a graph whose edge may be negative.\n \/\/ - Negative cycle can be detected by V[i][i] < 0 if we initialize V[i][i] = 0.\n auto N{static_cast(V.size())};\n for (auto k{0}; k < N; ++k)\n {\n for (auto i{0}; i < N; ++i)\n {\n for (auto j{0}; j < N; ++j)\n {\n if (V[i][k] == infinity || V[k][j] == infinity)\n {\n continue;\n }\n ch_min(V[i][j], V[i][k] + V[k][j]);\n }\n }\n }\n}\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n int H, W, K;\n vector S;\n vector> toID;\n\npublic:\n Solve(int H, int W) : H{H}, W{W}, S(H), toID(H, vector(W, -1))\n {\n for (auto i{0}; i < H; ++i)\n {\n cin >> S[i];\n }\n int id{0};\n for (auto i{0}; i < H; ++i)\n {\n for (auto j{0}; j < W; ++j)\n {\n if (S[i][j] == '.')\n {\n toID[i][j] = id++;\n }\n }\n }\n K = id;\n }\n\n void flush()\n {\n vector> D(K, vector(K, Infty()));\n for (auto i{0}; i < H; ++i)\n {\n for (auto j{0}; j < W; ++j)\n {\n if (toID[i][j] == -1)\n {\n continue;\n }\n for (auto k{0}; k < 4; ++k)\n {\n int nx{i + dx[k]};\n int ny{j + dy[k]};\n if (0 <= nx && nx < H && 0 <= ny && ny < W && toID[nx][ny] != -1)\n {\n int s{toID[i][j]};\n int t{toID[nx][ny]};\n#if DEBUG == 1\n cerr << \"s = \" << s << \", t = \" << t << endl;\n#endif\n D[s][t] = 1;\n D[t][s] = 1;\n }\n }\n }\n }\n WarshallFloyd(D);\n int ans{0};\n for (auto i{0}; i < K; ++i)\n {\n for (auto j{i + 1}; j < K; ++j)\n {\n ch_max(ans, D[i][j]);\n }\n }\n cout << ans << endl;\n }\n\nprivate:\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n int H, W;\n cin >> H >> W;\n Solve solve(H, W);\n solve.flush();\n}\n<|endoftext|>"} {"text":"#ifndef RBX_VM_BUILTIN_OBJECT_HPP\n#define RBX_VM_BUILTIN_OBJECT_HPP\n\n#include \n\n#include \"vm.hpp\"\n#include \"oop.hpp\"\n#include \"type_info.hpp\"\n#include \"executor.hpp\"\n#include \"objectmemory.hpp\"\n\nnamespace rubinius {\n\n\/**\n * Create a writer method for a slot.\n *\n * For attr_writer(foo, SomeClass), creates void foo(STATE, SomeClass* obj)\n * that sets the instance variable foo_ to the object given and runs the write\n * barrier.\n *\/\n#define attr_writer(name, type) \\\n template \\\n void name(T state, type* obj) { \\\n name ## _ = obj; \\\n this->write_barrier(state, obj); \\\n }\n\n\/**\n * Create a reader method for a slot.\n *\n * For attr_reader(foo, SomeClass), creates SomeClass* foo() which returns the\n * instance variable foo_. A const version is also generated.\n *\/\n#define attr_reader(name, type) \\\n type* name() const { return name ## _; }\n\n\/**\n * Ruby-like accessor creation for a slot.\n *\n * Both attr_writer and attr_reader.\n *\/\n#define attr_accessor(name, type) \\\n attr_reader(name, type) \\\n attr_writer(name, type)\n\n \/* Forwards *\/\n class Fixnum;\n class Integer;\n class String;\n class Module;\n class Executable;\n class Array;\n class Object;\n\n \/**\n * Object is the basic Ruby object.\n *\n * Because of needing to exactly control the in-memory layout of\n * Objects, none of the subclasses of Object (or ObjectHeader)\n * is allowed to use define virtual methods. In order to achieve\n * virtual dispatch for the cases where it is needed (it usually\n * is not), the TypeInfo class should be used. Each builtin class\n * defines a contained type Info which inherits--directly or not\n * from TypeInfo. TypeInfos use virtual methods to achieve dynamism.\n * Instances of these Info classes are held by the VM, where they\n * can be retrieved using a given Object's object_type. The Info\n * object will then dispatch the correct virtual method for the\n * type. The methods are written to understand the types they are\n * dealing with.\n *\n * The class definition layout differs from the normal alphabetic\n * order in order to group the different aspects involved better\n * and to simplify finding\/adding &c. related methods.\n *\n * @todo The entire codebase should be reviewed for const\n * correctness. --rue\n *\n * @todo Remove the unimplemented definitions? --rue\n *\n * @see vm\/type_info.hpp\n *\n *\/\n class Object : public ObjectHeader {\n public: \/* Slots and bookkeeping *\/\n\n \/** Class type identifier. *\/\n static const object_type type = ObjectType;\n\n static void bootstrap_methods(STATE);\n\n public: \/* GC support, bookkeeping &c. *\/\n\n \/** Provides access to the GC write barrier from any object. *\/\n void write_barrier(STATE, void* obj);\n void write_barrier(VM*, void* obj);\n\n \/** Special-case write_barrier() for Fixnums. *\/\n void write_barrier(STATE, Fixnum* obj);\n \/** Special-case write_barrier() for Symbols. *\/\n void write_barrier(STATE, Symbol* obj);\n\n void write_barrier(ObjectMemory* om, void* obj);\n\n void setup_allocation_site(STATE, CallFrame* call_frame = NULL);\n\n public: \/* Type information, field access, copy support &c. *\/\n\n \/**\n * Returns a copy of this object. This is NOT the same as Ruby\n * Kernel#dup. Code that needs Kernel#dup semantics MUST call\n * #dup from Ruby. This method is used in the VM to duplicate\n * data structures. It will not call the Ruby allocate() or\n * initialize_copy() methods.\n *\/\n Object* duplicate(STATE);\n\n Object* copy_object(STATE, Object* other);\n\n \/**\n * Copies the object including any instance variables. Called by\n * Kernel#dup.\n *\/\n\n \/\/ Rubinius.primitive :object_copy_object\n Object* copy_object_prim(STATE, Object* other, CallFrame* calling_environment);\n\n \/**\n * Copies this Object's MetaClass to the other Object. Called\n * by Kernel#clone.\n *\/\n \/\/ Rubinius.primitive :object_copy_singleton_class\n Object* copy_singleton_class(STATE, GCToken gct, Object* other, CallFrame* calling_environment);\n\n \/** True if this Object* is actually a Fixnum, false otherwise. *\/\n bool fixnum_p() const;\n\n \/**\n * Retrieve the Object stored in given field index of this Object.\n *\n * Uses TypeInfo.\n *\/\n Object* get_field(STATE, std::size_t index);\n\n \/** Safely return the object type, even if the receiver is an immediate. *\/\n object_type get_type() const;\n\n \/** True if given Module is this Object's class, superclass or an included Module. *\/\n bool kind_of_p(STATE, Object* module);\n\n \/** Store the given Object at given field index of this Object through TypeInfo. *\/\n void set_field(STATE, std::size_t index, Object* val);\n\n \/** True if this Object* is actually a Symbol, false otherwise. *\/\n bool symbol_p() const;\n\n \/** Return the TypeInfo for this Object's type. *\/\n TypeInfo* type_info(STATE) const;\n\n\n public: \/* Method dispatch stuff *\/\n\n \/** Actual class for this object. Also handles immediates *\/\n Class* direct_class(STATE) const;\n\n \/** Module where to start looking for the MethodTable for this Object. *\/\n Module* lookup_begin(STATE) const;\n\n \/**\n * Directly send a method to this Object.\n *\n * Sets up the current task to send the given method name to this\n * Object, passing the given number of arguments through varargs.\n *\/\n Object* send(STATE, CallFrame* caller, Symbol* name, Array* args,\n Object* block = cNil, bool allow_private = true);\n Object* send(STATE, CallFrame* caller, Symbol* name, bool allow_private = true);\n\n Object* send_prim(STATE, CallFrame* call_frame, Executable* exec, Module* mod, Arguments& args,\n Symbol* min_visibility);\n\n \/**\n * Ruby #send\/#__send__\n *\/\n \/\/ Rubinius.primitive? :object_send\n Object* private_send_prim(STATE, CallFrame* call_frame, Executable* exec, Module* mod, Arguments& args);\n\n \/**\n * Ruby #public_send\n *\/\n \/\/ Rubinius.primitive? :object_public_send\n Object* public_send_prim(STATE, CallFrame* call_frame, Executable* exec, Module* mod, Arguments& args);\n\n\n public: \/* Ruby interface *\/\n\n \/** Returns the Class object of which this Object is an instance. *\/\n \/\/ Rubinius.primitive+ :object_class\n Class* class_object(STATE) const;\n\n \/**\n * Ruby #equal?.\n *\n * Returns true if and only if this and the other object are\n * the SAME object, false otherwise.\n *\/\n \/\/ Rubinius.primitive+ :object_equal\n Object* equal(STATE, Object* other);\n\n \/** Sets the frozen flag. Rubinius does NOT currently support freezing. *\/\n \/\/ Rubinius.primitive :object_freeze\n Object* freeze(STATE);\n\n \/** Returns true if this Object's frozen flag set, false otherwise. *\/\n \/\/ Rubinius.primitive+ :object_frozen_p\n Object* frozen_p(STATE);\n\n \/**\n * Ruby #instance_variable_get.\n *\n * Return the Object stored as instance variable under the given\n * identifier.\n *\/\n \/\/ Rubinius.primitive :object_get_ivar\n Object* get_ivar_prim(STATE, Symbol* sym);\n\n Object* get_ivar(STATE, Symbol* sym);\n\n \/\/ A version that only attempts to find +sym+ in the ivars slot\n Object* get_table_ivar(STATE, Symbol* sym);\n\n \/\/ Rubinius.primitive :object_del_ivar\n Object* del_ivar(STATE, Symbol* sym);\n Object* del_table_ivar(STATE, Symbol* sym, bool* removed = 0);\n\n Object* table_ivar_defined(STATE, Symbol* sym);\n\n Object* ivar_defined(STATE, Symbol* sym);\n\n \/\/ Rubinius.primitive :object_ivar_defined\n Object* ivar_defined_prim(STATE, Symbol* sym);\n\n \/** Returns the structure containing this object's instance variables. *\/\n \/\/ Rubinius.primitive :object_ivar_names\n Array* ivar_names(STATE);\n\n Array* ivar_names(STATE, Array* ary);\n\n \/** Calculate a hash value for this object. *\/\n hashval hash(STATE);\n\n \/** Returns the hash value as an Integer. @see hash(). *\/\n \/\/ Rubinius.primitive+ :object_hash\n Integer* hash_prim(STATE);\n\n \/** Returns an Integer ID for this object. Created as needed. *\/\n \/\/ Rubinius.primitive+ :object_id\n Integer* id(STATE);\n\n \/** Indicates if this object has been assigned an object id. *\/\n bool has_id(STATE);\n\n \/** Reset the object id *\/\n void reset_id(STATE);\n\n \/\/ Rubinius.primitive+ :object_infect\n Object* infect_prim(STATE, Object* obj, Object* other) {\n other->infect(state, obj);\n return obj;\n }\n\n \/**\n * Taints other if this is tainted.\n *\/\n void infect(STATE, Object* other);\n\n \/**\n * Ruby #kind_of?\n *\n * Returns true if given Module is this Object's class,\n * superclass or an included Module, false otherwise.\n *\/\n \/\/ Rubinius.primitive+ :object_kind_of\n Object* kind_of_prim(STATE, Module* klass);\n\n \/**\n * Ruby #instance_of?\n *\n * Returns true if given Module is this Object's class,\n * false otherwise.\n *\/\n \/\/ Rubinius.primitive+ :object_instance_of\n Object* instance_of_prim(STATE, Module* klass);\n\n \/** Return object's MetaClass object. Created as needed.\n * Also fixes up the parent hierarchy if needed *\/\n Class* singleton_class(STATE);\n\n \/** Return object's MetaClass object. Created as needed. *\/\n Class* singleton_class_instance(STATE);\n\n \/**\n * Ruby #instance_variable_set\n *\n * Store the given object in the instance variable by\n * given identifier.\n *\/\n \/\/ Rubinius.primitive :object_set_ivar\n Object* set_ivar_prim(STATE, Symbol* sym, Object* val);\n\n Object* set_ivar(STATE, Symbol* sym, Object* val);\n\n \/\/ Specialized version that only checks ivars_\n Object* set_table_ivar(STATE, Symbol* sym, Object* val);\n\n \/** String describing this object (through TypeInfo.) *\/\n \/\/ Rubinius.primitive :object_show\n Object* show(STATE);\n \/** Indented String describing this object (through TypeInfo.) *\/\n Object* show(STATE, int level);\n \/** Shorter String describing this object (through TypeInfo.) *\/\n Object* show_simple(STATE);\n \/** Shorter indented String describing this object (through TypeInfo.) *\/\n Object* show_simple(STATE, int level);\n\n \/**\n * Set tainted flag on this object.\n *\/\n \/\/ Rubinius.primitive :object_taint\n Object* taint(STATE);\n\n \/**\n * Returns true if this object's tainted flag is set.\n *\/\n \/\/ Rubinius.primitive+ :object_tainted_p\n Object* tainted_p(STATE);\n\n \/**\n * Clears the tainted flag on this object.\n *\/\n \/\/ Rubinius.primitive :object_untaint\n Object* untaint(STATE);\n\n \/**\n * Returns true if this object's untrusted flag is set.\n *\/\n \/\/ Rubinius.primitive+ :object_untrusted_p\n Object* untrusted_p(STATE);\n\n \/**\n * Sets the untrusted flag on this object.\n *\/\n \/\/ Rubinius.primitive :object_untrust\n Object* untrust(STATE);\n\n \/**\n * Clears the untrusted flag on this object.\n *\/\n \/\/ Rubinius.primitive :object_trust\n Object* trust(STATE);\n\n \/**\n * Returns an #inspect-like representation of an Object for\n * use in C++ code.\n *\n * If address is true, uses the actual address of the object.\n * Otherwise, uses the object's id().\n *\/\n std::string to_string(STATE, bool address = false);\n\n \/**\n * Returns an #inspect-like representation of an Object for\n * use in C++ code. Not called from Ruby code.\n *\n * If address is true, uses the actual address of the object.\n * Otherwise, uses the object's id().\n *\/\n String* to_s(STATE, bool address = false);\n\n \/**\n *\n * Returns cTrue if this responds to method +meth+\n *\/\n \/\/ Rubinius.primitive+ :object_respond_to\n Object* respond_to(STATE, Symbol* name, Object* priv, CallFrame* calling_environment);\n\n Object* respond_to(STATE, Symbol* name, Object* priv);\n\n \/**\n * Checks if object is frozen and raises RuntimeError if it is.\n * Similar to CRuby rb_check_frozen\n *\/\n void check_frozen(STATE);\n\n public: \/* accessors *\/\n\n \/* klass_ from ObjectHeader. *\/\n attr_reader(klass, Class);\n\n template \n inline void klass(T state, Class* cls) {\n if(klass_ != cls) {\n klass_ = cls;\n this->write_barrier(state, cls);\n }\n }\n\n \/* ivars_ from ObjectHeader. *\/\n attr_accessor(ivars, Object);\n\n\n public: \/* TypeInfo *\/\n\n \/**\n * Static type information for Object.\n *\/\n class Info : public TypeInfo {\n public:\n virtual ~Info() {}\n Info(object_type type)\n : TypeInfo(type)\n {}\n\n virtual void auto_mark(Object* obj, ObjectMark& mark) {}\n };\n };\n\n\/* Object inlines -- Alphabetic, unlike class definition. *\/\n\n inline bool Object::fixnum_p() const {\n return __FIXNUM_P__(this);\n }\n\n inline Class* Object::direct_class(STATE) const {\n if(reference_p()) {\n return klass_;\n }\n\n return state->globals().special_classes[((uintptr_t)this) & SPECIAL_CLASS_MASK].get();\n }\n\n inline Module* Object::lookup_begin(STATE) const {\n return reinterpret_cast(direct_class(state));\n }\n\n inline bool Object::symbol_p() const {\n return __SYMBOL_P__(this);\n }\n\n inline void Object::write_barrier(STATE, Fixnum* obj) {\n \/* No-op *\/\n }\n\n inline void Object::write_barrier(STATE, Symbol* obj) {\n \/* No-op *\/\n }\n\n inline void Object::write_barrier(STATE, void* ptr) {\n Object* obj = reinterpret_cast(ptr);\n state->memory()->write_barrier(this, obj);\n }\n\n inline void Object::write_barrier(VM* vm, void* ptr) {\n Object* obj = reinterpret_cast(ptr);\n vm->om->write_barrier(this, obj);\n }\n\n \/\/ Used in filtering APIs\n class ObjectMatcher {\n public:\n virtual ~ObjectMatcher() {}\n virtual bool match_p(STATE, Object* obj) = 0;\n };\n\n class ObjectMatchAll : public ObjectMatcher {\n public:\n virtual ~ObjectMatchAll() {}\n virtual bool match_p(STATE, Object* obj) { return true; }\n };\n\n}\n\n#endif\nThis check would cause conditional jumps on uninitialized data#ifndef RBX_VM_BUILTIN_OBJECT_HPP\n#define RBX_VM_BUILTIN_OBJECT_HPP\n\n#include \n\n#include \"vm.hpp\"\n#include \"oop.hpp\"\n#include \"type_info.hpp\"\n#include \"executor.hpp\"\n#include \"objectmemory.hpp\"\n\nnamespace rubinius {\n\n\/**\n * Create a writer method for a slot.\n *\n * For attr_writer(foo, SomeClass), creates void foo(STATE, SomeClass* obj)\n * that sets the instance variable foo_ to the object given and runs the write\n * barrier.\n *\/\n#define attr_writer(name, type) \\\n template \\\n void name(T state, type* obj) { \\\n name ## _ = obj; \\\n this->write_barrier(state, obj); \\\n }\n\n\/**\n * Create a reader method for a slot.\n *\n * For attr_reader(foo, SomeClass), creates SomeClass* foo() which returns the\n * instance variable foo_. A const version is also generated.\n *\/\n#define attr_reader(name, type) \\\n type* name() const { return name ## _; }\n\n\/**\n * Ruby-like accessor creation for a slot.\n *\n * Both attr_writer and attr_reader.\n *\/\n#define attr_accessor(name, type) \\\n attr_reader(name, type) \\\n attr_writer(name, type)\n\n \/* Forwards *\/\n class Fixnum;\n class Integer;\n class String;\n class Module;\n class Executable;\n class Array;\n class Object;\n\n \/**\n * Object is the basic Ruby object.\n *\n * Because of needing to exactly control the in-memory layout of\n * Objects, none of the subclasses of Object (or ObjectHeader)\n * is allowed to use define virtual methods. In order to achieve\n * virtual dispatch for the cases where it is needed (it usually\n * is not), the TypeInfo class should be used. Each builtin class\n * defines a contained type Info which inherits--directly or not\n * from TypeInfo. TypeInfos use virtual methods to achieve dynamism.\n * Instances of these Info classes are held by the VM, where they\n * can be retrieved using a given Object's object_type. The Info\n * object will then dispatch the correct virtual method for the\n * type. The methods are written to understand the types they are\n * dealing with.\n *\n * The class definition layout differs from the normal alphabetic\n * order in order to group the different aspects involved better\n * and to simplify finding\/adding &c. related methods.\n *\n * @todo The entire codebase should be reviewed for const\n * correctness. --rue\n *\n * @todo Remove the unimplemented definitions? --rue\n *\n * @see vm\/type_info.hpp\n *\n *\/\n class Object : public ObjectHeader {\n public: \/* Slots and bookkeeping *\/\n\n \/** Class type identifier. *\/\n static const object_type type = ObjectType;\n\n static void bootstrap_methods(STATE);\n\n public: \/* GC support, bookkeeping &c. *\/\n\n \/** Provides access to the GC write barrier from any object. *\/\n void write_barrier(STATE, void* obj);\n void write_barrier(VM*, void* obj);\n\n \/** Special-case write_barrier() for Fixnums. *\/\n void write_barrier(STATE, Fixnum* obj);\n \/** Special-case write_barrier() for Symbols. *\/\n void write_barrier(STATE, Symbol* obj);\n\n void write_barrier(ObjectMemory* om, void* obj);\n\n void setup_allocation_site(STATE, CallFrame* call_frame = NULL);\n\n public: \/* Type information, field access, copy support &c. *\/\n\n \/**\n * Returns a copy of this object. This is NOT the same as Ruby\n * Kernel#dup. Code that needs Kernel#dup semantics MUST call\n * #dup from Ruby. This method is used in the VM to duplicate\n * data structures. It will not call the Ruby allocate() or\n * initialize_copy() methods.\n *\/\n Object* duplicate(STATE);\n\n Object* copy_object(STATE, Object* other);\n\n \/**\n * Copies the object including any instance variables. Called by\n * Kernel#dup.\n *\/\n\n \/\/ Rubinius.primitive :object_copy_object\n Object* copy_object_prim(STATE, Object* other, CallFrame* calling_environment);\n\n \/**\n * Copies this Object's MetaClass to the other Object. Called\n * by Kernel#clone.\n *\/\n \/\/ Rubinius.primitive :object_copy_singleton_class\n Object* copy_singleton_class(STATE, GCToken gct, Object* other, CallFrame* calling_environment);\n\n \/** True if this Object* is actually a Fixnum, false otherwise. *\/\n bool fixnum_p() const;\n\n \/**\n * Retrieve the Object stored in given field index of this Object.\n *\n * Uses TypeInfo.\n *\/\n Object* get_field(STATE, std::size_t index);\n\n \/** Safely return the object type, even if the receiver is an immediate. *\/\n object_type get_type() const;\n\n \/** True if given Module is this Object's class, superclass or an included Module. *\/\n bool kind_of_p(STATE, Object* module);\n\n \/** Store the given Object at given field index of this Object through TypeInfo. *\/\n void set_field(STATE, std::size_t index, Object* val);\n\n \/** True if this Object* is actually a Symbol, false otherwise. *\/\n bool symbol_p() const;\n\n \/** Return the TypeInfo for this Object's type. *\/\n TypeInfo* type_info(STATE) const;\n\n\n public: \/* Method dispatch stuff *\/\n\n \/** Actual class for this object. Also handles immediates *\/\n Class* direct_class(STATE) const;\n\n \/** Module where to start looking for the MethodTable for this Object. *\/\n Module* lookup_begin(STATE) const;\n\n \/**\n * Directly send a method to this Object.\n *\n * Sets up the current task to send the given method name to this\n * Object, passing the given number of arguments through varargs.\n *\/\n Object* send(STATE, CallFrame* caller, Symbol* name, Array* args,\n Object* block = cNil, bool allow_private = true);\n Object* send(STATE, CallFrame* caller, Symbol* name, bool allow_private = true);\n\n Object* send_prim(STATE, CallFrame* call_frame, Executable* exec, Module* mod, Arguments& args,\n Symbol* min_visibility);\n\n \/**\n * Ruby #send\/#__send__\n *\/\n \/\/ Rubinius.primitive? :object_send\n Object* private_send_prim(STATE, CallFrame* call_frame, Executable* exec, Module* mod, Arguments& args);\n\n \/**\n * Ruby #public_send\n *\/\n \/\/ Rubinius.primitive? :object_public_send\n Object* public_send_prim(STATE, CallFrame* call_frame, Executable* exec, Module* mod, Arguments& args);\n\n\n public: \/* Ruby interface *\/\n\n \/** Returns the Class object of which this Object is an instance. *\/\n \/\/ Rubinius.primitive+ :object_class\n Class* class_object(STATE) const;\n\n \/**\n * Ruby #equal?.\n *\n * Returns true if and only if this and the other object are\n * the SAME object, false otherwise.\n *\/\n \/\/ Rubinius.primitive+ :object_equal\n Object* equal(STATE, Object* other);\n\n \/** Sets the frozen flag. Rubinius does NOT currently support freezing. *\/\n \/\/ Rubinius.primitive :object_freeze\n Object* freeze(STATE);\n\n \/** Returns true if this Object's frozen flag set, false otherwise. *\/\n \/\/ Rubinius.primitive+ :object_frozen_p\n Object* frozen_p(STATE);\n\n \/**\n * Ruby #instance_variable_get.\n *\n * Return the Object stored as instance variable under the given\n * identifier.\n *\/\n \/\/ Rubinius.primitive :object_get_ivar\n Object* get_ivar_prim(STATE, Symbol* sym);\n\n Object* get_ivar(STATE, Symbol* sym);\n\n \/\/ A version that only attempts to find +sym+ in the ivars slot\n Object* get_table_ivar(STATE, Symbol* sym);\n\n \/\/ Rubinius.primitive :object_del_ivar\n Object* del_ivar(STATE, Symbol* sym);\n Object* del_table_ivar(STATE, Symbol* sym, bool* removed = 0);\n\n Object* table_ivar_defined(STATE, Symbol* sym);\n\n Object* ivar_defined(STATE, Symbol* sym);\n\n \/\/ Rubinius.primitive :object_ivar_defined\n Object* ivar_defined_prim(STATE, Symbol* sym);\n\n \/** Returns the structure containing this object's instance variables. *\/\n \/\/ Rubinius.primitive :object_ivar_names\n Array* ivar_names(STATE);\n\n Array* ivar_names(STATE, Array* ary);\n\n \/** Calculate a hash value for this object. *\/\n hashval hash(STATE);\n\n \/** Returns the hash value as an Integer. @see hash(). *\/\n \/\/ Rubinius.primitive+ :object_hash\n Integer* hash_prim(STATE);\n\n \/** Returns an Integer ID for this object. Created as needed. *\/\n \/\/ Rubinius.primitive+ :object_id\n Integer* id(STATE);\n\n \/** Indicates if this object has been assigned an object id. *\/\n bool has_id(STATE);\n\n \/** Reset the object id *\/\n void reset_id(STATE);\n\n \/\/ Rubinius.primitive+ :object_infect\n Object* infect_prim(STATE, Object* obj, Object* other) {\n other->infect(state, obj);\n return obj;\n }\n\n \/**\n * Taints other if this is tainted.\n *\/\n void infect(STATE, Object* other);\n\n \/**\n * Ruby #kind_of?\n *\n * Returns true if given Module is this Object's class,\n * superclass or an included Module, false otherwise.\n *\/\n \/\/ Rubinius.primitive+ :object_kind_of\n Object* kind_of_prim(STATE, Module* klass);\n\n \/**\n * Ruby #instance_of?\n *\n * Returns true if given Module is this Object's class,\n * false otherwise.\n *\/\n \/\/ Rubinius.primitive+ :object_instance_of\n Object* instance_of_prim(STATE, Module* klass);\n\n \/** Return object's MetaClass object. Created as needed.\n * Also fixes up the parent hierarchy if needed *\/\n Class* singleton_class(STATE);\n\n \/** Return object's MetaClass object. Created as needed. *\/\n Class* singleton_class_instance(STATE);\n\n \/**\n * Ruby #instance_variable_set\n *\n * Store the given object in the instance variable by\n * given identifier.\n *\/\n \/\/ Rubinius.primitive :object_set_ivar\n Object* set_ivar_prim(STATE, Symbol* sym, Object* val);\n\n Object* set_ivar(STATE, Symbol* sym, Object* val);\n\n \/\/ Specialized version that only checks ivars_\n Object* set_table_ivar(STATE, Symbol* sym, Object* val);\n\n \/** String describing this object (through TypeInfo.) *\/\n \/\/ Rubinius.primitive :object_show\n Object* show(STATE);\n \/** Indented String describing this object (through TypeInfo.) *\/\n Object* show(STATE, int level);\n \/** Shorter String describing this object (through TypeInfo.) *\/\n Object* show_simple(STATE);\n \/** Shorter indented String describing this object (through TypeInfo.) *\/\n Object* show_simple(STATE, int level);\n\n \/**\n * Set tainted flag on this object.\n *\/\n \/\/ Rubinius.primitive :object_taint\n Object* taint(STATE);\n\n \/**\n * Returns true if this object's tainted flag is set.\n *\/\n \/\/ Rubinius.primitive+ :object_tainted_p\n Object* tainted_p(STATE);\n\n \/**\n * Clears the tainted flag on this object.\n *\/\n \/\/ Rubinius.primitive :object_untaint\n Object* untaint(STATE);\n\n \/**\n * Returns true if this object's untrusted flag is set.\n *\/\n \/\/ Rubinius.primitive+ :object_untrusted_p\n Object* untrusted_p(STATE);\n\n \/**\n * Sets the untrusted flag on this object.\n *\/\n \/\/ Rubinius.primitive :object_untrust\n Object* untrust(STATE);\n\n \/**\n * Clears the untrusted flag on this object.\n *\/\n \/\/ Rubinius.primitive :object_trust\n Object* trust(STATE);\n\n \/**\n * Returns an #inspect-like representation of an Object for\n * use in C++ code.\n *\n * If address is true, uses the actual address of the object.\n * Otherwise, uses the object's id().\n *\/\n std::string to_string(STATE, bool address = false);\n\n \/**\n * Returns an #inspect-like representation of an Object for\n * use in C++ code. Not called from Ruby code.\n *\n * If address is true, uses the actual address of the object.\n * Otherwise, uses the object's id().\n *\/\n String* to_s(STATE, bool address = false);\n\n \/**\n *\n * Returns cTrue if this responds to method +meth+\n *\/\n \/\/ Rubinius.primitive+ :object_respond_to\n Object* respond_to(STATE, Symbol* name, Object* priv, CallFrame* calling_environment);\n\n Object* respond_to(STATE, Symbol* name, Object* priv);\n\n \/**\n * Checks if object is frozen and raises RuntimeError if it is.\n * Similar to CRuby rb_check_frozen\n *\/\n void check_frozen(STATE);\n\n public: \/* accessors *\/\n\n \/* klass_ from ObjectHeader. *\/\n attr_accessor(klass, Class);\n\n \/* ivars_ from ObjectHeader. *\/\n attr_accessor(ivars, Object);\n\n\n public: \/* TypeInfo *\/\n\n \/**\n * Static type information for Object.\n *\/\n class Info : public TypeInfo {\n public:\n virtual ~Info() {}\n Info(object_type type)\n : TypeInfo(type)\n {}\n\n virtual void auto_mark(Object* obj, ObjectMark& mark) {}\n };\n };\n\n\/* Object inlines -- Alphabetic, unlike class definition. *\/\n\n inline bool Object::fixnum_p() const {\n return __FIXNUM_P__(this);\n }\n\n inline Class* Object::direct_class(STATE) const {\n if(reference_p()) {\n return klass_;\n }\n\n return state->globals().special_classes[((uintptr_t)this) & SPECIAL_CLASS_MASK].get();\n }\n\n inline Module* Object::lookup_begin(STATE) const {\n return reinterpret_cast(direct_class(state));\n }\n\n inline bool Object::symbol_p() const {\n return __SYMBOL_P__(this);\n }\n\n inline void Object::write_barrier(STATE, Fixnum* obj) {\n \/* No-op *\/\n }\n\n inline void Object::write_barrier(STATE, Symbol* obj) {\n \/* No-op *\/\n }\n\n inline void Object::write_barrier(STATE, void* ptr) {\n Object* obj = reinterpret_cast(ptr);\n state->memory()->write_barrier(this, obj);\n }\n\n inline void Object::write_barrier(VM* vm, void* ptr) {\n Object* obj = reinterpret_cast(ptr);\n vm->om->write_barrier(this, obj);\n }\n\n \/\/ Used in filtering APIs\n class ObjectMatcher {\n public:\n virtual ~ObjectMatcher() {}\n virtual bool match_p(STATE, Object* obj) = 0;\n };\n\n class ObjectMatchAll : public ObjectMatcher {\n public:\n virtual ~ObjectMatchAll() {}\n virtual bool match_p(STATE, Object* obj) { return true; }\n };\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2017 The Bitcoin Core developers\n\/\/ Copyright (c) 2018-2018 The VERGE Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid CConnmanTest::AddNode(CNode& node)\n{\n LOCK(g_connman->cs_vNodes);\n g_connman->vNodes.push_back(&node);\n}\n\nvoid CConnmanTest::ClearNodes()\n{\n LOCK(g_connman->cs_vNodes);\n for (CNode* node : g_connman->vNodes) {\n delete node;\n }\n g_connman->vNodes.clear();\n}\n\nuint256 insecure_rand_seed = GetRandHash();\nFastRandomContext insecure_rand_ctx(insecure_rand_seed);\n\nextern bool fPrintToConsole;\nextern void noui_connect();\n\nstd::ostream& operator<<(std::ostream& os, const uint256& num)\n{\n os << num.ToString();\n return os;\n}\n\nBasicTestingSetup::BasicTestingSetup(const std::string& chainName)\n\t: m_path_root(fs::temp_directory_path() \/ \"test_verge\" \/ strprintf(\"%lu_%i\", (unsigned long)GetTime(), (int)(InsecureRandRange(1 << 30))))\n{\n SHA256AutoDetect();\n RandomInit();\n ECC_Start();\n SetupEnvironment();\n SetupNetworking();\n InitSignatureCache();\n InitScriptExecutionCache();\n fCheckBlockIndex = true;\n SelectParams(chainName);\n noui_connect();\n}\n\nBasicTestingSetup::~BasicTestingSetup()\n{\n fs::remove_all(m_path_root);\n ECC_Stop();\n}\n\nfs::path BasicTestingSetup::SetDataDir(const std::string& name)\n{\n fs::path ret = m_path_root \/ name;\n fs::create_directories(ret);\n gArgs.ForceSetArg(\"-datadir\", ret.string());\n return ret;\n}\n\nTestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(chainName)\n{\n\tSetDataDir(\"tempdir\");\n const CChainParams& chainparams = Params();\n std::cout << \"1\";\n \/\/ Ideally we'd move all the RPC tests to the functional testing framework\n \/\/ instead of unit tests, but for now we need these here.\n\n RegisterAllCoreRPCCommands(tableRPC);\n std::cout << \"2\";\n ClearDatadirCache();\n std::cout << \"3\";\n\n \/\/ We have to run a scheduler thread to prevent ActivateBestChain\n \/\/ from blocking due to queue overrun.\n std::cout << \"6\";\n threadGroup.create_thread(boost::bind(&CScheduler::serviceQueue, &scheduler));\n std::cout << \"7\";\n GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);\n \n std::cout << \"7\";\n mempool.setSanityCheck(1.0);\n pblocktree.reset(new CBlockTreeDB(1 << 20, true));\n pcoinsdbview.reset(new CCoinsViewDB(1 << 23, true));\n pcoinsTip.reset(new CCoinsViewCache(pcoinsdbview.get()));\n std::cout << \"8\";\n if (!LoadGenesisBlock(chainparams)) {\n std::cout << \"8.E\";\n throw std::runtime_error(\"LoadGenesisBlock failed.\");\n }\n std::cout << \"9.P\";\n {\n CValidationState state;\n std::cout << \"9\";\n if (!ActivateBestChain(state, chainparams)) {\n std::cout << \"9.E\";\n throw std::runtime_error(strprintf(\"ActivateBestChain failed. (%s)\", FormatStateMessage(state)));\n }\n }\n nScriptCheckThreads = 3;\n for (int i=0; i < nScriptCheckThreads-1; i++)\n threadGroup.create_thread(&ThreadScriptCheck);\n \n std::cout << \"10\";\n g_connman = std::unique_ptr(new CConnman(0x1337, 0x1337)); \/\/ Deterministic randomness for tests.\n std::cout << \"11\";\n connman = g_connman.get();\n std::cout << \"12\";\n peerLogic.reset(new PeerLogicValidation(connman, scheduler));\n std::cout << \"END\\n\";\n}\n\nTestingSetup::~TestingSetup()\n{\n threadGroup.interrupt_all();\n threadGroup.join_all();\n GetMainSignals().FlushBackgroundCallbacks();\n GetMainSignals().UnregisterBackgroundSignalScheduler();\n g_connman.reset();\n peerLogic.reset();\n UnloadBlockIndex();\n pcoinsTip.reset();\n pcoinsdbview.reset();\n pblocktree.reset();\n}\n\nTestChain100Setup::TestChain100Setup() : TestingSetup(CBaseChainParams::REGTEST)\n{\n \/\/ CreateAndProcessBlock() does not support building SegWit blocks, so don't activate in these tests.\n \/\/ TODO: fix the code to support SegWit blocks.\n UpdateVersionBitsParameters(Consensus::DEPLOYMENT_SEGWIT, 0, Consensus::BIP9Deployment::NO_TIMEOUT);\n \/\/ Generate a 100-block chain:\n coinbaseKey.MakeNewKey(true);\n CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;\n for (int i = 0; i < COINBASE_MATURITY; i++)\n {\n std::vector noTxns;\n CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey);\n m_coinbase_txns.push_back(b.vtx[0]);\n }\n}\n\n\/\/\n\/\/ Create a new block with just given transactions, coinbase paying to\n\/\/ scriptPubKey, and try to add it to the current chain.\n\/\/\nCBlock\nTestChain100Setup::CreateAndProcessBlock(const std::vector& txns, const CScript& scriptPubKey)\n{\n const CChainParams& chainparams = Params();\n std::unique_ptr pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey);\n CBlock& block = pblocktemplate->block;\n\n \/\/ Replace mempool-selected txns with just coinbase plus passed-in txns:\n block.vtx.resize(1);\n for (const CMutableTransaction& tx : txns)\n block.vtx.push_back(MakeTransactionRef(tx));\n \/\/ IncrementExtraNonce creates a valid coinbase and merkleRoot\n {\n LOCK(cs_main);\n unsigned int extraNonce = 0;\n IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);\n }\n\n while (!CheckProofOfWork(block.GetPoWHash(block.GetAlgo()), block.nBits, chainparams.GetConsensus())) ++block.nNonce;\n\n std::shared_ptr shared_pblock = std::make_shared(block);\n ProcessNewBlock(chainparams, shared_pblock, true, nullptr);\n\n CBlock result = block;\n return result;\n}\n\nTestChain100Setup::~TestChain100Setup()\n{\n}\n\n\nCTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction &tx) {\n return FromTx(MakeTransactionRef(tx));\n}\n\nCTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransactionRef& tx)\n{\n return CTxMemPoolEntry(tx, nFee, nTime, nHeight,\n spendsCoinbase, sigOpCost, lp);\n}\n\nCBlock getBlock13b8a()\n{\n CBlock block;\n CDataStream stream(ParseHex(\"04000000a0ec72a85d7de0ba13768bad314ee654ebc34e21d666cd87ce18ec0100000000d79a8656f873672e21495aac316cae23e05f862d02c955ff3ef924683f3aef7c2c4aea5498c6011c55772bda02010000002c4aea54010000000000000000000000000000000000000000000000000000000000000000ffffffff2703500a02062f503253482f042d4aea5408f800ea79eb9519000d2f7374726174756d506f6f6c2f0000000001a0401fd205000000232102614f24e897de983c2fee0acde4b32d3d2e50a9dc35b3b602154d685918591f00ac0000000001000000fd49ea5401cf851280c5434c73c99909ad9dfac1736a42c98ce240c2d605384fc340071cae010000006b48304502206c16cbe5ee5c6b418045a7ccebf632c06a40f726729bd15e679b944cffb320f7022100cf5deaaf0ab4114baad917b9e7447bd70c7c107048c3b9b02b96f936ce998d0b012102bcd4705d8784d52e594b5481c265ee20010d14366ac91a1c8a4cacf00c55e2acffffffff023aca1b96000000001976a914bb1243827de7374740fc00c290cc35115b4402d988ac807d2195000000001976a9146f5f2839260da439ffd448e61cf7ca2da631391a88ac00000000463044022068710e3fca37a02628c08799d59b152e0aaebb4eea187a58629cc9a12c7e00a202207297aa8213af08ad96ecdbfcff012a03bc96e140578889e92a31ec6babfdcd55\"), SER_NETWORK, PROTOCOL_VERSION);\n stream >> block;\n return block;\n}\nRemove useless logging\/\/ Copyright (c) 2009-2017 The Bitcoin Core developers\n\/\/ Copyright (c) 2018-2018 The VERGE Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid CConnmanTest::AddNode(CNode& node)\n{\n LOCK(g_connman->cs_vNodes);\n g_connman->vNodes.push_back(&node);\n}\n\nvoid CConnmanTest::ClearNodes()\n{\n LOCK(g_connman->cs_vNodes);\n for (CNode* node : g_connman->vNodes) {\n delete node;\n }\n g_connman->vNodes.clear();\n}\n\nuint256 insecure_rand_seed = GetRandHash();\nFastRandomContext insecure_rand_ctx(insecure_rand_seed);\n\nextern bool fPrintToConsole;\nextern void noui_connect();\n\nstd::ostream& operator<<(std::ostream& os, const uint256& num)\n{\n os << num.ToString();\n return os;\n}\n\nBasicTestingSetup::BasicTestingSetup(const std::string& chainName)\n\t: m_path_root(fs::temp_directory_path() \/ \"test_verge\" \/ strprintf(\"%lu_%i\", (unsigned long)GetTime(), (int)(InsecureRandRange(1 << 30))))\n{\n SHA256AutoDetect();\n RandomInit();\n ECC_Start();\n SetupEnvironment();\n SetupNetworking();\n InitSignatureCache();\n InitScriptExecutionCache();\n fCheckBlockIndex = true;\n SelectParams(chainName);\n noui_connect();\n}\n\nBasicTestingSetup::~BasicTestingSetup()\n{\n fs::remove_all(m_path_root);\n ECC_Stop();\n}\n\nfs::path BasicTestingSetup::SetDataDir(const std::string& name)\n{\n fs::path ret = m_path_root \/ name;\n fs::create_directories(ret);\n gArgs.ForceSetArg(\"-datadir\", ret.string());\n return ret;\n}\n\nTestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(chainName)\n{\n\tSetDataDir(\"tempdir\");\n const CChainParams& chainparams = Params();\n \/\/ Ideally we'd move all the RPC tests to the functional testing framework\n \/\/ instead of unit tests, but for now we need these here.\n\n RegisterAllCoreRPCCommands(tableRPC);\n ClearDatadirCache();\n\n \/\/ We have to run a scheduler thread to prevent ActivateBestChain\n \/\/ from blocking due to queue overrun.\n threadGroup.create_thread(boost::bind(&CScheduler::serviceQueue, &scheduler));\n GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);\n \n mempool.setSanityCheck(1.0);\n pblocktree.reset(new CBlockTreeDB(1 << 20, true));\n pcoinsdbview.reset(new CCoinsViewDB(1 << 23, true));\n pcoinsTip.reset(new CCoinsViewCache(pcoinsdbview.get()));\n\n if (!LoadGenesisBlock(chainparams)) {\n throw std::runtime_error(\"LoadGenesisBlock failed.\");\n }\n\n {\n CValidationState state;\n if (!ActivateBestChain(state, chainparams)) {\n throw std::runtime_error(strprintf(\"ActivateBestChain failed. (%s)\", FormatStateMessage(state)));\n }\n }\n nScriptCheckThreads = 3;\n for (int i=0; i < nScriptCheckThreads-1; i++)\n threadGroup.create_thread(&ThreadScriptCheck);\n \n g_connman = std::unique_ptr(new CConnman(0x1337, 0x1337)); \/\/ Deterministic randomness for tests.\n connman = g_connman.get();\n peerLogic.reset(new PeerLogicValidation(connman, scheduler));\n}\n\nTestingSetup::~TestingSetup()\n{\n threadGroup.interrupt_all();\n threadGroup.join_all();\n GetMainSignals().FlushBackgroundCallbacks();\n GetMainSignals().UnregisterBackgroundSignalScheduler();\n g_connman.reset();\n peerLogic.reset();\n UnloadBlockIndex();\n pcoinsTip.reset();\n pcoinsdbview.reset();\n pblocktree.reset();\n}\n\nTestChain100Setup::TestChain100Setup() : TestingSetup(CBaseChainParams::REGTEST)\n{\n \/\/ CreateAndProcessBlock() does not support building SegWit blocks, so don't activate in these tests.\n \/\/ TODO: fix the code to support SegWit blocks.\n UpdateVersionBitsParameters(Consensus::DEPLOYMENT_SEGWIT, 0, Consensus::BIP9Deployment::NO_TIMEOUT);\n \/\/ Generate a 100-block chain:\n coinbaseKey.MakeNewKey(true);\n CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;\n for (int i = 0; i < COINBASE_MATURITY; i++)\n {\n std::vector noTxns;\n CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey);\n m_coinbase_txns.push_back(b.vtx[0]);\n }\n}\n\n\/\/\n\/\/ Create a new block with just given transactions, coinbase paying to\n\/\/ scriptPubKey, and try to add it to the current chain.\n\/\/\nCBlock\nTestChain100Setup::CreateAndProcessBlock(const std::vector& txns, const CScript& scriptPubKey)\n{\n const CChainParams& chainparams = Params();\n std::unique_ptr pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey);\n CBlock& block = pblocktemplate->block;\n\n \/\/ Replace mempool-selected txns with just coinbase plus passed-in txns:\n block.vtx.resize(1);\n for (const CMutableTransaction& tx : txns)\n block.vtx.push_back(MakeTransactionRef(tx));\n \/\/ IncrementExtraNonce creates a valid coinbase and merkleRoot\n {\n LOCK(cs_main);\n unsigned int extraNonce = 0;\n IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);\n }\n\n while (!CheckProofOfWork(block.GetPoWHash(block.GetAlgo()), block.nBits, chainparams.GetConsensus())) ++block.nNonce;\n\n std::shared_ptr shared_pblock = std::make_shared(block);\n ProcessNewBlock(chainparams, shared_pblock, true, nullptr);\n\n CBlock result = block;\n return result;\n}\n\nTestChain100Setup::~TestChain100Setup()\n{\n}\n\n\nCTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction &tx) {\n return FromTx(MakeTransactionRef(tx));\n}\n\nCTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransactionRef& tx)\n{\n return CTxMemPoolEntry(tx, nFee, nTime, nHeight,\n spendsCoinbase, sigOpCost, lp);\n}\n\nCBlock getBlock13b8a()\n{\n CBlock block;\n CDataStream stream(ParseHex(\"04000000a0ec72a85d7de0ba13768bad314ee654ebc34e21d666cd87ce18ec0100000000d79a8656f873672e21495aac316cae23e05f862d02c955ff3ef924683f3aef7c2c4aea5498c6011c55772bda02010000002c4aea54010000000000000000000000000000000000000000000000000000000000000000ffffffff2703500a02062f503253482f042d4aea5408f800ea79eb9519000d2f7374726174756d506f6f6c2f0000000001a0401fd205000000232102614f24e897de983c2fee0acde4b32d3d2e50a9dc35b3b602154d685918591f00ac0000000001000000fd49ea5401cf851280c5434c73c99909ad9dfac1736a42c98ce240c2d605384fc340071cae010000006b48304502206c16cbe5ee5c6b418045a7ccebf632c06a40f726729bd15e679b944cffb320f7022100cf5deaaf0ab4114baad917b9e7447bd70c7c107048c3b9b02b96f936ce998d0b012102bcd4705d8784d52e594b5481c265ee20010d14366ac91a1c8a4cacf00c55e2acffffffff023aca1b96000000001976a914bb1243827de7374740fc00c290cc35115b4402d988ac807d2195000000001976a9146f5f2839260da439ffd448e61cf7ca2da631391a88ac00000000463044022068710e3fca37a02628c08799d59b152e0aaebb4eea187a58629cc9a12c7e00a202207297aa8213af08ad96ecdbfcff012a03bc96e140578889e92a31ec6babfdcd55\"), SER_NETWORK, PROTOCOL_VERSION);\n stream >> block;\n return block;\n}\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2020\/2\/2 16:15:30\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n int H, W;\n cin >> H >> W;\n vector> G(H, vector(W));\n for (auto i = 0; i < H; ++i)\n {\n for (auto j = 0; j < W; ++j)\n {\n cin >> G[i][j];\n }\n }\n for (auto i = 0; i < H; ++i)\n {\n for (auto j = 0; j < W; ++j)\n {\n int t;\n cin >> t;\n G[i][j] = abs(G[i][j] - t);\n }\n }\n vector>> DP(H, vector>(W, vector(10000, false)));\n DP[0][0][G[0][0]] = false;\n for (auto i = 0; i < H; ++i)\n {\n for (auto j = 0; j < W; ++j)\n {\n if (i + 1 < H)\n {\n for (auto k = 0; k < 10000; ++k)\n {\n if (DP[i][j][k])\n {\n DP[i + 1][j][abs(k + G[i + 1][j])] = true;\n DP[i + 1][j][abs(k - G[i + 1][j])] = true;\n }\n }\n }\n if (j + 1 < W)\n {\n for (auto k = 0; k < 10000; ++k)\n {\n if (DP[i][j][k])\n {\n DP[i][j + 1][abs(k + G[i][j + 1])] = true;\n DP[i][j + 1][abs(k - G[i][j + 1])] = true;\n }\n }\n }\n }\n }\n#if DEBUG == 1\n for (auto i = 0; i < H; ++i)\n {\n for (auto j = 0; j < W; ++j)\n {\n for (auto k = 0; k < 10000; ++k)\n {\n if (DP[i][j][k])\n {\n cout << \"DP[\" << i << \"][\" << j << \"] = \" << k << endl;\n break;\n }\n }\n }\n }\n#endif\n for (auto k = 0; k < 10000; ++k)\n {\n if (DP[H - 1][W - 1][k])\n {\n cout << k << endl;\n return 0;\n }\n }\n}\ntried E.cpp to 'E'#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2020\/2\/2 16:15:30\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n int H, W;\n cin >> H >> W;\n vector> G(H, vector(W));\n for (auto i = 0; i < H; ++i)\n {\n for (auto j = 0; j < W; ++j)\n {\n cin >> G[i][j];\n }\n }\n for (auto i = 0; i < H; ++i)\n {\n for (auto j = 0; j < W; ++j)\n {\n int t;\n cin >> t;\n G[i][j] = abs(G[i][j] - t);\n }\n }\n vector>> DP(H, vector>(W, vector(10000, false)));\n DP[0][0][G[0][0]] = true;\n for (auto i = 0; i < H; ++i)\n {\n for (auto j = 0; j < W; ++j)\n {\n if (i + 1 < H)\n {\n for (auto k = 0; k < 10000; ++k)\n {\n if (DP[i][j][k])\n {\n DP[i + 1][j][abs(k + G[i + 1][j])] = true;\n DP[i + 1][j][abs(k - G[i + 1][j])] = true;\n }\n }\n }\n if (j + 1 < W)\n {\n for (auto k = 0; k < 10000; ++k)\n {\n if (DP[i][j][k])\n {\n DP[i][j + 1][abs(k + G[i][j + 1])] = true;\n DP[i][j + 1][abs(k - G[i][j + 1])] = true;\n }\n }\n }\n }\n }\n#if DEBUG == 1\n for (auto i = 0; i < H; ++i)\n {\n for (auto j = 0; j < W; ++j)\n {\n for (auto k = 0; k < 10000; ++k)\n {\n if (DP[i][j][k])\n {\n cout << \"DP[\" << i << \"][\" << j << \"] = \" << k << endl;\n break;\n }\n }\n }\n }\n#endif\n for (auto k = 0; k < 10000; ++k)\n {\n if (DP[H - 1][W - 1][k])\n {\n cout << k << endl;\n return 0;\n }\n }\n}\n<|endoftext|>"} {"text":"#define BOOST_TEST_MODULE Bitcoin Test Suite\n#include \n\n#include \"db.h\"\n#include \"txdb.h\"\n#include \"main.h\"\n#include \"wallet.h\"\n\nCWallet* pwalletMain;\nCClientUIInterface uiInterface;\n\nextern bool fPrintToConsole;\nextern void noui_connect();\n\nstruct TestingSetup {\n CCoinsViewDB *pcoinsdbview;\n\n TestingSetup() {\n fPrintToDebugger = true; \/\/ don't want to write to debug.log file\n noui_connect();\n bitdb.MakeMock();\n pblocktree = new CBlockTreeDB(1 << 20, true);\n pcoinsdbview = new CCoinsViewDB(1 << 23, true);\n pcoinsTip = new CCoinsViewCache(*pcoinsdbview);\n LoadBlockIndex();\n bool fFirstRun;\n pwalletMain = new CWallet(\"wallet.dat\");\n pwalletMain->LoadWallet(fFirstRun);\n RegisterWallet(pwalletMain);\n }\n ~TestingSetup()\n {\n delete pwalletMain;\n pwalletMain = NULL;\n delete pcoinsTip;\n delete pcoinsdbview;\n delete pblocktree;\n bitdb.Flush(true);\n }\n};\n\nBOOST_GLOBAL_FIXTURE(TestingSetup);\n\nvoid Shutdown(void* parg)\n{\n exit(0);\n}\n\nvoid StartShutdown()\n{\n exit(0);\n}\n\nMake test_bitcoin run in a temp datadir#define BOOST_TEST_MODULE Bitcoin Test Suite\n#include \n#include \n\n#include \"db.h\"\n#include \"txdb.h\"\n#include \"main.h\"\n#include \"wallet.h\"\n#include \"util.h\"\n\nCWallet* pwalletMain;\nCClientUIInterface uiInterface;\n\nextern bool fPrintToConsole;\nextern void noui_connect();\n\nstruct TestingSetup {\n CCoinsViewDB *pcoinsdbview;\n boost::filesystem::path pathTemp;\n\n TestingSetup() {\n fPrintToDebugger = true; \/\/ don't want to write to debug.log file\n noui_connect();\n bitdb.MakeMock();\n pathTemp = GetTempPath() \/ strprintf(\"test_bitcoin_%lu_%i\", (unsigned long)GetTime(), (int)(GetRand(100000)));\n boost::filesystem::create_directories(pathTemp);\n mapArgs[\"-datadir\"] = pathTemp.string();\n pblocktree = new CBlockTreeDB(1 << 20, true);\n pcoinsdbview = new CCoinsViewDB(1 << 23, true);\n pcoinsTip = new CCoinsViewCache(*pcoinsdbview);\n LoadBlockIndex();\n bool fFirstRun;\n pwalletMain = new CWallet(\"wallet.dat\");\n pwalletMain->LoadWallet(fFirstRun);\n RegisterWallet(pwalletMain);\n }\n ~TestingSetup()\n {\n delete pwalletMain;\n pwalletMain = NULL;\n delete pcoinsTip;\n delete pcoinsdbview;\n delete pblocktree;\n bitdb.Flush(true);\n boost::filesystem::remove_all(pathTemp);\n }\n};\n\nBOOST_GLOBAL_FIXTURE(TestingSetup);\n\nvoid Shutdown(void* parg)\n{\n exit(0);\n}\n\nvoid StartShutdown()\n{\n exit(0);\n}\n\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 2\/6\/2020, 1:50:46 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nclass Solve\n{\n int N;\n vector> V;\n vector alpha, beta, S, T;\n double total;\n\npublic:\n Solve(int N, vector> const &V) : N{N}, V(V), alpha(N, 0.0), beta(N, 0.0), S(N, 0.0), T(N, 0.0)\n {\n calc_alpha();\n calc_beta();\n calc_S();\n calc_T();\n total = S[N - 1];\n#if DEBUG == 1\n cerr << fixed << setprecision(4);\n for (auto i = 0; i < N; ++i)\n {\n cerr << \"alpha[\" << i << \"] = \" << alpha[i] << endl;\n }\n for (auto i = 0; i < N; ++i)\n {\n cerr << \"beta[\" << i << \"] = \" << beta[i] << endl;\n }\n for (auto i = 0; i < N; ++i)\n {\n cerr << \"S[\" << i << \"] = \" << S[i] << endl;\n }\n for (auto i = 0; i < N; ++i)\n {\n cerr << \"T[\" << i << \"] = \" << T[i] << endl;\n }\n#endif\n }\n\n void flush()\n {\n double ans{0.0};\n for (auto i = 0; i < N; ++i)\n {\n if (V[i].size() <= 1)\n {\n continue;\n }\n double Delta{0.0};\n double d{delta(i)};\n for (auto j : V[i])\n {\n Delta += delta(i, j, d);\n }\n d = delta_zero(i);\n for (auto j : V[i])\n {\n ch_min(ans, Delta + delta(i, j, d));\n }\n }\n cout << fixed << setprecision(10) << ans + total << endl;\n }\n\nprivate:\n double prob(int i)\n {\n assert(!V[i].empty());\n return 1.0 \/ V[i].size();\n }\n\n double delta(int i)\n {\n assert(V[i].size() > 1);\n return 1.0 \/ (V[i].size() - 1) - 1.0 \/ V[i].size();\n }\n\n double delta_zero(int i)\n {\n assert(V[i].size() > 1);\n return -1.0 \/ (V[i].size() - 1);\n }\n\n double delta(int u, int v, double d)\n {\n return d * (beta[v] * S[u] + alpha[u] * T[v] + alpha[u] * beta[v]);\n }\n\n void calc_alpha()\n {\n alpha[0] = 1.0;\n for (auto i = 0; i < N - 1; ++i)\n {\n for (auto j : V[i])\n {\n alpha[j] += prob(i) * alpha[i];\n }\n }\n }\n\n void calc_beta()\n {\n beta = alpha;\n }\n\n void calc_S()\n {\n for (auto i = 0; i < N - 1; ++i)\n {\n for (auto j : V[i])\n {\n S[j] += alpha[i] * prob(i) * (S[i] + 1.0);\n }\n }\n }\n\n void calc_T()\n {\n for (auto i = N - 2; i >= 0; --i)\n {\n double sum{0.0};\n for (auto j : V[i])\n {\n sum += T[j];\n }\n T[i] = 1.0 + prob(i) * sum;\n }\n }\n};\n\nint main()\n{\n int N, M;\n cin >> N >> M;\n vector> V(N);\n for (auto i = 0; i < M; ++i)\n {\n int s, t;\n cin >> s >> t;\n --s;\n --t;\n V[s].push_back(t);\n }\n Solve solve(N, V);\n solve.flush();\n}\ntried F.cpp to 'F'#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 2\/6\/2020, 1:50:46 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nclass Solve\n{\n int N;\n vector> V;\n vector alpha, beta, S, T;\n double total;\n\npublic:\n Solve(int N, vector> const &V) : N{N}, V(V), alpha(N, 0.0), beta(N, 0.0), S(N, 0.0), T(N, 0.0)\n {\n calc_alpha();\n calc_beta();\n calc_S();\n calc_T();\n total = S[N - 1];\n#if DEBUG == 1\n cerr << fixed << setprecision(4);\n for (auto i = 0; i < N; ++i)\n {\n cerr << \"alpha[\" << i << \"] = \" << alpha[i] << endl;\n }\n for (auto i = 0; i < N; ++i)\n {\n cerr << \"beta[\" << i << \"] = \" << beta[i] << endl;\n }\n for (auto i = 0; i < N; ++i)\n {\n cerr << \"S[\" << i << \"] = \" << S[i] << endl;\n }\n for (auto i = 0; i < N; ++i)\n {\n cerr << \"T[\" << i << \"] = \" << T[i] << endl;\n }\n#endif\n }\n\n void flush()\n {\n double ans{0.0};\n for (auto i = 0; i < N; ++i)\n {\n if (V[i].size() <= 1)\n {\n continue;\n }\n double Delta{0.0};\n double d{delta(i)};\n for (auto j : V[i])\n {\n Delta += delta(i, j, d);\n }\n d = delta_zero(i);\n for (auto j : V[i])\n {\n ch_min(ans, Delta + delta(i, j, d));\n }\n }\n cout << fixed << setprecision(10) << ans + total << endl;\n }\n\nprivate:\n double prob(int i)\n {\n assert(!V[i].empty());\n return 1.0 \/ V[i].size();\n }\n\n double delta(int i)\n {\n assert(V[i].size() > 1);\n return 1.0 \/ (V[i].size() - 1) - 1.0 \/ V[i].size();\n }\n\n double delta_zero(int i)\n {\n assert(V[i].size() > 1);\n return -1.0 \/ (V[i].size() - 1);\n }\n\n double delta(int u, int v, double d)\n {\n return d * (beta[v] * S[u] + alpha[u] * T[v] + alpha[u] * beta[v]);\n }\n\n void calc_alpha()\n {\n alpha[0] = 1.0;\n for (auto i = 0; i < N - 1; ++i)\n {\n for (auto j : V[i])\n {\n alpha[j] += prob(i) * alpha[i];\n }\n }\n }\n\n void calc_beta()\n {\n beta = alpha;\n }\n\n void calc_S()\n {\n for (auto i = 0; i < N - 1; ++i)\n {\n for (auto j : V[i])\n {\n S[j] += alpha[i] * prob(i) * 1.0 + prob(i) * S[i];\n }\n }\n }\n\n void calc_T()\n {\n for (auto i = N - 2; i >= 0; --i)\n {\n double sum{0.0};\n for (auto j : V[i])\n {\n sum += T[j];\n }\n T[i] = 1.0 + prob(i) * sum;\n }\n }\n};\n\nint main()\n{\n int N, M;\n cin >> N >> M;\n vector> V(N);\n for (auto i = 0; i < M; ++i)\n {\n int s, t;\n cin >> s >> t;\n --s;\n --t;\n V[s].push_back(t);\n }\n Solve solve(N, V);\n solve.flush();\n}\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2\/10\/2020, 5:30:41 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n string S;\n int K;\n cin >> S >> K;\n int N{static_cast(S.size())};\n vector>> DP(N + 1, vector>(K + 1, vector(2, 0)));\n DP[0][0][0] = 1;\n for (auto i = 0; i < N; ++i)\n {\n for (auto k = 0; k <= K; ++k)\n {\n for (auto j = 0; j < 2; ++j)\n {\n for (auto d = 0; d <= 9; ++d)\n {\n int ni{i + 1}, nk{k}, nj{j};\n if (d > 0)\n {\n ++nk;\n }\n if (nk > K)\n {\n continue;\n }\n int num{S[i] - '0'};\n if (k == 0 && d > num)\n {\n continue;\n }\n else if (k == 0 && d < num)\n {\n nk = 1;\n }\n DP[ni][nk][nj] += DP[i][k][j];\n }\n }\n }\n }\n cout << DP[N][K][0] + DP[N][K][1] << endl;\n}\ntried E.cpp to 'E'#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2\/10\/2020, 5:30:41 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n string S;\n int K;\n cin >> S >> K;\n int N{static_cast(S.size())};\n vector>> DP(N + 1, vector>(K + 1, vector(2, 0)));\n DP[0][0][0] = 1;\n for (auto i = 0; i < N; ++i)\n {\n for (auto k = 0; k <= K; ++k)\n {\n for (auto j = 0; j < 2; ++j)\n {\n for (auto d = 0; d <= 9; ++d)\n {\n int ni{i + 1}, nk{k}, nj{j};\n if (d > 0)\n {\n ++nk;\n }\n if (nk > K)\n {\n continue;\n }\n int num{S[i] - '0'};\n if (k == 0 && d > num)\n {\n continue;\n }\n else if (k == 0 && d < num)\n {\n nk = 1;\n }\n DP[ni][nk][nj] += DP[i][k][j];\n }\n }\n }\n }\n#if DEBUG == 1\n for (auto i = 0; i < N; ++i)\n {\n for (auto k = 0; k <= K; ++k)\n {\n for (auto j = 0; j < 2; ++j)\n {\n cerr << \"DP[\" << i + 1 << \"][\" << k << \"][\" << j << \"] = \" << DP[i + 1][k][j] << endl;\n }\n }\n }\n#endif\n cout << DP[N][K][0] + DP[N][K][1] << endl;\n}\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : A.cpp\n * Author : Kazune Takahashi\n * Created : 2\/22\/2020, 8:41:54 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n ll N, R;\n cin >> N >> R;\n if (N >= 10)\n {\n cout << R << endl;\n }\n else\n {\n cout << R - 100 * (10 - N) << endl;\n }\n}\nsubmit A.cpp to 'A - Beginner' (abc156) [C++14 (GCC 5.4.1)]#define DEBUG 1\n\/**\n * File : A.cpp\n * Author : Kazune Takahashi\n * Created : 2\/22\/2020, 8:41:54 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\ntemplate \nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate \nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n ll N, R;\n cin >> N >> R;\n if (N >= 10)\n {\n cout << R << endl;\n }\n else\n {\n cout << R + 100 * (10 - N) << endl;\n }\n}\n<|endoftext|>"} {"text":"#include \"common\/RhoPort.h\"\nextern \"C\" void Init_System();\nextern \"C\" void Init_Network();\nextern \"C\" void Init_SQLite3();\nextern \"C\" void Init_Log();\nextern \"C\" void Init_WebView();\nextern \"C\" void Init_WebView_extension();\nextern \"C\" void Init_Application();\nextern \"C\" void Init_NativeToolbar();\nextern \"C\" void Init_NativeToolbar_extension();\nextern \"C\" void Init_NativeTabbar();\nextern \"C\" void Init_NativeTabbar_extension();\nextern \"C\" void Init_Navbar();\nextern \"C\" void Init_Notification();\nextern \"C\" void Init_RhoFile();\nextern \"C\" void Init_NativeMenuBar();\nextern \"C\" void Init_Led();\nextern \"C\" void Init_Push();\nextern \"C\" void Init_NewORM_extension();\nextern \"C\" void Init_Intent();\n\nextern \"C\" void Init_CoreAPI_Extension()\n{\n Init_System();\n Init_Application();\n\n\tInit_Network();\n Init_SQLite3();\n Init_NewORM_extension();\n Init_Log();\n#if defined(OS_MACOSX) || defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(OS_ANDROID)\n Init_WebView();\n#elif defined(OS_WP8)\n Init_WebView_extension();\n#endif\n\n#if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || (defined(OS_MACOSX) && defined(RHODES_EMULATOR)) || defined(OS_ANDROID) || defined(OS_MACOSX)\n Init_NativeToolbar();\n Init_NativeTabbar();\n#elif defined(OS_WP8)\n Init_NativeToolbar_extension();\n Init_NativeTabbar_extension();\n#endif\n\n#if defined(OS_MACOSX) || defined(RHODES_EMULATOR)\n Init_Navbar();\n#endif\n\n#if defined(OS_WINDOWS_DESKTOP) || defined(RHODES_EMULATOR) || defined(OS_WINCE) || defined(OS_MACOSX) || defined(OS_ANDROID)\n Init_Notification();\n#endif\n\n#if defined(OS_MACOSX) || defined(OS_ANDROID) || defined(WINDOWS_PLATFORM)\n Init_RhoFile();\n#endif\n\n#if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(RHODES_EMULATOR)\n Init_NativeMenuBar();\n#endif\n\n\n#if defined(OS_WINCE) || defined(OS_ANDROID)\n \/\/Init_Led();\n#endif\n\n#if defined(OS_ANDROID) || defined(OS_WINCE) || defined(OS_MACOSX) || (defined(OS_WINDOWS_DESKTOP) && !defined(RHODES_EMULATOR))\n Init_Push();\n#endif\n\n#if defined(OS_ANDROID) || (defined(OS_MACOSX) && !defined(RHODES_EMULATOR)) || defined(OS_WINCE)\n Init_Intent();\n#endif\n}\nLimiting NewORM to iOS & Android for now#include \"common\/RhoPort.h\"\nextern \"C\" void Init_System();\nextern \"C\" void Init_Network();\nextern \"C\" void Init_SQLite3();\nextern \"C\" void Init_Log();\nextern \"C\" void Init_WebView();\nextern \"C\" void Init_WebView_extension();\nextern \"C\" void Init_Application();\nextern \"C\" void Init_NativeToolbar();\nextern \"C\" void Init_NativeToolbar_extension();\nextern \"C\" void Init_NativeTabbar();\nextern \"C\" void Init_NativeTabbar_extension();\nextern \"C\" void Init_Navbar();\nextern \"C\" void Init_Notification();\nextern \"C\" void Init_RhoFile();\nextern \"C\" void Init_NativeMenuBar();\nextern \"C\" void Init_Led();\nextern \"C\" void Init_Push();\nextern \"C\" void Init_NewORM_extension();\nextern \"C\" void Init_Intent();\n\nextern \"C\" void Init_CoreAPI_Extension()\n{\n Init_System();\n Init_Application();\n\n\tInit_Network();\n Init_SQLite3();\n#if defined(OS_MACOSX) || defined(OS_ANDROID)\n Init_NewORM_extension();\n#endif\n Init_Log();\n#if defined(OS_MACOSX) || defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(OS_ANDROID)\n Init_WebView();\n#elif defined(OS_WP8)\n Init_WebView_extension();\n#endif\n\n#if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || (defined(OS_MACOSX) && defined(RHODES_EMULATOR)) || defined(OS_ANDROID) || defined(OS_MACOSX)\n Init_NativeToolbar();\n Init_NativeTabbar();\n#elif defined(OS_WP8)\n Init_NativeToolbar_extension();\n Init_NativeTabbar_extension();\n#endif\n\n#if defined(OS_MACOSX) || defined(RHODES_EMULATOR)\n Init_Navbar();\n#endif\n\n#if defined(OS_WINDOWS_DESKTOP) || defined(RHODES_EMULATOR) || defined(OS_WINCE) || defined(OS_MACOSX) || defined(OS_ANDROID)\n Init_Notification();\n#endif\n\n#if defined(OS_MACOSX) || defined(OS_ANDROID) || defined(WINDOWS_PLATFORM)\n Init_RhoFile();\n#endif\n\n#if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(RHODES_EMULATOR)\n Init_NativeMenuBar();\n#endif\n\n\n#if defined(OS_WINCE) || defined(OS_ANDROID)\n \/\/Init_Led();\n#endif\n\n#if defined(OS_ANDROID) || defined(OS_WINCE) || defined(OS_MACOSX) || (defined(OS_WINDOWS_DESKTOP) && !defined(RHODES_EMULATOR))\n Init_Push();\n#endif\n\n#if defined(OS_ANDROID) || (defined(OS_MACOSX) && !defined(RHODES_EMULATOR)) || defined(OS_WINCE)\n Init_Intent();\n#endif\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: object.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2006-06-02 12:42:35 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#if defined(WIN32) || defined(WIN16)\n#include \n#endif\n\n#include \n\n#include \n#include \n\n#include \n\n#include \n\nusing namespace vos;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Object super class\n\nVOS_NAMESPACE(OClassInfo, vos) VOS_NAMESPACE(OObject, vos)::__ClassInfo__(VOS_CLASSNAME(OObject, vos), sizeof(VOS_NAMESPACE(OObject, vos)));\n\nOObject::OObject()\n{\n}\n\nOObject::OObject(const OCreateParam& rParam)\n{\n}\n\nOObject::~OObject()\n{\n}\n\nvoid* OObject::operator new(size_t size)\n{\n void* p = rtl_allocateMemory(size);\n\n VOS_ASSERT(p != NULL);\n\n return (p);\n}\n\nvoid* OObject::operator new(size_t size, void* p)\n{\n return (p);\n}\n\nvoid OObject::operator delete(void* p)\n{\n rtl_freeMemory(p);\n}\n\nconst OClassInfo& OObject::classInfo()\n{\n return (__ClassInfo__);\n}\n\nconst OClassInfo& OObject::getClassInfo() const\n{\n return (VOS_CLASSINFO(VOS_NAMESPACE(OObject, vos)));\n}\n\nsal_Bool OObject::isKindOf(const OClassInfo& rClass) const\n{\n VOS_ASSERT(this != NULL);\n\n const OClassInfo& rClassThis = getClassInfo();\n\n return (rClassThis.isDerivedFrom(rClass));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Basic class information\n\nOClassInfo::OClassInfo(const sal_Char *pClassName, sal_Int32 ObjectSize,\n const OClassInfo* pBaseClass, sal_uInt32 Schema,\n OObject* (SAL_CALL * fnCreateObject)(const OCreateParam&))\n{\n m_pClassName = pClassName;\n m_nObjectSize = ObjectSize;\n m_wSchema = Schema;\n\n m_pfnCreateObject = fnCreateObject;\n\n m_pBaseClass = pBaseClass;\n m_pNextClass = NULL;\n}\n\nOObject* OClassInfo::createObject(const OCreateParam& rParam) const\n{\n if (m_pfnCreateObject == NULL)\n return NULL;\n\n OObject* pObject = NULL;\n pObject = (*m_pfnCreateObject)(rParam);\n\n return (pObject);\n}\n\nsal_Bool OClassInfo::isDerivedFrom(const OClassInfo& rClass) const\n{\n VOS_ASSERT(this != NULL);\n\n const OClassInfo* pClassThis = this;\n\n while (pClassThis != NULL)\n {\n if (pClassThis == &rClass)\n return (sal_True);\n\n pClassThis = pClassThis->m_pBaseClass;\n }\n\n return (sal_False); \/\/ walked to the top, no match\n}\n\nconst OClassInfo* OClassInfo::getClassInfo(const sal_Char* pClassName)\n{\n VOS_ASSERT(pClassName != NULL);\n\n const OClassInfo* pClass = &VOS_CLASSINFO(VOS_NAMESPACE(OObject, vos));\n\n while (pClass != NULL)\n {\n if (strcmp(pClassName, pClass->m_pClassName) == 0)\n break;\n\n pClass = pClass->m_pNextClass;\n }\n\n return (pClass);\n}\n\nVOS_CLASSINIT::VOS_CLASSINIT(register OClassInfo* pNewClass)\n{\n VOS_ASSERT(pNewClass != NULL);\n\n OClassInfo* pClassRoot = (OClassInfo*)&VOS_CLASSINFO(VOS_NAMESPACE(OObject, vos));\n\n pNewClass->m_pNextClass = pClassRoot->m_pNextClass;\n\n pClassRoot->m_pNextClass = pNewClass;\n}\nINTEGRATION: CWS warnings01 (1.3.126); FILE MERGED 2006\/01\/25 21:59:16 sb 1.3.126.4: RESYNC: (1.4-1.5); FILE MERGED 2005\/11\/21 15:07:03 sb 1.3.126.3: #i53898# Made code warning-free. 2005\/09\/23 00:18:15 sb 1.3.126.2: RESYNC: (1.3-1.4); FILE MERGED 2005\/09\/07 16:34:15 sb 1.3.126.1: #i53898# Made code warning-free.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: object.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 04:06:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n\n#include \n#include \n\n#include \n\n#include \n\nusing namespace vos;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Object super class\n\nVOS_NAMESPACE(OClassInfo, vos) VOS_NAMESPACE(OObject, vos)::__ClassInfo__(VOS_CLASSNAME(OObject, vos), sizeof(VOS_NAMESPACE(OObject, vos)));\n\nOObject::OObject()\n{\n}\n\nOObject::OObject(const OCreateParam&)\n{\n}\n\nOObject::~OObject()\n{\n}\n\nvoid* OObject::operator new(size_t size)\n{\n void* p = rtl_allocateMemory(size);\n\n VOS_ASSERT(p != NULL);\n\n return (p);\n}\n\nvoid* OObject::operator new(size_t, void* p)\n{\n return (p);\n}\n\nvoid OObject::operator delete(void* p)\n{\n rtl_freeMemory(p);\n}\n\nconst OClassInfo& OObject::classInfo()\n{\n return (__ClassInfo__);\n}\n\nconst OClassInfo& OObject::getClassInfo() const\n{\n return (VOS_CLASSINFO(VOS_NAMESPACE(OObject, vos)));\n}\n\nsal_Bool OObject::isKindOf(const OClassInfo& rClass) const\n{\n VOS_ASSERT(this != NULL);\n\n const OClassInfo& rClassThis = getClassInfo();\n\n return (rClassThis.isDerivedFrom(rClass));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Basic class information\n\nOClassInfo::OClassInfo(const sal_Char *pClassName, sal_Int32 ObjectSize,\n const OClassInfo* pBaseClass, sal_uInt32 Schema,\n OObject* (SAL_CALL * fnCreateObject)(const OCreateParam&))\n{\n m_pClassName = pClassName;\n m_nObjectSize = ObjectSize;\n m_wSchema = Schema;\n\n m_pfnCreateObject = fnCreateObject;\n\n m_pBaseClass = pBaseClass;\n m_pNextClass = NULL;\n}\n\nOObject* OClassInfo::createObject(const OCreateParam& rParam) const\n{\n if (m_pfnCreateObject == NULL)\n return NULL;\n\n OObject* pObject = NULL;\n pObject = (*m_pfnCreateObject)(rParam);\n\n return (pObject);\n}\n\nsal_Bool OClassInfo::isDerivedFrom(const OClassInfo& rClass) const\n{\n VOS_ASSERT(this != NULL);\n\n const OClassInfo* pClassThis = this;\n\n while (pClassThis != NULL)\n {\n if (pClassThis == &rClass)\n return (sal_True);\n\n pClassThis = pClassThis->m_pBaseClass;\n }\n\n return (sal_False); \/\/ walked to the top, no match\n}\n\nconst OClassInfo* OClassInfo::getClassInfo(const sal_Char* pClassName)\n{\n VOS_ASSERT(pClassName != NULL);\n\n const OClassInfo* pClass = &VOS_CLASSINFO(VOS_NAMESPACE(OObject, vos));\n\n while (pClass != NULL)\n {\n if (strcmp(pClassName, pClass->m_pClassName) == 0)\n break;\n\n pClass = pClass->m_pNextClass;\n }\n\n return (pClass);\n}\n\nVOS_CLASSINIT::VOS_CLASSINIT(register OClassInfo* pNewClass)\n{\n VOS_ASSERT(pNewClass != NULL);\n\n OClassInfo* pClassRoot = (OClassInfo*)&VOS_CLASSINFO(VOS_NAMESPACE(OObject, vos));\n\n pNewClass->m_pNextClass = pClassRoot->m_pNextClass;\n\n pClassRoot->m_pNextClass = pNewClass;\n}\n<|endoftext|>"} {"text":"\/* This file is part of the KDE project.\n\nCopyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\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\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see .\n\n*\/\n\n#include \"mediaobject.h\"\n#include \"utils.h\"\n\n#include \"videowidget.h\"\n\n#ifdef PHONON_MMF_VIDEO_SURFACES\n#include \"videooutput_surface.h\"\n#else\n#include \"videooutput_dsa.h\"\n#endif\n\nQT_BEGIN_NAMESPACE\n\nusing namespace Phonon;\nusing namespace Phonon::MMF;\n\n\/*! \\class MMF::VideoWidget\n \\internal\n*\/\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constants\n\/\/-----------------------------------------------------------------------------\n\nstatic const qreal DefaultBrightness = 1.0;\nstatic const qreal DefaultContrast = 1.0;\nstatic const qreal DefaultHue = 1.0;\nstatic const qreal DefaultSaturation = 1.0;\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constructor \/ destructor\n\/\/-----------------------------------------------------------------------------\n\nMMF::VideoWidget::VideoWidget(QWidget *parent)\n : MediaNode(parent)\n#ifdef PHONON_MMF_VIDEO_SURFACES\n , m_videoOutput(new SurfaceVideoOutput(parent))\n#else\n , m_videoOutput(new DsaVideoOutput(parent))\n#endif\n , m_brightness(DefaultBrightness)\n , m_contrast(DefaultContrast)\n , m_hue(DefaultHue)\n , m_saturation(DefaultSaturation)\n{\n TRACE_CONTEXT(VideoWidget::VideoWidget, EVideoApi);\n TRACE_ENTRY_0();\n\n TRACE_EXIT_0();\n}\n\nMMF::VideoWidget::~VideoWidget()\n{\n TRACE_CONTEXT(VideoWidget::~VideoWidget, EVideoApi);\n TRACE_ENTRY_0();\n\n TRACE_EXIT_0();\n}\n\n#ifndef PHONON_MMF_VIDEO_SURFACES\nvoid MMF::VideoWidget::setAncestorMoveMonitor(AncestorMoveMonitor *monitor)\n{\n static_cast(m_videoOutput.data())->setAncestorMoveMonitor(monitor);\n}\n#endif\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ VideoWidgetInterface\n\/\/-----------------------------------------------------------------------------\n\nPhonon::VideoWidget::AspectRatio MMF::VideoWidget::aspectRatio() const\n{\n return m_videoOutput->aspectRatio();\n}\n\nvoid MMF::VideoWidget::setAspectRatio\n(Phonon::VideoWidget::AspectRatio aspectRatio)\n{\n TRACE_CONTEXT(VideoWidget::setAspectRatio, EVideoApi);\n TRACE(\"aspectRatio %d\", aspectRatio);\n\n m_videoOutput->setAspectRatio(aspectRatio);\n}\n\nqreal MMF::VideoWidget::brightness() const\n{\n return m_brightness;\n}\n\nvoid MMF::VideoWidget::setBrightness(qreal brightness)\n{\n TRACE_CONTEXT(VideoWidget::setBrightness, EVideoApi);\n TRACE(\"brightness %f\", brightness);\n\n m_brightness = brightness;\n}\n\nPhonon::VideoWidget::ScaleMode MMF::VideoWidget::scaleMode() const\n{\n return m_videoOutput->scaleMode();\n}\n\nvoid MMF::VideoWidget::setScaleMode(Phonon::VideoWidget::ScaleMode scaleMode)\n{\n TRACE_CONTEXT(VideoWidget::setScaleMode, EVideoApi);\n TRACE(\"setScaleMode %d\", setScaleMode);\n\n m_videoOutput->setScaleMode(scaleMode);\n}\n\nqreal MMF::VideoWidget::contrast() const\n{\n return m_contrast;\n}\n\nvoid MMF::VideoWidget::setContrast(qreal contrast)\n{\n TRACE_CONTEXT(VideoWidget::setContrast, EVideoApi);\n TRACE(\"contrast %f\", contrast);\n\n m_contrast = contrast;\n}\n\nqreal MMF::VideoWidget::hue() const\n{\n return m_hue;\n}\n\nvoid MMF::VideoWidget::setHue(qreal hue)\n{\n TRACE_CONTEXT(VideoWidget::setHue, EVideoApi);\n TRACE(\"hue %f\", hue);\n\n m_hue = hue;\n}\n\nqreal MMF::VideoWidget::saturation() const\n{\n return m_saturation;\n}\n\nvoid MMF::VideoWidget::setSaturation(qreal saturation)\n{\n TRACE_CONTEXT(VideoWidget::setSaturation, EVideoApi);\n TRACE(\"saturation %f\", saturation);\n\n m_saturation = saturation;\n}\n\nQWidget* MMF::VideoWidget::widget()\n{\n return m_videoOutput.data();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ MediaNode\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::VideoWidget::connectMediaObject(MediaObject *mediaObject)\n{\n mediaObject->setVideoOutput(m_videoOutput.data());\n}\n\nvoid MMF::VideoWidget::disconnectMediaObject(MediaObject *mediaObject)\n{\n mediaObject->setVideoOutput(0);\n}\n\nQT_END_NAMESPACE\n\nPhonon MMF: fixed typo in trace statement\/* This file is part of the KDE project.\n\nCopyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\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\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see .\n\n*\/\n\n#include \"mediaobject.h\"\n#include \"utils.h\"\n\n#include \"videowidget.h\"\n\n#ifdef PHONON_MMF_VIDEO_SURFACES\n#include \"videooutput_surface.h\"\n#else\n#include \"videooutput_dsa.h\"\n#endif\n\nQT_BEGIN_NAMESPACE\n\nusing namespace Phonon;\nusing namespace Phonon::MMF;\n\n\/*! \\class MMF::VideoWidget\n \\internal\n*\/\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constants\n\/\/-----------------------------------------------------------------------------\n\nstatic const qreal DefaultBrightness = 1.0;\nstatic const qreal DefaultContrast = 1.0;\nstatic const qreal DefaultHue = 1.0;\nstatic const qreal DefaultSaturation = 1.0;\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Constructor \/ destructor\n\/\/-----------------------------------------------------------------------------\n\nMMF::VideoWidget::VideoWidget(QWidget *parent)\n : MediaNode(parent)\n#ifdef PHONON_MMF_VIDEO_SURFACES\n , m_videoOutput(new SurfaceVideoOutput(parent))\n#else\n , m_videoOutput(new DsaVideoOutput(parent))\n#endif\n , m_brightness(DefaultBrightness)\n , m_contrast(DefaultContrast)\n , m_hue(DefaultHue)\n , m_saturation(DefaultSaturation)\n{\n TRACE_CONTEXT(VideoWidget::VideoWidget, EVideoApi);\n TRACE_ENTRY_0();\n\n TRACE_EXIT_0();\n}\n\nMMF::VideoWidget::~VideoWidget()\n{\n TRACE_CONTEXT(VideoWidget::~VideoWidget, EVideoApi);\n TRACE_ENTRY_0();\n\n TRACE_EXIT_0();\n}\n\n#ifndef PHONON_MMF_VIDEO_SURFACES\nvoid MMF::VideoWidget::setAncestorMoveMonitor(AncestorMoveMonitor *monitor)\n{\n static_cast(m_videoOutput.data())->setAncestorMoveMonitor(monitor);\n}\n#endif\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ VideoWidgetInterface\n\/\/-----------------------------------------------------------------------------\n\nPhonon::VideoWidget::AspectRatio MMF::VideoWidget::aspectRatio() const\n{\n return m_videoOutput->aspectRatio();\n}\n\nvoid MMF::VideoWidget::setAspectRatio\n(Phonon::VideoWidget::AspectRatio aspectRatio)\n{\n TRACE_CONTEXT(VideoWidget::setAspectRatio, EVideoApi);\n TRACE(\"aspectRatio %d\", aspectRatio);\n\n m_videoOutput->setAspectRatio(aspectRatio);\n}\n\nqreal MMF::VideoWidget::brightness() const\n{\n return m_brightness;\n}\n\nvoid MMF::VideoWidget::setBrightness(qreal brightness)\n{\n TRACE_CONTEXT(VideoWidget::setBrightness, EVideoApi);\n TRACE(\"brightness %f\", brightness);\n\n m_brightness = brightness;\n}\n\nPhonon::VideoWidget::ScaleMode MMF::VideoWidget::scaleMode() const\n{\n return m_videoOutput->scaleMode();\n}\n\nvoid MMF::VideoWidget::setScaleMode(Phonon::VideoWidget::ScaleMode scaleMode)\n{\n TRACE_CONTEXT(VideoWidget::setScaleMode, EVideoApi);\n TRACE(\"setScaleMode %d\", scaleMode);\n\n m_videoOutput->setScaleMode(scaleMode);\n}\n\nqreal MMF::VideoWidget::contrast() const\n{\n return m_contrast;\n}\n\nvoid MMF::VideoWidget::setContrast(qreal contrast)\n{\n TRACE_CONTEXT(VideoWidget::setContrast, EVideoApi);\n TRACE(\"contrast %f\", contrast);\n\n m_contrast = contrast;\n}\n\nqreal MMF::VideoWidget::hue() const\n{\n return m_hue;\n}\n\nvoid MMF::VideoWidget::setHue(qreal hue)\n{\n TRACE_CONTEXT(VideoWidget::setHue, EVideoApi);\n TRACE(\"hue %f\", hue);\n\n m_hue = hue;\n}\n\nqreal MMF::VideoWidget::saturation() const\n{\n return m_saturation;\n}\n\nvoid MMF::VideoWidget::setSaturation(qreal saturation)\n{\n TRACE_CONTEXT(VideoWidget::setSaturation, EVideoApi);\n TRACE(\"saturation %f\", saturation);\n\n m_saturation = saturation;\n}\n\nQWidget* MMF::VideoWidget::widget()\n{\n return m_videoOutput.data();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ MediaNode\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::VideoWidget::connectMediaObject(MediaObject *mediaObject)\n{\n mediaObject->setVideoOutput(m_videoOutput.data());\n}\n\nvoid MMF::VideoWidget::disconnectMediaObject(MediaObject *mediaObject)\n{\n mediaObject->setVideoOutput(0);\n}\n\nQT_END_NAMESPACE\n\n<|endoftext|>"} {"text":"\/\/ $Id$\n\n#include \n\nvoid hits()\n{\n hits(\"FMD\",\"1\");\n hits(\"PHOS\",\"1\");\n hits(\"START\",\"1\");\n hits(\"TOF\",\"2\");\n hits(\"TPC\",\"2\");\n\n \/\/hits(\"ITS\",\"5\");\n \/\/hits(\"MUON\",\"0\");\n \/\/hits(\"PMD\",\"1\");\n \/\/hits(\"RICH\",\"1\");\n} \n\nvoid hits(const TString& detName, const TString& detVersion)\n{\n cout << detName << endl;\n\n \/\/ labels\n TString g3 = \"G3: \";\n TString g4 = \"G4: \";\n\n \/\/ construct file names\n TString top = getenv(\"ALICE_ROOT\");\n TString f1NameEnd = \"test10.root\";\n TString f2NameEnd = \"test20.root\";\n\n TString g3File1Name = top + \"\/test\/\" + f1NameEnd;\n TString g3File2Name = top + \"\/test\/\" + f2NameEnd;\n TString g4File1Name = top + \"\/AliGeant4\/test\/\" + f1NameEnd;\n TString g4File2Name = top + \"\/AliGeant4\/test\/\" + f2NameEnd;\n \n cout << \"Files: \" << endl;\n cout << g3File1Name << endl;\n cout << g3File2Name << endl;\n cout << g4File1Name << endl;\n cout << g4File2Name << endl;\n\n \/\/ link shared libs\n if (gClassTable->GetID(\"AliRun\") < 0) {\n gROOT->LoadMacro(\"loadlibs.C\");\n loadlibs();\n }\n cout << \"AliRoot libraries were loaded.\" << endl;\n \n \/\/ set histogram ranges\n Int_t nbin;\n Int_t g3xmin; Int_t g4xmin; Int_t g3xmax; Int_t g4xmax;\n Int_t g3ymin; Int_t g4ymin; Int_t g3ymax; Int_t g4ymax;\n Int_t g3zmin; Int_t g4zmin; Int_t g3zmax; Int_t g4zmax;\n SetHistogramRanges(detName, nbin, \n g3xmin, g3xmax, g4xmin, g4xmax,\n g3ymin, g3ymax, g4ymin, g4ymax,\n g3zmin, g3zmax, g4zmin, g4zmax);\n\n\n \/\/ create histograms\n TH1F* g3x = new TH1F(\"g3x\", g3 + detName + \" hits per x\", nbin, g3xmin, g3xmax);\n TH1F* g3xh = new TH1F(\"g3xh\", g3 + detName + \" hits per x\", nbin, g3xmin, g3xmax);\n TH1F* g4x = new TH1F(\"g4x\", g4 + detName + \" hits per x\", nbin, g4xmin, g4xmax);\n TH1F* g4xh = new TH1F(\"g4xh\", g4 + detName + \" hits per x\", nbin, g4xmin, g4xmax);\n\n TH1F* g3z = new TH1F(\"g3z\", g3 + detName + \" hits per z\", nbin, g3zmin, g3zmax);\n TH1F* g3zh = new TH1F(\"g3zh\", g3 + detName + \" hits per z\", nbin, g3zmin, g3zmax);\n TH1F* g4z = new TH1F(\"g4z\", g4 + detName + \" hits per z\", nbin, g4zmin, g4zmax);\n TH1F* g4zh = new TH1F(\"g4zh\", g4 + detName + \" hits per z\", nbin, g4zmin, g4zmax);\n\n TH1F* g3y = 0;\n TH1F* g3yh = 0;\n TH1F* g4y = 0;\n TH1F* g4yh = 0;\n if (detName == \"PHOS\") {\n TH1F* g3y = new TH1F(\"g3y\", g3 + detName + \" hits per y\", nbin, g3ymin, g3ymax);\n TH1F* g3yh = new TH1F(\"g3yh\", g3 + detName + \" hits per y\", nbin, g3ymin, g3ymax);\n TH1F* g4y = new TH1F(\"g4y\", g4 + detName + \" hits per y\", nbin, g4ymin, g4ymax);\n TH1F* g4yh = new TH1F(\"g4yh\", g4 + detName + \" hits per y\", nbin, g4ymin, g4ymax);\n }\n\n cout << \"Histograms were created.\" << endl;\n\n \/\/ fill histograms\n AliDetector* detector;\n\n \/\/detector = LoadDetector(g3File1Name, detName, g3);\n \/\/FillHistogram(detector, g3, g3x, g3y, g3z); \n\n detector = LoadDetector(g3File2Name, detName, g3);\n FillHistogram(detector, g3, g3xh, g3yh, g3zh); \n \/\/TH1F* g3xh = LoadHistograms(\"g3xh\"); \n \/\/TH1F* g3zh = LoadHistograms(\"g3zh\"); \n\n detector = LoadDetector(g4File1Name, detName, g4);\n FillHistogram(detector, g4, g4x, g4y, g4z); \n\n detector = LoadDetector(g4File2Name, detName, g4);\n FillHistogram(detector, g4, g4xh, g4yh, g4zh); \n\n \/\/ compose picture name\n TString gifNameBase = \"hits\" + detName + \"v\" + detVersion;\n TString title = detName + \" hits\";\n\n \/\/ draw histohrams\n DrawHistograms(title, gifNameBase + \".gif\", g3xh, g4xh, g3zh, g4zh);\n if (detName == \"PHOS\") \n DrawHistograms(title, gifNameBase + \"2.gif\", g3yh, g4yh, g3zh, g4zh);\n\n \/\/DrawHistograms(title, gifNameBase + \"_x.gif\", g3x, g4x, g3xh, g4xh);\n \/\/DrawHistograms(title, gifNameBase + \"_y.gif\", g3y, g4y, g3yh, g4yh);\n \/\/DrawHistograms(title, gifNameBase + \"_z.gif\", g3z, g4z, g3zh, g4zh);\n \n}\n\nvoid SetHistogramRanges(TString& detName, Int_t& nbin, \n Int_t& g3xmin, Int_t& g3xmax,\n Int_t& g4xmin, Int_t& g4xmax,\n Int_t& g3ymin, Int_t& g3ymax, \n Int_t& g4ymin, Int_t& g4ymax, \n Int_t& g3zmin, Int_t& g3zmax, \n Int_t& g4zmin, Int_t& g4zmax)\n{\t\t\t \n nbin = 200;\n\n g3xmin = 0; g4xmin = g3xmin;\n g3xmax = 1; g4xmax = g3xmax;\n g3ymin = 0; g4ymin = g3xmin;\n g3ymax = 1; g4ymax = g3xmax;\n g3zmin = 0; g4zmin = g3zmin;\n g3zmax = 1; g4zmax = g3zmax;\n\n if (detName == \"FMD\") {\n g3xmin = -50; g4xmin = g3xmin;\n g3xmax = 50; g4xmax = g3xmax;\n g3zmin = -700; g4zmin = g3zmin;\n g3zmax = 150; g4zmax = g3zmax;\n }\n else if (detName == \"ITS\") {\n g3xmin = -60; g4xmin = g3xmin;\n g3xmax = 60; g4xmax = g3xmax;\n g3zmin = -60; g4zmin = g3zmin;\n g3zmax = 60; g4zmax = g3zmax;\n } \n else if (detName == \"MUON\") {\n g3xmin = -450; g4xmin = g3xmin;\n g3xmax = 450; g4xmax = g3xmax;\n g3zmin = 400; g4zmin = g3zmin;\n g3zmax = 1800; g4zmax = g3zmax;\n }\n else if (detName == \"PHOS\") {\n g3xmin = -400; g4xmin = g3xmin;\n g3xmax = 400; g4xmax = g3xmax;\n g3ymin = 250; g4ymin = g3ymin;\n g3ymax = 500; g4ymax = g3ymax;\n g3zmin = -80; g4zmin = g3zmin;\n g3zmax = 80; g4zmax = g3zmax;\n }\n else if (detName == \"PMD\") {\n g3xmin = -200; g4xmin = g3xmin*10;\n g3xmax = 200; g4xmax = g3xmax*10;\n g3zmin = -582; g4zmin = g3zmin*10;\n g3zmax = -578; g4zmax = g3zmax*10;\n }\n else if (detName == \"RICH\") {\n g3xmin = -250; g4xmin = g3xmin;\n g3xmax = 250; g4xmax = g3xmax;\n g3zmin = -250; g4zmin = g3zmin;\n g3zmax = 250; g4zmax = g3zmax;\n }\n else if (detName == \"START\") {\n g3xmin = -10; g4xmin = g3xmin;\n g3xmax = 10; g4xmax = g3xmax;\n g3zmin = -80; g4zmin = g3zmin;\n g3zmax = 80; g4zmax = g3zmax;\n }\n else if (detName == \"TOF\") {\n g3xmin = -400; g4xmin = g3xmin;\n g3xmax = 400; g4xmax = g3xmax;\n g3zmin = -400; g4zmin = g3zmin;\n g3zmax = 400; g4zmax = g3zmax;\n }\n else if (detName == \"TPC\") {\n g3xmin = -300; g4xmin = g3xmin;\n g3xmax = 300; g4xmax = g3xmax;\n g3zmin = -300; g4zmin = g3zmin;\n g3zmax = 300; g4zmax = g3zmax;\n }\n} \n\nAliDetector* LoadDetector(TString& fileName, TString& detName, TString& label)\n{ \n \/\/ connect the Root files\n TFile* file = new TFile(fileName);\n if (!file) {\n cerr << \"Root file was not found.\" << endl;\n return 0;\n }\n\n \/\/ get AliRun object from file \n if (gAlice) delete gAlice;\n gAlice = 0;\n gAlice = (AliRun*)file->Get(\"gAlice\");\n if (!gAlice) {\n cerr << label << \"AliRun object not found in a file.\" << endl;\n return 0;\n }\n \n \/\/ import the hits trees \n Int_t nparticles = gAlice->GetEvent(0);\n if (nparticles <= 0) {\n cerr << label << \"No particles in a file.\" << endl;\n return 0;\n } \n cout << label << \"got nparticles = \" << nparticles << endl;\n\n \/\/ get detector\n AliDetector* detector = gAlice->GetDetector(detName);\n if (!detector) {\n cerr << label << \"No detector \" << detName << \" in a file.\" << endl;\n return 0;\n } \n \n return detector;\n} \n\nvoid FillHistogram(AliDetector* detector, TString& label, \n TH1F* hx, TH1F* hy, TH1F* hz) \n{ \n Int_t nofHits = 0;\n \/\/ get number of primary tracks\n Int_t ntracks = gAlice->TreeH()->GetEntries();\n cout << label << \"got ntracks = \" << ntracks << endl;\n\n \/\/ loop on tracks in the hits container\n for (Int_t i=0; iFirstHit(i); hit; hit=detector->NextHit()) {\n\n TString detName = detector->GetName();\n if (detName == \"PHOS\") { \n \/\/ PHOS special\n FillPHOSHit(detector, hit, hx, hy, hz);\n }\t\n else {\n FillHit(hit, hx, hy, hz);\n }\t\n\t\n nofHits++;\n }\n } \n\/* \n TFile* file = new TFile(\"tmp.root\",\"recreate\");\n hx->Write();\n hz->Write();\n file->Close();\n*\/\n cout << label << \"filled \" << nofHits << \" hits\" << endl;\n} \n\nTH1F* LoadHistograms(TString name)\n{\n TFile* file = new TFile(\"tmp.root\");\n return (TH1F*)file->Get(name);\n} \n\nvoid FillHit(AliHit* hit, TH1F* hx, TH1F* hy, TH1F* hz) \n{ \n if (hx) hx->Fill(hit->X());\n if (hy) hy->Fill(hit->Y());\n if (hz) hz->Fill(hit->Z());\n} \n\nvoid FillPHOSHit(AliDetector* detector, AliHit* hit, \n TH1F* hx, TH1F* hy, TH1F* hz) \n{ \n \/\/ PHOS special\n Float_t id = ((AliPHOSHit*)hit)->GetId();\n \n TVector3 pos;\n ((AliPHOS*)detector)->GetGeometry()->RelPosInAlice(id, pos);\n \n if (hx) hx->Fill(pos.X());\n if (hy) hy->Fill(pos.Y());\n if (hz) hz->Fill(pos.Z());\n} \n\nvoid DrawHistograms(TString& title, TString& gifName,\n TH1F* h1, TH1F* h2, TH1F* h3, TH1F* h4)\n{\n\/\/ Create canvas, set the view range, show histograms.\n\/\/ ---\n\n if (h1 && h2 && h3 && h4) {\n \/\/ create canvas\n TCanvas* canvas = new TCanvas(\"c1\", title, 400, 10, 800, 600);\n canvas->Divide(2,2);\n \n \/\/ draw histograms\n canvas->cd(1); h1->Draw();\n canvas->cd(2); h2->Draw(); \n canvas->cd(3); h3->Draw(); \n canvas->cd(4); h4->Draw();\n \n \/\/ save gif\n \/\/canvas->SaveAs(gifNameBase + \"_x.gif\"); \n canvas->SaveAs(gifName); \n } \n}\nadded function for drawing histograms one by one; added function for loading histograms from tmp file\/\/ $Id$\n\n#include \n\nvoid hits()\n{\n hits(\"FMD\",\"1\");\n hits(\"PHOS\",\"1\");\n hits(\"START\",\"1\");\n hits(\"TOF\",\"2\");\n hits(\"TPC\",\"2\");\n\n \/\/hits(\"ITS\",\"5\");\n \/\/hits(\"MUON\",\"0\");\n \/\/hits(\"PMD\",\"1\");\n \/\/hits(\"RICH\",\"1\");\n} \n\nvoid hits(const TString& detName, const TString& detVersion)\n{\n cout << detName << endl;\n\n \/\/ labels\n TString g3 = \"G3: \";\n TString g4 = \"G4: \";\n\n \/\/ construct file names\n TString top = getenv(\"ALICE_ROOT\");\n TString f1NameEnd = \"test10.root\";\n TString f2NameEnd = \"test20.root\";\n\n TString g3File1Name = top + \"\/test\/\" + f1NameEnd;\n TString g3File2Name = top + \"\/test\/\" + f2NameEnd;\n TString g4File1Name = top + \"\/AliGeant4\/test\/\" + f1NameEnd;\n TString g4File2Name = top + \"\/AliGeant4\/test\/\" + f2NameEnd;\n \n cout << \"Files: \" << endl;\n cout << g3File1Name << endl;\n cout << g3File2Name << endl;\n cout << g4File1Name << endl;\n cout << g4File2Name << endl;\n\n \/\/ link shared libs\n if (gClassTable->GetID(\"AliRun\") < 0) {\n gROOT->LoadMacro(\"loadlibs.C\");\n loadlibs();\n }\n cout << \"AliRoot libraries were loaded.\" << endl;\n \n \/\/ set histogram ranges\n Int_t nbin;\n Int_t g3xmin; Int_t g4xmin; Int_t g3xmax; Int_t g4xmax;\n Int_t g3ymin; Int_t g4ymin; Int_t g3ymax; Int_t g4ymax;\n Int_t g3zmin; Int_t g4zmin; Int_t g3zmax; Int_t g4zmax;\n SetHistogramRanges(detName, nbin, \n g3xmin, g3xmax, g4xmin, g4xmax,\n g3ymin, g3ymax, g4ymin, g4ymax,\n g3zmin, g3zmax, g4zmin, g4zmax);\n\n\n \/\/ create histograms\n TH1F* g3x = new TH1F(\"g3x\", g3 + detName + \" hits per x\", nbin, g3xmin, g3xmax);\n TH1F* g3xh = new TH1F(\"g3xh\", g3 + detName + \" hits per x\", nbin, g3xmin, g3xmax);\n TH1F* g4x = new TH1F(\"g4x\", g4 + detName + \" hits per x\", nbin, g4xmin, g4xmax);\n TH1F* g4xh = new TH1F(\"g4xh\", g4 + detName + \" hits per x\", nbin, g4xmin, g4xmax);\n\n TH1F* g3z = new TH1F(\"g3z\", g3 + detName + \" hits per z\", nbin, g3zmin, g3zmax);\n TH1F* g3zh = new TH1F(\"g3zh\", g3 + detName + \" hits per z\", nbin, g3zmin, g3zmax);\n TH1F* g4z = new TH1F(\"g4z\", g4 + detName + \" hits per z\", nbin, g4zmin, g4zmax);\n TH1F* g4zh = new TH1F(\"g4zh\", g4 + detName + \" hits per z\", nbin, g4zmin, g4zmax);\n\n TH1F* g3y = 0;\n TH1F* g3yh = 0;\n TH1F* g4y = 0;\n TH1F* g4yh = 0;\n if (detName == \"PHOS\") {\n TH1F* g3y = new TH1F(\"g3y\", g3 + detName + \" hits per y\", nbin, g3ymin, g3ymax);\n TH1F* g3yh = new TH1F(\"g3yh\", g3 + detName + \" hits per y\", nbin, g3ymin, g3ymax);\n TH1F* g4y = new TH1F(\"g4y\", g4 + detName + \" hits per y\", nbin, g4ymin, g4ymax);\n TH1F* g4yh = new TH1F(\"g4yh\", g4 + detName + \" hits per y\", nbin, g4ymin, g4ymax);\n }\n\n cout << \"Histograms were created.\" << endl;\n\n \/\/ fill histograms\n AliDetector* detector;\n\n detector = LoadDetector(g3File1Name, detName, g3);\n FillHistogram(detector, g3, g3x, g3y, g3z); \n\n detector = LoadDetector(g3File2Name, detName, g3);\n FillHistogram(detector, g3, g3xh, g3yh, g3zh); \n \/\/TH1F* g3xh = LoadHistograms(\"g3xh\"); \n \/\/TH1F* g3zh = LoadHistograms(\"g3zh\"); \n\n detector = LoadDetector(g4File1Name, detName, g4);\n FillHistogram(detector, g4, g4x, g4y, g4z); \n\n detector = LoadDetector(g4File2Name, detName, g4);\n FillHistogram(detector, g4, g4xh, g4yh, g4zh); \n\n \/\/ compose picture name\n TString gifNameBase = \"hits\" + detName + \"v\" + detVersion;\n TString title = detName + \" hits\";\n\n \/\/ draw histograms (G3, G4 in one canvas)\n DrawHistograms(title, gifNameBase + \".gif\", g3xh, g4xh, g3zh, g4zh);\n if (detName == \"PHOS\") \n DrawHistograms(title, gifNameBase + \"2.gif\", g3yh, g4yh, g3zh, g4zh);\n\n \/\/DrawHistograms(title, gifNameBase + \"_x.gif\", g3x, g4x, g3xh, g4xh);\n \/\/DrawHistograms(title, gifNameBase + \"_y.gif\", g3y, g4y, g3yh, g4yh);\n \/\/DrawHistograms(title, gifNameBase + \"_z.gif\", g3z, g4z, g3zh, g4zh);\n \n \/\/ draw histograms (one by one)\n DrawHistogram(title, \"g3x_\"+ gifNameBase + \".gif\", g3xh);\n DrawHistogram(title, \"g4x_\"+ gifNameBase + \".gif\", g4xh);\n DrawHistogram(title, \"g3z_\"+ gifNameBase + \".gif\", g3zh);\n DrawHistogram(title, \"g4z_\"+ gifNameBase + \".gif\", g4zh);\n\n}\n\nvoid SetHistogramRanges(TString& detName, Int_t& nbin, \n Int_t& g3xmin, Int_t& g3xmax,\n Int_t& g4xmin, Int_t& g4xmax,\n Int_t& g3ymin, Int_t& g3ymax, \n Int_t& g4ymin, Int_t& g4ymax, \n Int_t& g3zmin, Int_t& g3zmax, \n Int_t& g4zmin, Int_t& g4zmax)\n{\t\t\t \n nbin = 200;\n\n g3xmin = 0; g4xmin = g3xmin;\n g3xmax = 1; g4xmax = g3xmax;\n g3ymin = 0; g4ymin = g3xmin;\n g3ymax = 1; g4ymax = g3xmax;\n g3zmin = 0; g4zmin = g3zmin;\n g3zmax = 1; g4zmax = g3zmax;\n\n if (detName == \"FMD\") {\n g3xmin = -50; g4xmin = g3xmin;\n g3xmax = 50; g4xmax = g3xmax;\n g3zmin = -700; g4zmin = g3zmin;\n g3zmax = 150; g4zmax = g3zmax;\n }\n else if (detName == \"ITS\") {\n g3xmin = -60; g4xmin = g3xmin;\n g3xmax = 60; g4xmax = g3xmax;\n g3zmin = -60; g4zmin = g3zmin;\n g3zmax = 60; g4zmax = g3zmax;\n } \n else if (detName == \"MUON\") {\n g3xmin = -450; g4xmin = g3xmin;\n g3xmax = 450; g4xmax = g3xmax;\n g3zmin = 400; g4zmin = g3zmin;\n g3zmax = 1800; g4zmax = g3zmax;\n }\n else if (detName == \"PHOS\") {\n g3xmin = -400; g4xmin = g3xmin;\n g3xmax = 400; g4xmax = g3xmax;\n g3ymin = 250; g4ymin = g3ymin;\n g3ymax = 500; g4ymax = g3ymax;\n g3zmin = -80; g4zmin = g3zmin;\n g3zmax = 80; g4zmax = g3zmax;\n }\n else if (detName == \"PMD\") {\n g3xmin = -200; g4xmin = g3xmin*10;\n g3xmax = 200; g4xmax = g3xmax*10;\n g3zmin = -582; g4zmin = g3zmin*10;\n g3zmax = -578; g4zmax = g3zmax*10;\n }\n else if (detName == \"RICH\") {\n g3xmin = -250; g4xmin = g3xmin;\n g3xmax = 250; g4xmax = g3xmax;\n g3zmin = -250; g4zmin = g3zmin;\n g3zmax = 250; g4zmax = g3zmax;\n }\n else if (detName == \"START\") {\n g3xmin = -10; g4xmin = g3xmin;\n g3xmax = 10; g4xmax = g3xmax;\n g3zmin = -80; g4zmin = g3zmin;\n g3zmax = 80; g4zmax = g3zmax;\n }\n else if (detName == \"TOF\") {\n g3xmin = -400; g4xmin = g3xmin;\n g3xmax = 400; g4xmax = g3xmax;\n g3zmin = -400; g4zmin = g3zmin;\n g3zmax = 400; g4zmax = g3zmax;\n }\n else if (detName == \"TPC\") {\n g3xmin = -300; g4xmin = g3xmin;\n g3xmax = 300; g4xmax = g3xmax;\n g3zmin = -300; g4zmin = g3zmin;\n g3zmax = 300; g4zmax = g3zmax;\n }\n} \n\nAliDetector* LoadDetector(TString& fileName, TString& detName, TString& label)\n{ \n \/\/ connect the Root files\n TFile* file = new TFile(fileName);\n if (!file) {\n cerr << \"Root file was not found.\" << endl;\n return 0;\n }\n\n \/\/ get AliRun object from file \n if (gAlice) delete gAlice;\n gAlice = 0;\n gAlice = (AliRun*)file->Get(\"gAlice\");\n if (!gAlice) {\n cerr << label << \"AliRun object not found in a file.\" << endl;\n return 0;\n }\n \n \/\/ import the hits trees \n Int_t nparticles = gAlice->GetEvent(0);\n if (nparticles <= 0) {\n cerr << label << \"No particles in a file.\" << endl;\n return 0;\n } \n cout << label << \"got nparticles = \" << nparticles << endl;\n\n \/\/ get detector\n AliDetector* detector = gAlice->GetDetector(detName);\n if (!detector) {\n cerr << label << \"No detector \" << detName << \" in a file.\" << endl;\n return 0;\n } \n \n return detector;\n} \n\nvoid FillHistogram(AliDetector* detector, TString& label, \n TH1F* hx, TH1F* hy, TH1F* hz) \n{ \n Int_t nofHits = 0;\n \/\/ get number of primary tracks\n Int_t ntracks = gAlice->TreeH()->GetEntries();\n cout << label << \"got ntracks = \" << ntracks << endl;\n\n \/\/ loop on tracks in the hits container\n for (Int_t i=0; iFirstHit(i); hit; hit=detector->NextHit()) {\n\n TString detName = detector->GetName();\n if (detName == \"PHOS\") { \n \/\/ PHOS special\n FillPHOSHit(detector, hit, hx, hy, hz);\n }\t\n else {\n FillHit(hit, hx, hy, hz);\n }\t\n\t\n nofHits++;\n }\n } \n\/* \n TFile* file = new TFile(\"tmp.root\",\"recreate\");\n hx->Write();\n hz->Write();\n file->Close();\n*\/\n cout << label << \"filled \" << nofHits << \" hits\" << endl;\n} \n\nTH1F* LoadHistograms(TString name)\n{\n TFile* file = new TFile(\"tmp.root\");\n return (TH1F*)file->Get(name);\n} \n\nvoid FillHit(AliHit* hit, TH1F* hx, TH1F* hy, TH1F* hz) \n{ \n if (hx) hx->Fill(hit->X());\n if (hy) hy->Fill(hit->Y());\n if (hz) hz->Fill(hit->Z());\n} \n\nvoid FillPHOSHit(AliDetector* detector, AliHit* hit, \n TH1F* hx, TH1F* hy, TH1F* hz) \n{ \n \/\/ PHOS special\n Float_t id = ((AliPHOSHit*)hit)->GetId();\n \n TVector3 pos;\n ((AliPHOS*)detector)->GetGeometry()->RelPosInAlice(id, pos);\n \n if (hx) hx->Fill(pos.X());\n if (hy) hy->Fill(pos.Y());\n if (hz) hz->Fill(pos.Z());\n} \n\nvoid DrawHistograms(TString& title, TString& gifName,\n TH1F* h1, TH1F* h2, TH1F* h3, TH1F* h4)\n{\n\/\/ Create canvas, set the view range, show histograms.\n\/\/ ---\n\n if (h1 && h2 && h3 && h4) {\n \/\/ create canvas\n TCanvas* canvas1 = new TCanvas(\"c1\", title, 400, 10, 400, 300);\n TCanvas* canvas2 = new TCanvas(\"c2\", title, 400, 10, 400, 300);\n TCanvas* canvas3 = new TCanvas(\"c3\", title, 400, 10, 400, 300);\n TCanvas* canvas4 = new TCanvas(\"c4\", title, 400, 10, 400, 300);\n \/\/canvas->Divide(2,2);\n \n \/\/ draw histograms\n canvas1->cd(1); h1->Draw();\n canvas2->cd(1); h2->Draw(); \n canvas3->cd(1); h3->Draw(); \n canvas4->cd(1); h4->Draw();\n \n \/\/ save gif\n \/\/canvas->SaveAs(gifNameBase + \"_x.gif\"); \n canvas1->SaveAs(gifName+\"1\"); \n canvas2->SaveAs(gifName+\"2\"); \n canvas3->SaveAs(gifName+\"3\"); \n canvas4->SaveAs(gifName+\"4\"); \n } \n}\n\nvoid DrawHistogram(TString& title, TString& gifName, TH1F* h)\n{\n\/\/ Create canvas, set the view range, show histograms.\n\/\/ ---\n\n if (h){\n \/\/ create canvas\n TCanvas* canvas = new TCanvas(\"c\", title, 400, 10, 400, 300);\n \n \/\/ draw histograms\n h->Draw();\n \n \/\/ save gif\n canvas->SaveAs(gifName); \n } \n}\n<|endoftext|>"} {"text":"\/\/\/ \\file DboxPassword.cpp\n\/\/-----------------------------------------------------------------------------\n\n#include \"PasswordSafe.h\"\n\n#include \"ThisMfcApp.h\"\n#include \"corelib\/Util.h\"\n#include \"corelib\/PWCharPool.h\"\n#include \"corelib\/PWSprefs.h\"\n\n#include \"DboxMain.h\"\n\n\n\/\/-----------------------------------------------------------------------------\nCMyString\nDboxMain::GetPassword(void) const\n{\n PWSprefs *prefs = PWSprefs::GetInstance();\n CPasswordCharPool pwchars(prefs->GetPref(PWSprefs::IntPrefs::PWLenDefault),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWUseLowercase),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWUseUppercase),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWUseDigits),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWUseSymbols),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWUseHexDigits),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWEasyVision));\n\n return pwchars.MakePassword();\n}\n\n\n\nadd comment.\/\/\/ \\file DboxPassword.cpp\n\/\/-----------------------------------------------------------------------------\n\n#include \"PasswordSafe.h\"\n\n#include \"ThisMfcApp.h\"\n#include \"corelib\/Util.h\"\n#include \"corelib\/PWCharPool.h\"\n#include \"corelib\/PWSprefs.h\"\n\n#include \"DboxMain.h\"\n\n\n\/\/-----------------------------------------------------------------------------\n\n\/\/ Generate a new random password.\nCMyString\nDboxMain::GetPassword(void) const\n{\n PWSprefs *prefs = PWSprefs::GetInstance();\n CPasswordCharPool pwchars(prefs->GetPref(PWSprefs::IntPrefs::PWLenDefault),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWUseLowercase),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWUseUppercase),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWUseDigits),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWUseSymbols),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWUseHexDigits),\n\t\t\t prefs->GetPref(PWSprefs::BoolPrefs::PWEasyVision));\n\n return pwchars.MakePassword();\n}\n\n\n\n<|endoftext|>"} {"text":"[webgui] use loopback address by default<|endoftext|>"} {"text":"\/* \n * Copyright 2009 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"version.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\nusing namespace votca::csg;\nusing namespace votca::tools;\n\nvoid help_text()\n{\n votca::csg::HelpTextHeader(\"csg_resample\");\n cout << \"Change grid + interval of any sort of table files.\\n\"\n \"Mainly called internally by inverse script, can also be\\n\"\n \"used to manually prepare input files for coarse-grained\\n\"\n \"simulations.\\n\\n\"; \n}\n\nvoid check_option(po::options_description &desc, po::variables_map &vm, const string &option)\n{\n if(!vm.count(option)) {\n cout << \"csg_resample \\n\\n\"; \n cout << desc << endl << \"parameter \" << option << \" is not specified\\n\";\n exit(1);\n }\n}\n\nint main(int argc, char** argv)\n{\n\n string in_file, out_file, grid, fitgrid, comment, type, boundaries;\n Spline *spline;\n Table in, out, der;\n \/\/ program options\n po::options_description desc(\"Allowed options\"); \n \n desc.add_options()\n (\"in\", po::value(&in_file), \"table to read\")\n (\"out\", po::value(&out_file), \"table to write\")\n (\"derivative\", po::value(), \"table to write\")\n (\"grid\", po::value(&grid), \"new grid spacing (min:step:max). If 'grid' is specified only, interpolation is performed.\")\n (\"type\", po::value(&type)->default_value(\"akima\"), \"[cubic|akima|linear]. If option is not specified, the default type 'akima' is assumed.\")\n (\"fitgrid\", po::value(&fitgrid), \"specify fit grid (min:step:max). If 'grid' and 'fitgrid' are specified, a fit is performed.\")\n (\"nocut\", \"Option for fitgrid: Normally, values out of fitgrid boundaries are cut off. If they shouldn't, choose --nocut.\")\n (\"comment\", po::value(&comment), \"store a comment in the output table\")\n (\"boundaries\", po::value(&boundaries), \"(natural|periodic|derivativezero) sets boundary conditions\")\n (\"help\", \"options file for coarse graining\");\n \n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm); \n po::notify(vm);\n }\n catch(po::error err) {\n cout << \"error parsing command line: \" << err.what() << endl;\n return -1;\n }\n \n \/\/ does the user want help?\n if (vm.count(\"help\")) {\n help_text();\n cout << desc << endl;\n return 0;\n }\n \n check_option(desc, vm, \"in\");\n check_option(desc, vm, \"out\");\n\n if(!(vm.count(\"grid\") || vm.count(\"fitgrid\"))) {\n cout << \"Need grid for interpolation or fitgrid for fit.\\n\";\n return 1;\n }\n\n if((!vm.count(\"grid\")) && vm.count(\"fitgrid\")) {\n cout << \"Need a grid for fitting as well.\\n\";\n return 1;\n }\n\n \n double min, max, step;\n {\n Tokenizer tok(grid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format, use min:step:max\\n\";\n return 1; \n }\n min = boost::lexical_cast(toks[0]);\n step = boost::lexical_cast(toks[1]);\n max = boost::lexical_cast(toks[2]);\n }\n\n \n in.Load(in_file);\n\n if (vm.count(\"type\")) {\n if(type==\"cubic\") {\n spline = new CubicSpline();\n }\n else if(type==\"akima\") {\n spline = new AkimaSpline();\n }\n else if(type==\"linear\") {\n spline = new LinSpline();\n }\n else {\n throw std::runtime_error(\"unknown type\");\n }\n }\n spline->setBC(Spline::splineNormal);\n \n\n if (vm.count(\"boundaries\")) {\n if(boundaries==\"periodic\") {\n spline->setBC(Spline::splinePeriodic);\n }\n if(boundaries==\"derivativezero\") {\n spline->setBC(Spline::splineDerivativeZero);\n }\n \/\/default: normal\n }\n\n\n \/\/ in case fit is specified\n if (vm.count(\"fitgrid\")) {\n Tokenizer tok(fitgrid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format in fitgrid, use min:step:max\\n\";\n return 1; \n }\n double sp_min, sp_max, sp_step;\n sp_min = boost::lexical_cast(toks[0]);\n sp_step = boost::lexical_cast(toks[1]);\n sp_max = boost::lexical_cast(toks[2]);\n cout << \"doing \" << type << \" fit \" << sp_min << \":\" << sp_step << \":\" << sp_max << endl;\n\n \/\/ cut off any values out of fitgrid boundaries (exception: do nothing in case of --nocut)\n ub::vector x_copy;\n ub::vector y_copy;\n if (!vm.count(\"nocut\")) {\n \/\/ determine vector size\n int minindex=-1, maxindex;\n for (int i=0; i(maxindex-minindex+1);\n y_copy = ub::zero_vector(maxindex-minindex+1);\n for (int i=minindex; i<=maxindex; i++) {\n x_copy(i-minindex) = in.x(i);\n y_copy(i-minindex) = in.y(i);\n }\n }\n\n \/\/ fitting\n spline->GenerateGrid(sp_min, sp_max, sp_step);\n if (vm.count(\"nocut\")) {\n spline->Fit(in.x(), in.y());\n } else {\n spline->Fit(x_copy, y_copy);\n }\n } else {\n \/\/ otherwise do interpolation (default = cubic)\n spline->Interpolate(in.x(), in.y());\n }\n\n \n out.GenerateGridSpacing(min, max, step);\n spline->Calculate(out.x(), out.y());\n \n \n \/\/store a comment line\n if (vm.count(\"comment\")){\n out.set_comment(comment);\n }\n out.y() = out.y();\n out.flags() = ub::scalar_vector(out.flags().size(), 'o');\n\n int i=0;\n for(i=0; out.x(i) < in.x(0) && i= out.x(i) || fabs(in.x(j)-out.x(i) ) < 1e-12) \/\/ fix for precison errors\n break; \n if(in.size() == j) break;\n out.flags(i) = in.flags(j);\n }\n \n out.Save(out_file);\n \n if (vm.count(\"derivative\")) {\n der.GenerateGridSpacing(min, max, step);\n der.flags() = ub::scalar_vector(der.flags().size(), 'o');\n\n spline->CalculateDerivative(der.x(), der.y());\n\n der.Save(vm[\"derivative\"].as());\n }\n\n delete spline;\n return 0;\n}\n\nerror handling in csg_resample\/* \n * Copyright 2009 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"version.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\nusing namespace votca::csg;\nusing namespace votca::tools;\n\nvoid help_text()\n{\n votca::csg::HelpTextHeader(\"csg_resample\");\n cout << \"Change grid + interval of any sort of table files.\\n\"\n \"Mainly called internally by inverse script, can also be\\n\"\n \"used to manually prepare input files for coarse-grained\\n\"\n \"simulations.\\n\\n\"; \n}\n\nvoid check_option(po::options_description &desc, po::variables_map &vm, const string &option)\n{\n if(!vm.count(option)) {\n cout << \"csg_resample \\n\\n\"; \n cout << desc << endl << \"parameter \" << option << \" is not specified\\n\";\n exit(1);\n }\n}\n\nint main(int argc, char** argv)\n{\n\n string in_file, out_file, grid, fitgrid, comment, type, boundaries;\n Spline *spline;\n Table in, out, der;\n \/\/ program options\n po::options_description desc(\"Allowed options\"); \n \n desc.add_options()\n (\"in\", po::value(&in_file), \"table to read\")\n (\"out\", po::value(&out_file), \"table to write\")\n (\"derivative\", po::value(), \"table to write\")\n (\"grid\", po::value(&grid), \"new grid spacing (min:step:max). If 'grid' is specified only, interpolation is performed.\")\n (\"type\", po::value(&type)->default_value(\"akima\"), \"[cubic|akima|linear]. If option is not specified, the default type 'akima' is assumed.\")\n (\"fitgrid\", po::value(&fitgrid), \"specify fit grid (min:step:max). If 'grid' and 'fitgrid' are specified, a fit is performed.\")\n (\"nocut\", \"Option for fitgrid: Normally, values out of fitgrid boundaries are cut off. If they shouldn't, choose --nocut.\")\n (\"comment\", po::value(&comment), \"store a comment in the output table\")\n (\"boundaries\", po::value(&boundaries), \"(natural|periodic|derivativezero) sets boundary conditions\")\n (\"help\", \"options file for coarse graining\");\n \n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm); \n po::notify(vm);\n }\n catch(po::error err) {\n cout << \"error parsing command line: \" << err.what() << endl;\n return -1;\n }\n \n \/\/ does the user want help?\n if (vm.count(\"help\")) {\n help_text();\n cout << desc << endl;\n return 0;\n }\n \n check_option(desc, vm, \"in\");\n check_option(desc, vm, \"out\");\n\n if(!(vm.count(\"grid\") || vm.count(\"fitgrid\"))) {\n cout << \"Need grid for interpolation or fitgrid for fit.\\n\";\n return 1;\n }\n\n if((!vm.count(\"grid\")) && vm.count(\"fitgrid\")) {\n cout << \"Need a grid for fitting as well.\\n\";\n return 1;\n }\n\n \n double min, max, step;\n {\n Tokenizer tok(grid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format, use min:step:max\\n\";\n return 1; \n }\n min = boost::lexical_cast(toks[0]);\n step = boost::lexical_cast(toks[1]);\n max = boost::lexical_cast(toks[2]);\n }\n\n \n in.Load(in_file);\n\n if (vm.count(\"type\")) {\n if(type==\"cubic\") {\n spline = new CubicSpline();\n }\n else if(type==\"akima\") {\n spline = new AkimaSpline();\n }\n else if(type==\"linear\") {\n spline = new LinSpline();\n }\n else {\n throw std::runtime_error(\"unknown type\");\n }\n }\n spline->setBC(Spline::splineNormal);\n \n\n if (vm.count(\"boundaries\")) {\n if(boundaries==\"periodic\") {\n spline->setBC(Spline::splinePeriodic);\n }\n if(boundaries==\"derivativezero\") {\n spline->setBC(Spline::splineDerivativeZero);\n }\n \/\/default: normal\n }\n\n\n \/\/ in case fit is specified\n if (vm.count(\"fitgrid\")) {\n Tokenizer tok(fitgrid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format in fitgrid, use min:step:max\\n\";\n return 1; \n }\n double sp_min, sp_max, sp_step;\n sp_min = boost::lexical_cast(toks[0]);\n sp_step = boost::lexical_cast(toks[1]);\n sp_max = boost::lexical_cast(toks[2]);\n cout << \"doing \" << type << \" fit \" << sp_min << \":\" << sp_step << \":\" << sp_max << endl;\n\n \/\/ cut off any values out of fitgrid boundaries (exception: do nothing in case of --nocut)\n ub::vector x_copy;\n ub::vector y_copy;\n if (!vm.count(\"nocut\")) {\n \/\/ determine vector size\n int minindex=-1, maxindex;\n for (int i=0; i(maxindex-minindex+1);\n y_copy = ub::zero_vector(maxindex-minindex+1);\n for (int i=minindex; i<=maxindex; i++) {\n x_copy(i-minindex) = in.x(i);\n y_copy(i-minindex) = in.y(i);\n }\n }\n\n \/\/ fitting\n spline->GenerateGrid(sp_min, sp_max, sp_step);\n try {\n if (vm.count(\"nocut\")) {\n spline->Fit(in.x(), in.y());\n } else {\n spline->Fit(x_copy, y_copy);\n } \n } catch (const char* message) {\n if(message=\"qrsolve_zero_column_in_matrix\") {\n throw std::runtime_error(\"error in Linalg::linalg_qrsolve : Not enough data for fit, please adjust grid (zero row in fit matrix)\");\n } \n else if(message=\"constrained_qrsolve_zero_column_in_matrix\") {\n throw std::runtime_error(\"error in Linalg::linalg_constrained_qrsolve : Not enough data for fit, please adjust grid (zero row in fit matrix)\");\n }\n else throw std::runtime_error(\"Unknown error in csg_resample while fitting.\");\n }\n } else {\n \/\/ otherwise do interpolation (default = cubic)\n try {\n spline->Interpolate(in.x(), in.y());\n } catch (const char* message) {\n if(message=\"qrsolve_zero_column_in_matrix\") {\n throw std::runtime_error(\"error in Linalg::linalg_qrsolve : Not enough data, please adjust grid (zero row in fit matrix)\");\n }\n else if(message=\"constrained_qrsolve_zero_column_in_matrix\") {\n throw std::runtime_error(\"error in Linalg::linalg_constrained_qrsolve : Not enough data, please adjust grid (zero row in fit matrix)\");\n }\n else throw std::runtime_error(\"Unknown error in csg_resample while interpolating.\");\n }\n }\n\n \n out.GenerateGridSpacing(min, max, step);\n spline->Calculate(out.x(), out.y());\n \n \n \/\/store a comment line\n if (vm.count(\"comment\")){\n out.set_comment(comment);\n }\n out.y() = out.y();\n out.flags() = ub::scalar_vector(out.flags().size(), 'o');\n\n int i=0;\n for(i=0; out.x(i) < in.x(0) && i= out.x(i) || fabs(in.x(j)-out.x(i) ) < 1e-12) \/\/ fix for precison errors\n break; \n if(in.size() == j) break;\n out.flags(i) = in.flags(j);\n }\n \n out.Save(out_file);\n \n if (vm.count(\"derivative\")) {\n der.GenerateGridSpacing(min, max, step);\n der.flags() = ub::scalar_vector(der.flags().size(), 'o');\n\n spline->CalculateDerivative(der.x(), der.y());\n\n der.Save(vm[\"derivative\"].as());\n }\n\n delete spline;\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/* \n * Copyright 2009 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"version.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\nusing namespace votca::csg;\nusing namespace votca::tools;\n\nvoid help_text()\n{\n votca::csg::HelpTextHeader(\"csg_resample\");\n cout << \"Change grid + interval of any sort of table files.\\n\"\n \"Mainly called internally by inverse script, can also be\\n\"\n \"used to manually prepare input files for coarse-grained\\n\"\n \"simulations.\\n\\n\"; \n}\n\nvoid check_option(po::options_description &desc, po::variables_map &vm, const string &option)\n{\n if(!vm.count(option)) {\n cout << \"csg_resample \\n\\n\"; \n cout << desc << endl << \"parameter \" << option << \" is not specified\\n\";\n exit(1);\n }\n}\n\nint main(int argc, char** argv)\n{\n string in_file, out_file, grid, spfit, comment, boundaries;\n CubicSpline spline;\n Table in, out, der;\n\n \/\/ program options\n po::options_description desc(\"Allowed options\"); \n \n desc.add_options()\n (\"in\", po::value(&in_file), \"table to read\")\n (\"out\", po::value(&out_file), \"table to write\")\n (\"derivative\", po::value(), \"table to write\")\n (\"grid\", po::value(&grid), \"new grid spacing (min:step:max)\")\n (\"spfit\", po::value(&spfit), \"specify spline fit grid. if option is not specified, normal spline interpolation is performed\")\n \/\/(\"bc\", po::)\n (\"comment\", po::value(&comment), \"store a comment in the output table\")\n (\"boundaries\", po::value(&boundaries), \"(natural|periodic|derivativezero) sets boundary conditions\")\n (\"help\", \"options file for coarse graining\");\n \n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm); \n po::notify(vm);\n }\n catch(po::error err) {\n cout << \"error parsing command line: \" << err.what() << endl;\n return -1;\n }\n \n \/\/ does the user want help?\n if (vm.count(\"help\")) {\n help_text();\n cout << desc << endl;\n return 0;\n }\n \n check_option(desc, vm, \"in\");\n check_option(desc, vm, \"out\");\n check_option(desc, vm, \"grid\");\n \n double min, max, step;\n {\n Tokenizer tok(grid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format, use min:step:max\\n\";\n return 1; \n }\n min = boost::lexical_cast(toks[0]);\n step = boost::lexical_cast(toks[1]);\n max = boost::lexical_cast(toks[2]);\n }\n \n \n in.Load(in_file);\n \n if (vm.count(\"boundaries\")){\n if (boundaries==\"periodic\"){\n spline.setBC(CubicSpline::splinePeriodic);\n }\n else if (boundaries==\"derivativezero\"){\n spline.setBC(CubicSpline::splineDerivativeZero);\n }\n \/\/default: normal\n } \n if (vm.count(\"spfit\")) {\n Tokenizer tok(spfit, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format in spfit, use min:step:max\\n\";\n return 1; \n }\n double sp_min, sp_max, sp_step;\n sp_min = boost::lexical_cast(toks[0]);\n sp_step = boost::lexical_cast(toks[1]);\n sp_max = boost::lexical_cast(toks[2]);\n cout << \"doing spline fit \" << sp_min << \":\" << sp_step << \":\" << sp_max << endl;\n spline.GenerateGrid(sp_min, sp_max, sp_step);\n\n spline.Fit(in.x(), in.y());\n } else {\n spline.Interpolate(in.x(), in.y());\n }\n \n out.GenerateGridSpacing(min, max, step);\n spline.Calculate(out.x(), out.y());\n \n \/\/store a comment line\n if (vm.count(\"comment\")){\n out.set_comment(comment);\n }\n out.y() = out.y();\n out.flags() = ub::scalar_vector(out.flags().size(), 'o');\n\n int i=0;\n for(i=0; out.x(i) < in.x(0) && i= out.x(i))\n break; \n if(in.size() == j) break;\n out.flags(i) = in.flags(j);\n }\n \n out.Save(out_file);\n \n if (vm.count(\"derivative\")) {\n der.GenerateGridSpacing(min, max, step);\n der.flags() = ub::scalar_vector(der.flags().size(), 'o');\n spline.CalculateDerivative(der.x(), der.y());\n der.Save(vm[\"derivative\"].as());\n }\n return 0;\n}\n\nadded akima support to csg_resample\/* \n * Copyright 2009 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"version.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\nusing namespace votca::csg;\nusing namespace votca::tools;\n\nvoid help_text()\n{\n votca::csg::HelpTextHeader(\"csg_resample\");\n cout << \"Change grid + interval of any sort of table files.\\n\"\n \"Mainly called internally by inverse script, can also be\\n\"\n \"used to manually prepare input files for coarse-grained\\n\"\n \"simulations.\\n\\n\"; \n}\n\nvoid check_option(po::options_description &desc, po::variables_map &vm, const string &option)\n{\n if(!vm.count(option)) {\n cout << \"csg_resample \\n\\n\"; \n cout << desc << endl << \"parameter \" << option << \" is not specified\\n\";\n exit(1);\n }\n}\n\nint main(int argc, char** argv)\n{\n\n string in_file, out_file, grid, fitgrid, comment, type, boundaries;\n CubicSpline spline;\n AkimaSpline akspline;\n LinSpline linspline;\n Table in, out, der;\n\n \/\/ program options\n po::options_description desc(\"Allowed options\"); \n \n desc.add_options()\n (\"in\", po::value(&in_file), \"table to read\")\n (\"out\", po::value(&out_file), \"table to write\")\n (\"derivative\", po::value(), \"table to write\")\n (\"grid\", po::value(&grid), \"new grid spacing (min:step:max). If 'grid' is specified only, interpolation is performed.\")\n (\"type\", po::value(&type)->default_value(\"akima\"), \"[cubic|akima|linear]. If option is not specified, the default type 'akima' is assumed.\")\n (\"fitgrid\", po::value(&fitgrid), \"specify fit grid (min:step:max). If 'grid' and 'fitgrid' are specified, a fit is performed.\")\n (\"comment\", po::value(&comment), \"store a comment in the output table\")\n (\"boundaries\", po::value(&boundaries), \"(natural|periodic|derivativezero) sets boundary conditions\")\n (\"help\", \"options file for coarse graining\");\n \n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm); \n po::notify(vm);\n }\n catch(po::error err) {\n cout << \"error parsing command line: \" << err.what() << endl;\n return -1;\n }\n \n \/\/ does the user want help?\n if (vm.count(\"help\")) {\n help_text();\n cout << desc << endl;\n return 0;\n }\n \n check_option(desc, vm, \"in\");\n check_option(desc, vm, \"out\");\n\n if(!(vm.count(\"grid\") || vm.count(\"fitgrid\"))) {\n cout << \"Need grid for interpolation or fitgrid for fit.\\n\";\n return 1;\n }\n\n if((!vm.count(\"grid\")) && vm.count(\"fitgrid\")) {\n cout << \"Need a grid for fitting as well.\\n\";\n return 1;\n }\n\n \n double min, max, step;\n {\n Tokenizer tok(grid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format, use min:step:max\\n\";\n return 1; \n }\n min = boost::lexical_cast(toks[0]);\n step = boost::lexical_cast(toks[1]);\n max = boost::lexical_cast(toks[2]);\n }\n\n \n in.Load(in_file);\n\n if (vm.count(\"type\")) {\n if(type==\"cubic\") {\n spline.setBC(CubicSpline::splineNormal);\n }\n if(type==\"akima\") {\n akspline.setBC(AkimaSpline::splineNormal);\n }\n if(type==\"linear\") {\n linspline.setBC(LinSpline::splineNormal);\n }\n }\n \n\n if (vm.count(\"boundaries\")) {\n if(boundaries==\"periodic\") {\n spline.setBC(CubicSpline::splinePeriodic);\n akspline.setBC(AkimaSpline::splinePeriodic);\n linspline.setBC(LinSpline::splinePeriodic);\n }\n if(boundaries==\"derivativezero\") {\n spline.setBC(CubicSpline::splineDerivativeZero);\n }\n \/\/default: normal\n } \n\n\n \/\/ in case fit is specified\n if (vm.count(\"fitgrid\")) {\n Tokenizer tok(fitgrid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format in fitgrid, use min:step:max\\n\";\n return 1; \n }\n double sp_min, sp_max, sp_step;\n sp_min = boost::lexical_cast(toks[0]);\n sp_step = boost::lexical_cast(toks[1]);\n sp_max = boost::lexical_cast(toks[2]);\n cout << \"doing \" << type << \" fit \" << sp_min << \":\" << sp_step << \":\" << sp_max << endl;\n\n if(type==\"cubic\") {\n spline.GenerateGrid(sp_min, sp_max, sp_step);\n spline.Fit(in.x(), in.y());\n }\n if(type==\"akima\") {\n akspline.GenerateGrid(sp_min, sp_max, sp_step);\n akspline.Fit(in.x(), in.y());\n }\n if(type==\"linear\") {\n linspline.GenerateGrid(sp_min, sp_max, sp_step);\n linspline.Fit(in.x(), in.y());\n }\n } else {\n \/\/ else: do interpolation (default = cubic)\n if(type==\"cubic\") {\n spline.Interpolate(in.x(), in.y());\n }\n if(type==\"akima\") {\n akspline.Interpolate(in.x(), in.y());\n }\n if(type==\"linear\") {\n linspline.Interpolate(in.x(), in.y());\n }\n }\n\n \n out.GenerateGridSpacing(min, max, step);\n\n if(type==\"cubic\") {\n spline.Calculate(out.x(), out.y());\n }\n if(type==\"akima\") {\n akspline.Calculate(out.x(), out.y());\n }\n if(type==\"linear\") {\n linspline.Calculate(out.x(), out.y());\n }\n \n \n \/\/store a comment line\n if (vm.count(\"comment\")){\n out.set_comment(comment);\n }\n out.y() = out.y();\n out.flags() = ub::scalar_vector(out.flags().size(), 'o');\n\n int i=0;\n for(i=0; out.x(i) < in.x(0) && i= out.x(i))\n break; \n if(in.size() == j) break;\n out.flags(i) = in.flags(j);\n }\n \n out.Save(out_file);\n \n if (vm.count(\"derivative\")) {\n der.GenerateGridSpacing(min, max, step);\n der.flags() = ub::scalar_vector(der.flags().size(), 'o');\n\n if (type == \"cubic\") {\n spline.CalculateDerivative(der.x(), der.y());\n }\n if (type == \"akima\") {\n akspline.CalculateDerivative(der.x(), der.y());\n }\n if (type == \"linear\") {\n linspline.CalculateDerivative(der.x(), der.y());\n }\n der.Save(vm[\"derivative\"].as());\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*ckwg +5\n * Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"helpers\/pipeline_builder.h\"\n#include \"helpers\/tool_main.h\"\n#include \"helpers\/tool_usage.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nclass config_printer\n : public boost::static_visitor<>\n{\n public:\n config_printer(std::ostream& ostr, vistk::pipeline_t const& pipe, vistk::config_t const& conf);\n ~config_printer();\n\n void operator () (vistk::config_pipe_block const& config_block);\n void operator () (vistk::process_pipe_block const& process_block);\n void operator () (vistk::connect_pipe_block const& connect_block) const;\n\n void output_process_defaults();\n private:\n void print_config_value(vistk::config_value_t const& config_value) const;\n void output_process_by_name(vistk::process::name_t const& name, bool fatal_if_no_process);\n void output_process(vistk::process_t const& proc);\n\n typedef std::set process_set_t;\n\n std::ostream& m_ostr;\n vistk::pipeline_t const m_pipe;\n vistk::config_t const m_config;\n process_set_t m_visited;\n};\n\nint\ntool_main(int argc, char* argv[])\n{\n vistk::load_known_modules();\n\n boost::program_options::options_description desc;\n desc\n .add(tool_common_options())\n .add(pipeline_common_options())\n .add(pipeline_input_options())\n .add(pipeline_output_options());\n\n boost::program_options::variables_map const vm = tool_parse(argc, argv, desc);\n\n pipeline_builder const builder(vm, desc);\n\n vistk::pipeline_t const pipe = builder.pipeline();\n vistk::config_t const config = builder.config();\n vistk::pipe_blocks const blocks = builder.blocks();\n\n if (!pipe)\n {\n std::cerr << \"Error: Unable to bake pipeline\" << std::endl;\n\n return EXIT_FAILURE;\n }\n\n std::ostream* postr;\n boost::filesystem::ofstream fout;\n\n vistk::path_t const opath = vm[\"output\"].as();\n\n if (opath == vistk::path_t(\"-\"))\n {\n postr = &std::cout;\n }\n else\n {\n fout.open(opath);\n\n if (fout.bad())\n {\n std::cerr << \"Error: Unable to open output file\" << std::endl;\n\n return EXIT_FAILURE;\n }\n\n postr = &fout;\n }\n\n std::ostream& ostr = *postr;\n\n config_printer printer(ostr, pipe, config);\n\n std::for_each(blocks.begin(), blocks.end(), boost::apply_visitor(printer));\n\n printer.output_process_defaults();\n\n return EXIT_SUCCESS;\n}\n\nconfig_printer\n::config_printer(std::ostream& ostr, vistk::pipeline_t const& pipe, vistk::config_t const& conf)\n : m_ostr(ostr)\n , m_pipe(pipe)\n , m_config(conf)\n{\n}\n\nconfig_printer\n::~config_printer()\n{\n}\n\nclass key_printer\n{\n public:\n key_printer(std::ostream& ostr);\n ~key_printer();\n\n void operator () (vistk::config_value_t const& config_value) const;\n private:\n std::ostream& m_ostr;\n};\n\nvoid\nconfig_printer\n::operator () (vistk::config_pipe_block const& config_block)\n{\n vistk::config::keys_t const& keys = config_block.key;\n vistk::config_values_t const& values = config_block.values;\n\n vistk::config::key_t const key_path = boost::join(keys, vistk::config::block_sep);\n\n m_ostr << \"config \" << key_path << std::endl;\n\n key_printer const printer(m_ostr);\n\n std::for_each(values.begin(), values.end(), printer);\n\n output_process_by_name(key_path, false);\n}\n\nvoid\nconfig_printer\n::operator () (vistk::process_pipe_block const& process_block)\n{\n vistk::process::name_t const& name = process_block.name;\n vistk::process::type_t const& type = process_block.type;\n vistk::config_values_t const& values = process_block.config_values;\n\n m_ostr << \"process \" << name << std::endl;\n m_ostr << \" :: \" << type << std::endl;\n\n key_printer const printer(m_ostr);\n\n std::for_each(values.begin(), values.end(), printer);\n\n output_process_by_name(name, true);\n}\n\nvoid\nconfig_printer\n::operator () (vistk::connect_pipe_block const& connect_block) const\n{\n vistk::process::port_addr_t const& upstream_addr = connect_block.from;\n vistk::process::port_addr_t const& downstream_addr = connect_block.to;\n\n vistk::process::name_t const& upstream_name = upstream_addr.first;\n vistk::process::port_t const& upstream_port = upstream_addr.second;\n vistk::process::name_t const& downstream_name = downstream_addr.first;\n vistk::process::port_t const& downstream_port = downstream_addr.second;\n\n m_ostr << \"connect from \" << upstream_name << \".\" << upstream_port << std::endl;\n m_ostr << \" to \" << downstream_name << \".\" << downstream_port << std::endl;\n\n m_ostr << std::endl;\n}\n\nvoid\nconfig_printer\n::output_process_defaults()\n{\n vistk::process::names_t const cluster_names = m_pipe->cluster_names();\n\n BOOST_FOREACH (vistk::process::name_t const& name, cluster_names)\n {\n if (m_visited.count(name))\n {\n continue;\n }\n\n vistk::process_cluster_t const cluster = m_pipe->cluster_by_name(name);\n vistk::process_t const proc = boost::static_pointer_cast(cluster);\n\n vistk::process::type_t const& type = proc->type();\n\n m_ostr << \"# Defaults for \\'\" << name << \"\\' cluster:\" << std::endl;\n m_ostr << \"config \" << name << std::endl;\n m_ostr << \"# :: \" << type << std::endl;\n\n output_process(proc);\n }\n\n vistk::process::names_t const process_names = m_pipe->process_names();\n\n BOOST_FOREACH (vistk::process::name_t const& name, process_names)\n {\n if (m_visited.count(name))\n {\n continue;\n }\n\n vistk::process_t const proc = m_pipe->process_by_name(name);\n\n vistk::process::type_t const& type = proc->type();\n\n m_ostr << \"# Defaults for \\'\" << name << \"\\' process:\" << std::endl;\n m_ostr << \"config \" << name << std::endl;\n m_ostr << \"# :: \" << type << std::endl;\n\n output_process(proc);\n }\n}\n\nvoid\nconfig_printer\n::output_process_by_name(vistk::process::name_t const& name, bool fatal_if_no_process)\n{\n vistk::process_t proc;\n\n if (!m_visited.count(name))\n {\n try\n {\n proc = m_pipe->process_by_name(name);\n }\n catch (vistk::no_such_process_exception const& \/*e*\/)\n {\n try\n {\n vistk::process_cluster_t const cluster = m_pipe->cluster_by_name(name);\n\n proc = boost::static_pointer_cast(cluster);\n }\n catch (vistk::no_such_process_exception const& \/*e*\/)\n {\n if (fatal_if_no_process)\n {\n std::string const reason = \"A process block did not result in a process being \"\n \"added to the pipeline: \" + name;\n\n throw std::logic_error(reason);\n }\n }\n }\n }\n\n if (proc)\n {\n output_process(proc);\n }\n else\n {\n m_ostr << std::endl;\n }\n}\n\nvoid\nconfig_printer\n::output_process(vistk::process_t const& proc)\n{\n vistk::process::name_t const name = proc->name();\n vistk::config::keys_t const keys = proc->available_config();\n\n BOOST_FOREACH (vistk::config::key_t const& key, keys)\n {\n if (boost::starts_with(key, \"_\"))\n {\n continue;\n }\n\n m_ostr << std::endl;\n\n vistk::process::conf_info_t const& info = proc->config_info(key);\n\n vistk::config::description_t const desc = boost::replace_all_copy(info->description, \"\\n\", \"\\n # \");\n\n m_ostr << \" # Key: \" << key << std::endl;\n\n m_ostr << \" # Description: \" << desc << std::endl;\n\n vistk::config::value_t const& def = info->def;\n\n if (def.empty())\n {\n m_ostr << \" # No default value\" << std::endl;\n }\n else\n {\n m_ostr << \" # Default value: \" << def << std::endl;\n }\n\n vistk::config::key_t const resolved_key = name + vistk::config::block_sep + key;\n\n if (m_config->has_value(resolved_key))\n {\n vistk::config::value_t const cur_value = m_config->get_value(resolved_key);\n\n m_ostr << \" # Current value: \" << cur_value << std::endl;\n }\n else\n {\n m_ostr << \" # No current value\" << std::endl;\n }\n }\n\n m_ostr << std::endl;\n\n m_visited.insert(name);\n}\n\nkey_printer\n::key_printer(std::ostream& ostr)\n : m_ostr(ostr)\n{\n}\n\nkey_printer\n::~key_printer()\n{\n}\n\nvoid\nkey_printer\n::operator () (vistk::config_value_t const& config_value) const\n{\n vistk::config_key_t const& key = config_value.key;\n vistk::config::value_t const& value = config_value.value;\n\n vistk::config::keys_t const& keys = key.key_path;\n vistk::config_key_options_t const& options = key.options;\n\n vistk::config::key_t const key_path = boost::join(keys, vistk::config::block_sep);\n\n boost::optional const& flags = options.flags;\n boost::optional const& provider = options.provider;\n\n m_ostr << \" \" << vistk::config::block_sep << key_path;\n\n if (flags)\n {\n vistk::config_flag_t const flag_list = boost::join(*flags, \",\");\n\n m_ostr << \"[\" << flag_list << \"]\";\n }\n\n if (provider)\n {\n m_ostr << \"{\" << *provider << \"}\";\n }\n\n m_ostr << \" \" << value << std::endl;\n}\nRefactor printing a process block from nothing\/*ckwg +5\n * Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"helpers\/pipeline_builder.h\"\n#include \"helpers\/tool_main.h\"\n#include \"helpers\/tool_usage.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nclass config_printer\n : public boost::static_visitor<>\n{\n public:\n config_printer(std::ostream& ostr, vistk::pipeline_t const& pipe, vistk::config_t const& conf);\n ~config_printer();\n\n void operator () (vistk::config_pipe_block const& config_block);\n void operator () (vistk::process_pipe_block const& process_block);\n void operator () (vistk::connect_pipe_block const& connect_block) const;\n\n void output_process_defaults();\n private:\n void print_config_value(vistk::config_value_t const& config_value) const;\n void output_process_by_name(vistk::process::name_t const& name, bool fatal_if_no_process);\n void output_process_block(vistk::process_t const& name, std::string const& kind);\n void output_process(vistk::process_t const& proc);\n\n typedef std::set process_set_t;\n\n std::ostream& m_ostr;\n vistk::pipeline_t const m_pipe;\n vistk::config_t const m_config;\n process_set_t m_visited;\n};\n\nint\ntool_main(int argc, char* argv[])\n{\n vistk::load_known_modules();\n\n boost::program_options::options_description desc;\n desc\n .add(tool_common_options())\n .add(pipeline_common_options())\n .add(pipeline_input_options())\n .add(pipeline_output_options());\n\n boost::program_options::variables_map const vm = tool_parse(argc, argv, desc);\n\n pipeline_builder const builder(vm, desc);\n\n vistk::pipeline_t const pipe = builder.pipeline();\n vistk::config_t const config = builder.config();\n vistk::pipe_blocks const blocks = builder.blocks();\n\n if (!pipe)\n {\n std::cerr << \"Error: Unable to bake pipeline\" << std::endl;\n\n return EXIT_FAILURE;\n }\n\n std::ostream* postr;\n boost::filesystem::ofstream fout;\n\n vistk::path_t const opath = vm[\"output\"].as();\n\n if (opath == vistk::path_t(\"-\"))\n {\n postr = &std::cout;\n }\n else\n {\n fout.open(opath);\n\n if (fout.bad())\n {\n std::cerr << \"Error: Unable to open output file\" << std::endl;\n\n return EXIT_FAILURE;\n }\n\n postr = &fout;\n }\n\n std::ostream& ostr = *postr;\n\n config_printer printer(ostr, pipe, config);\n\n std::for_each(blocks.begin(), blocks.end(), boost::apply_visitor(printer));\n\n printer.output_process_defaults();\n\n return EXIT_SUCCESS;\n}\n\nconfig_printer\n::config_printer(std::ostream& ostr, vistk::pipeline_t const& pipe, vistk::config_t const& conf)\n : m_ostr(ostr)\n , m_pipe(pipe)\n , m_config(conf)\n{\n}\n\nconfig_printer\n::~config_printer()\n{\n}\n\nclass key_printer\n{\n public:\n key_printer(std::ostream& ostr);\n ~key_printer();\n\n void operator () (vistk::config_value_t const& config_value) const;\n private:\n std::ostream& m_ostr;\n};\n\nvoid\nconfig_printer\n::operator () (vistk::config_pipe_block const& config_block)\n{\n vistk::config::keys_t const& keys = config_block.key;\n vistk::config_values_t const& values = config_block.values;\n\n vistk::config::key_t const key_path = boost::join(keys, vistk::config::block_sep);\n\n m_ostr << \"config \" << key_path << std::endl;\n\n key_printer const printer(m_ostr);\n\n std::for_each(values.begin(), values.end(), printer);\n\n output_process_by_name(key_path, false);\n}\n\nvoid\nconfig_printer\n::operator () (vistk::process_pipe_block const& process_block)\n{\n vistk::process::name_t const& name = process_block.name;\n vistk::process::type_t const& type = process_block.type;\n vistk::config_values_t const& values = process_block.config_values;\n\n m_ostr << \"process \" << name << std::endl;\n m_ostr << \" :: \" << type << std::endl;\n\n key_printer const printer(m_ostr);\n\n std::for_each(values.begin(), values.end(), printer);\n\n output_process_by_name(name, true);\n}\n\nvoid\nconfig_printer\n::operator () (vistk::connect_pipe_block const& connect_block) const\n{\n vistk::process::port_addr_t const& upstream_addr = connect_block.from;\n vistk::process::port_addr_t const& downstream_addr = connect_block.to;\n\n vistk::process::name_t const& upstream_name = upstream_addr.first;\n vistk::process::port_t const& upstream_port = upstream_addr.second;\n vistk::process::name_t const& downstream_name = downstream_addr.first;\n vistk::process::port_t const& downstream_port = downstream_addr.second;\n\n m_ostr << \"connect from \" << upstream_name << \".\" << upstream_port << std::endl;\n m_ostr << \" to \" << downstream_name << \".\" << downstream_port << std::endl;\n\n m_ostr << std::endl;\n}\n\nvoid\nconfig_printer\n::output_process_defaults()\n{\n vistk::process::names_t const cluster_names = m_pipe->cluster_names();\n\n BOOST_FOREACH (vistk::process::name_t const& name, cluster_names)\n {\n if (m_visited.count(name))\n {\n continue;\n }\n\n vistk::process_cluster_t const cluster = m_pipe->cluster_by_name(name);\n vistk::process_t const proc = boost::static_pointer_cast(cluster);\n\n static std::string const kind = \"cluster\";\n\n output_process_block(proc, kind);\n }\n\n vistk::process::names_t const process_names = m_pipe->process_names();\n\n BOOST_FOREACH (vistk::process::name_t const& name, process_names)\n {\n if (m_visited.count(name))\n {\n continue;\n }\n\n vistk::process_t const proc = m_pipe->process_by_name(name);\n\n static std::string const kind = \"process\";\n\n output_process_block(proc, kind);\n }\n}\n\nvoid\nconfig_printer\n::output_process_by_name(vistk::process::name_t const& name, bool fatal_if_no_process)\n{\n vistk::process_t proc;\n\n if (!m_visited.count(name))\n {\n try\n {\n proc = m_pipe->process_by_name(name);\n }\n catch (vistk::no_such_process_exception const& \/*e*\/)\n {\n try\n {\n vistk::process_cluster_t const cluster = m_pipe->cluster_by_name(name);\n\n proc = boost::static_pointer_cast(cluster);\n }\n catch (vistk::no_such_process_exception const& \/*e*\/)\n {\n if (fatal_if_no_process)\n {\n std::string const reason = \"A process block did not result in a process being \"\n \"added to the pipeline: \" + name;\n\n throw std::logic_error(reason);\n }\n }\n }\n }\n\n if (proc)\n {\n output_process(proc);\n }\n else\n {\n m_ostr << std::endl;\n }\n}\n\nvoid\nconfig_printer\n::output_process_block(vistk::process_t const& proc, std::string const& kind)\n{\n vistk::process::type_t const& type = proc->type();\n\n m_ostr << \"# Defaults for \\'\" << name << \"\\' \" << kind << \":\" << std::endl;\n m_ostr << \"config \" << name << std::endl;\n m_ostr << \"# :: \" << type << std::endl;\n\n output_process(proc);\n}\n\nvoid\nconfig_printer\n::output_process(vistk::process_t const& proc)\n{\n vistk::process::name_t const name = proc->name();\n vistk::config::keys_t const keys = proc->available_config();\n\n BOOST_FOREACH (vistk::config::key_t const& key, keys)\n {\n if (boost::starts_with(key, \"_\"))\n {\n continue;\n }\n\n m_ostr << std::endl;\n\n vistk::process::conf_info_t const& info = proc->config_info(key);\n\n vistk::config::description_t const desc = boost::replace_all_copy(info->description, \"\\n\", \"\\n # \");\n\n m_ostr << \" # Key: \" << key << std::endl;\n\n m_ostr << \" # Description: \" << desc << std::endl;\n\n vistk::config::value_t const& def = info->def;\n\n if (def.empty())\n {\n m_ostr << \" # No default value\" << std::endl;\n }\n else\n {\n m_ostr << \" # Default value: \" << def << std::endl;\n }\n\n vistk::config::key_t const resolved_key = name + vistk::config::block_sep + key;\n\n if (m_config->has_value(resolved_key))\n {\n vistk::config::value_t const cur_value = m_config->get_value(resolved_key);\n\n m_ostr << \" # Current value: \" << cur_value << std::endl;\n }\n else\n {\n m_ostr << \" # No current value\" << std::endl;\n }\n }\n\n m_ostr << std::endl;\n\n m_visited.insert(name);\n}\n\nkey_printer\n::key_printer(std::ostream& ostr)\n : m_ostr(ostr)\n{\n}\n\nkey_printer\n::~key_printer()\n{\n}\n\nvoid\nkey_printer\n::operator () (vistk::config_value_t const& config_value) const\n{\n vistk::config_key_t const& key = config_value.key;\n vistk::config::value_t const& value = config_value.value;\n\n vistk::config::keys_t const& keys = key.key_path;\n vistk::config_key_options_t const& options = key.options;\n\n vistk::config::key_t const key_path = boost::join(keys, vistk::config::block_sep);\n\n boost::optional const& flags = options.flags;\n boost::optional const& provider = options.provider;\n\n m_ostr << \" \" << vistk::config::block_sep << key_path;\n\n if (flags)\n {\n vistk::config_flag_t const flag_list = boost::join(*flags, \",\");\n\n m_ostr << \"[\" << flag_list << \"]\";\n }\n\n if (provider)\n {\n m_ostr << \"{\" << *provider << \"}\";\n }\n\n m_ostr << \" \" << value << std::endl;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/login_prompt.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/lock.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/password_manager\/password_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/tab_contents\/constrained_window.h\"\n#include \"chrome\/browser\/tab_contents\/navigation_controller.h\"\n#include \"chrome\/browser\/tab_contents\/tab_util.h\"\n#include \"chrome\/browser\/tab_contents\/web_contents.h\"\n#include \"chrome\/browser\/views\/login_view.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/l10n_util.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/views\/dialog_delegate.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/auth.h\"\n#include \"net\/url_request\/url_request.h\"\n\nusing namespace std;\nusing views::LoginView;\n\nclass LoginHandlerImpl;\n\n\/\/ Helper to remove the ref from an URLRequest to the LoginHandler.\n\/\/ Should only be called from the IO thread, since it accesses an URLRequest.\nstatic void ResetLoginHandlerForRequest(URLRequest* request) {\n ResourceDispatcherHost::ExtraRequestInfo* info =\n ResourceDispatcherHost::ExtraInfoForRequest(request);\n if (!info)\n return;\n\n info->login_handler = NULL;\n}\n\n\/\/ Get the signon_realm under which this auth info should be stored.\n\/\/\n\/\/ The format of the signon_realm for proxy auth is:\n\/\/ proxy-host\/auth-realm\n\/\/ The format of the signon_realm for server auth is:\n\/\/ url-scheme:\/\/url-host[:url-port]\/auth-realm\n\/\/\n\/\/ Be careful when changing this function, since you could make existing\n\/\/ saved logins un-retrievable.\n\nstd::string GetSignonRealm(const GURL& url,\n const net::AuthChallengeInfo& auth_info) {\n std::string signon_realm;\n if (auth_info.is_proxy) {\n signon_realm = WideToASCII(auth_info.host);\n signon_realm.append(\"\/\");\n } else {\n \/\/ Take scheme, host, and port from the url.\n signon_realm = url.GetOrigin().spec();\n \/\/ This ends with a \"\/\".\n }\n signon_realm.append(WideToUTF8(auth_info.realm));\n return signon_realm;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ LoginHandlerImpl\n\n\/\/ This class simply forwards the authentication from the LoginView (on\n\/\/ the UI thread) to the URLRequest (on the I\/O thread).\n\/\/ This class uses ref counting to ensure that it lives until all InvokeLaters\n\/\/ have been called.\nclass LoginHandlerImpl : public LoginHandler,\n public base::RefCountedThreadSafe,\n public views::DialogDelegate {\n public:\n LoginHandlerImpl(URLRequest* request, MessageLoop* ui_loop)\n : dialog_(NULL),\n handled_auth_(false),\n request_(request),\n request_loop_(MessageLoop::current()),\n ui_loop_(ui_loop),\n password_manager_(NULL) {\n DCHECK(request_) << \"LoginHandler constructed with NULL request\";\n\n AddRef(); \/\/ matched by ReleaseLater.\n if (!tab_util::GetTabContentsID(request_, &render_process_host_id_,\n &tab_contents_id_)) {\n NOTREACHED();\n }\n }\n\n ~LoginHandlerImpl() {\n }\n\n \/\/ Initialize the UI part of the LoginHandler.\n \/\/ Scary thread safety note: This can potentially be called *after* SetAuth\n \/\/ or CancelAuth (say, if the request was cancelled before the UI thread got\n \/\/ control). However, that's OK since any UI interaction in those functions\n \/\/ will occur via an InvokeLater on the UI thread, which is guaranteed\n \/\/ to happen after this is called (since this was InvokeLater'd first).\n void InitWithDialog(ConstrainedWindow* dlg) {\n DCHECK(MessageLoop::current() == ui_loop_);\n dialog_ = dlg;\n SendNotifications();\n }\n\n \/\/ Returns the WebContents that needs authentication.\n WebContents* GetWebContentsForLogin() {\n DCHECK(MessageLoop::current() == ui_loop_);\n\n return tab_util::GetWebContentsByID(render_process_host_id_,\n tab_contents_id_);\n }\n\n void set_login_view(LoginView* login_view) {\n login_view_ = login_view;\n }\n\n void set_password_form(const PasswordForm& form) {\n password_form_ = form;\n }\n\n void set_password_manager(PasswordManager* password_manager) {\n password_manager_ = password_manager;\n }\n\n \/\/ views::DialogDelegate methods:\n virtual std::wstring GetDialogButtonLabel(DialogButton button) const {\n if (button == DIALOGBUTTON_OK)\n return l10n_util::GetString(IDS_LOGIN_DIALOG_OK_BUTTON_LABEL);\n return DialogDelegate::GetDialogButtonLabel(button);\n }\n virtual std::wstring GetWindowTitle() const {\n return l10n_util::GetString(IDS_LOGIN_DIALOG_TITLE);\n }\n virtual void WindowClosing() {\n DCHECK(MessageLoop::current() == ui_loop_);\n\n \/\/ Reference is no longer valid.\n dialog_ = NULL;\n\n if (!WasAuthHandled(true)) {\n request_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::CancelAuthDeferred));\n SendNotifications();\n }\n }\n virtual void DeleteDelegate() {\n \/\/ Delete this object once all InvokeLaters have been called.\n request_loop_->ReleaseSoon(FROM_HERE, this);\n }\n virtual bool Cancel() {\n DCHECK(MessageLoop::current() == ui_loop_);\n DCHECK(dialog_) << \"LoginHandler invoked without being attached\";\n CancelAuth();\n return true;\n }\n virtual bool Accept() {\n DCHECK(MessageLoop::current() == ui_loop_);\n DCHECK(dialog_) << \"LoginHandler invoked without being attached\";\n SetAuth(login_view_->GetUsername(), login_view_->GetPassword());\n return true;\n }\n virtual views::View* GetContentsView() {\n return login_view_;\n }\n\n \/\/ LoginHandler:\n virtual void SetAuth(const std::wstring& username,\n const std::wstring& password) {\n if (WasAuthHandled(true))\n return;\n\n \/\/ Tell the password manager the credentials were submitted \/ accepted.\n if (password_manager_) {\n password_form_.username_value = username;\n password_form_.password_value = password;\n password_manager_->ProvisionallySavePassword(password_form_);\n }\n\n ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::CloseContentsDeferred));\n ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::SendNotifications));\n request_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::SetAuthDeferred, username, password));\n }\n\n virtual void CancelAuth() {\n if (WasAuthHandled(true))\n return;\n\n ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::CloseContentsDeferred));\n ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::SendNotifications));\n request_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::CancelAuthDeferred));\n }\n\n virtual void OnRequestCancelled() {\n DCHECK(MessageLoop::current() == request_loop_) <<\n \"Why is OnRequestCancelled called from the UI thread?\";\n\n \/\/ Reference is no longer valid.\n request_ = NULL;\n\n \/\/ Give up on auth if the request was cancelled.\n CancelAuth();\n }\n\n private:\n\n \/\/ Calls SetAuth from the request_loop.\n void SetAuthDeferred(const std::wstring& username,\n const std::wstring& password) {\n DCHECK(MessageLoop::current() == request_loop_);\n\n if (request_) {\n request_->SetAuth(username, password);\n ResetLoginHandlerForRequest(request_);\n }\n }\n\n \/\/ Calls CancelAuth from the request_loop.\n void CancelAuthDeferred() {\n DCHECK(MessageLoop::current() == request_loop_);\n\n if (request_) {\n request_->CancelAuth();\n \/\/ Verify that CancelAuth does destroy the request via our delegate.\n DCHECK(request_ != NULL);\n ResetLoginHandlerForRequest(request_);\n }\n }\n\n \/\/ Closes the view_contents from the UI loop.\n void CloseContentsDeferred() {\n DCHECK(MessageLoop::current() == ui_loop_);\n\n \/\/ The hosting ConstrainedWindow may have been freed.\n if (dialog_)\n dialog_->CloseConstrainedWindow();\n }\n\n \/\/ Returns whether authentication had been handled (SetAuth or CancelAuth).\n \/\/ If |set_handled| is true, it will mark authentication as handled.\n bool WasAuthHandled(bool set_handled) {\n AutoLock lock(handled_auth_lock_);\n bool was_handled = handled_auth_;\n if (set_handled)\n handled_auth_ = true;\n return was_handled;\n }\n\n \/\/ Notify observers that authentication is needed or received. The automation\n \/\/ proxy uses this for testing.\n void SendNotifications() {\n DCHECK(MessageLoop::current() == ui_loop_);\n\n NotificationService* service = NotificationService::current();\n WebContents* requesting_contents = GetWebContentsForLogin();\n if (!requesting_contents)\n return;\n\n NavigationController* controller = requesting_contents->controller();\n\n if (!WasAuthHandled(false)) {\n LoginNotificationDetails details(this);\n service->Notify(NotificationType::AUTH_NEEDED,\n Source(controller),\n Details(&details));\n } else {\n service->Notify(NotificationType::AUTH_SUPPLIED,\n Source(controller),\n NotificationService::NoDetails());\n }\n }\n\n \/\/ True if we've handled auth (SetAuth or CancelAuth has been called).\n bool handled_auth_;\n Lock handled_auth_lock_;\n\n \/\/ The ConstrainedWindow that is hosting our LoginView.\n \/\/ This should only be accessed on the ui_loop_.\n ConstrainedWindow* dialog_;\n\n \/\/ The MessageLoop of the thread that the ChromeViewContents lives in.\n MessageLoop* ui_loop_;\n\n \/\/ The request that wants login data.\n \/\/ This should only be accessed on the request_loop_.\n URLRequest* request_;\n\n \/\/ The MessageLoop of the thread that the URLRequest lives in.\n MessageLoop* request_loop_;\n\n \/\/ The LoginView that contains the user's login information\n LoginView* login_view_;\n\n \/\/ The PasswordForm sent to the PasswordManager. This is so we can refer to it\n \/\/ when later notifying the password manager if the credentials were accepted\n \/\/ or rejected.\n \/\/ This should only be accessed on the ui_loop_.\n PasswordForm password_form_;\n\n \/\/ Points to the password manager owned by the TabContents requesting auth.\n \/\/ Can be null if the TabContents is not a WebContents.\n \/\/ This should only be accessed on the ui_loop_.\n PasswordManager* password_manager_;\n\n \/\/ Cached from the URLRequest, in case it goes NULL on us.\n int render_process_host_id_;\n int tab_contents_id_;\n\n DISALLOW_EVIL_CONSTRUCTORS(LoginHandlerImpl);\n};\n\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ LoginDialogTask\n\n\/\/ This task is run on the UI thread and creates a constrained window with\n\/\/ a LoginView to prompt the user. The response will be sent to LoginHandler,\n\/\/ which then routes it to the URLRequest on the I\/O thread.\nclass LoginDialogTask : public Task {\n public:\n LoginDialogTask(net::AuthChallengeInfo* auth_info, LoginHandlerImpl* handler)\n : auth_info_(auth_info), handler_(handler) {\n }\n virtual ~LoginDialogTask() {\n }\n\n void Run() {\n WebContents* parent_contents = handler_->GetWebContentsForLogin();\n if (!parent_contents) {\n \/\/ The request was probably cancelled.\n return;\n }\n\n wstring explanation = auth_info_->realm.empty() ?\n l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION_NO_REALM,\n auth_info_->host) :\n l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION,\n auth_info_->host,\n auth_info_->realm);\n LoginView* view = new LoginView(explanation);\n \/\/ Tell the password manager to look for saved passwords. There is only\n \/\/ a password manager when dealing with a WebContents type.\n if (parent_contents->type() == TAB_CONTENTS_WEB) {\n PasswordManager* password_manager =\n parent_contents->AsWebContents()->GetPasswordManager();\n \/\/ Set the model for the login view. The model (password manager) is owned\n \/\/ by the view's parent TabContents, so natural destruction order means we\n \/\/ don't have to worry about calling SetModel(NULL), because the view will\n \/\/ be deleted before the password manager.\n view->SetModel(password_manager);\n std::vector v;\n MakeInputForPasswordManager(parent_contents->GetURL(), &v);\n password_manager->PasswordFormsSeen(v);\n handler_->set_password_manager(password_manager);\n }\n\n handler_->set_login_view(view);\n ConstrainedWindow* dialog =\n parent_contents->CreateConstrainedDialog(handler_, view);\n handler_->InitWithDialog(dialog);\n }\n\n private:\n \/\/ Helper to create a PasswordForm and stuff it into a vector as input\n \/\/ for PasswordManager::PasswordFormsSeen, the hook into PasswordManager.\n void MakeInputForPasswordManager(\n const GURL& origin_url,\n std::vector* password_manager_input) {\n PasswordForm dialog_form;\n if (LowerCaseEqualsASCII(auth_info_->scheme, \"basic\")) {\n dialog_form.scheme = PasswordForm::SCHEME_BASIC;\n } else if (LowerCaseEqualsASCII(auth_info_->scheme, \"digest\")) {\n dialog_form.scheme = PasswordForm::SCHEME_DIGEST;\n } else {\n dialog_form.scheme = PasswordForm::SCHEME_OTHER;\n }\n dialog_form.origin = origin_url;\n dialog_form.signon_realm = GetSignonRealm(dialog_form.origin, *auth_info_);\n password_manager_input->push_back(dialog_form);\n \/\/ Set the password form for the handler (by copy).\n handler_->set_password_form(dialog_form);\n }\n\n \/\/ Info about who\/where\/what is asking for authentication.\n scoped_refptr auth_info_;\n\n \/\/ Where to send the authentication when obtained.\n \/\/ This is owned by the ResourceDispatcherHost that invoked us.\n LoginHandlerImpl* handler_;\n\n DISALLOW_EVIL_CONSTRUCTORS(LoginDialogTask);\n};\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Public API\n\nLoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,\n URLRequest* request,\n MessageLoop* ui_loop) {\n LoginHandlerImpl* handler = new LoginHandlerImpl(request, ui_loop);\n ui_loop->PostTask(FROM_HERE, new LoginDialogTask(auth_info, handler));\n return handler;\n}\nbustage fix - moved file\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/login_prompt.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/lock.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/password_manager\/password_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/tab_contents\/constrained_window.h\"\n#include \"chrome\/browser\/tab_contents\/navigation_controller.h\"\n#include \"chrome\/browser\/tab_contents\/tab_util.h\"\n#include \"chrome\/browser\/tab_contents\/web_contents.h\"\n#include \"chrome\/browser\/views\/login_view.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/l10n_util.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/views\/window\/dialog_delegate.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/auth.h\"\n#include \"net\/url_request\/url_request.h\"\n\nusing namespace std;\nusing views::LoginView;\n\nclass LoginHandlerImpl;\n\n\/\/ Helper to remove the ref from an URLRequest to the LoginHandler.\n\/\/ Should only be called from the IO thread, since it accesses an URLRequest.\nstatic void ResetLoginHandlerForRequest(URLRequest* request) {\n ResourceDispatcherHost::ExtraRequestInfo* info =\n ResourceDispatcherHost::ExtraInfoForRequest(request);\n if (!info)\n return;\n\n info->login_handler = NULL;\n}\n\n\/\/ Get the signon_realm under which this auth info should be stored.\n\/\/\n\/\/ The format of the signon_realm for proxy auth is:\n\/\/ proxy-host\/auth-realm\n\/\/ The format of the signon_realm for server auth is:\n\/\/ url-scheme:\/\/url-host[:url-port]\/auth-realm\n\/\/\n\/\/ Be careful when changing this function, since you could make existing\n\/\/ saved logins un-retrievable.\n\nstd::string GetSignonRealm(const GURL& url,\n const net::AuthChallengeInfo& auth_info) {\n std::string signon_realm;\n if (auth_info.is_proxy) {\n signon_realm = WideToASCII(auth_info.host);\n signon_realm.append(\"\/\");\n } else {\n \/\/ Take scheme, host, and port from the url.\n signon_realm = url.GetOrigin().spec();\n \/\/ This ends with a \"\/\".\n }\n signon_realm.append(WideToUTF8(auth_info.realm));\n return signon_realm;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ LoginHandlerImpl\n\n\/\/ This class simply forwards the authentication from the LoginView (on\n\/\/ the UI thread) to the URLRequest (on the I\/O thread).\n\/\/ This class uses ref counting to ensure that it lives until all InvokeLaters\n\/\/ have been called.\nclass LoginHandlerImpl : public LoginHandler,\n public base::RefCountedThreadSafe,\n public views::DialogDelegate {\n public:\n LoginHandlerImpl(URLRequest* request, MessageLoop* ui_loop)\n : dialog_(NULL),\n handled_auth_(false),\n request_(request),\n request_loop_(MessageLoop::current()),\n ui_loop_(ui_loop),\n password_manager_(NULL) {\n DCHECK(request_) << \"LoginHandler constructed with NULL request\";\n\n AddRef(); \/\/ matched by ReleaseLater.\n if (!tab_util::GetTabContentsID(request_, &render_process_host_id_,\n &tab_contents_id_)) {\n NOTREACHED();\n }\n }\n\n ~LoginHandlerImpl() {\n }\n\n \/\/ Initialize the UI part of the LoginHandler.\n \/\/ Scary thread safety note: This can potentially be called *after* SetAuth\n \/\/ or CancelAuth (say, if the request was cancelled before the UI thread got\n \/\/ control). However, that's OK since any UI interaction in those functions\n \/\/ will occur via an InvokeLater on the UI thread, which is guaranteed\n \/\/ to happen after this is called (since this was InvokeLater'd first).\n void InitWithDialog(ConstrainedWindow* dlg) {\n DCHECK(MessageLoop::current() == ui_loop_);\n dialog_ = dlg;\n SendNotifications();\n }\n\n \/\/ Returns the WebContents that needs authentication.\n WebContents* GetWebContentsForLogin() {\n DCHECK(MessageLoop::current() == ui_loop_);\n\n return tab_util::GetWebContentsByID(render_process_host_id_,\n tab_contents_id_);\n }\n\n void set_login_view(LoginView* login_view) {\n login_view_ = login_view;\n }\n\n void set_password_form(const PasswordForm& form) {\n password_form_ = form;\n }\n\n void set_password_manager(PasswordManager* password_manager) {\n password_manager_ = password_manager;\n }\n\n \/\/ views::DialogDelegate methods:\n virtual std::wstring GetDialogButtonLabel(DialogButton button) const {\n if (button == DIALOGBUTTON_OK)\n return l10n_util::GetString(IDS_LOGIN_DIALOG_OK_BUTTON_LABEL);\n return DialogDelegate::GetDialogButtonLabel(button);\n }\n virtual std::wstring GetWindowTitle() const {\n return l10n_util::GetString(IDS_LOGIN_DIALOG_TITLE);\n }\n virtual void WindowClosing() {\n DCHECK(MessageLoop::current() == ui_loop_);\n\n \/\/ Reference is no longer valid.\n dialog_ = NULL;\n\n if (!WasAuthHandled(true)) {\n request_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::CancelAuthDeferred));\n SendNotifications();\n }\n }\n virtual void DeleteDelegate() {\n \/\/ Delete this object once all InvokeLaters have been called.\n request_loop_->ReleaseSoon(FROM_HERE, this);\n }\n virtual bool Cancel() {\n DCHECK(MessageLoop::current() == ui_loop_);\n DCHECK(dialog_) << \"LoginHandler invoked without being attached\";\n CancelAuth();\n return true;\n }\n virtual bool Accept() {\n DCHECK(MessageLoop::current() == ui_loop_);\n DCHECK(dialog_) << \"LoginHandler invoked without being attached\";\n SetAuth(login_view_->GetUsername(), login_view_->GetPassword());\n return true;\n }\n virtual views::View* GetContentsView() {\n return login_view_;\n }\n\n \/\/ LoginHandler:\n virtual void SetAuth(const std::wstring& username,\n const std::wstring& password) {\n if (WasAuthHandled(true))\n return;\n\n \/\/ Tell the password manager the credentials were submitted \/ accepted.\n if (password_manager_) {\n password_form_.username_value = username;\n password_form_.password_value = password;\n password_manager_->ProvisionallySavePassword(password_form_);\n }\n\n ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::CloseContentsDeferred));\n ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::SendNotifications));\n request_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::SetAuthDeferred, username, password));\n }\n\n virtual void CancelAuth() {\n if (WasAuthHandled(true))\n return;\n\n ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::CloseContentsDeferred));\n ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::SendNotifications));\n request_loop_->PostTask(FROM_HERE, NewRunnableMethod(\n this, &LoginHandlerImpl::CancelAuthDeferred));\n }\n\n virtual void OnRequestCancelled() {\n DCHECK(MessageLoop::current() == request_loop_) <<\n \"Why is OnRequestCancelled called from the UI thread?\";\n\n \/\/ Reference is no longer valid.\n request_ = NULL;\n\n \/\/ Give up on auth if the request was cancelled.\n CancelAuth();\n }\n\n private:\n\n \/\/ Calls SetAuth from the request_loop.\n void SetAuthDeferred(const std::wstring& username,\n const std::wstring& password) {\n DCHECK(MessageLoop::current() == request_loop_);\n\n if (request_) {\n request_->SetAuth(username, password);\n ResetLoginHandlerForRequest(request_);\n }\n }\n\n \/\/ Calls CancelAuth from the request_loop.\n void CancelAuthDeferred() {\n DCHECK(MessageLoop::current() == request_loop_);\n\n if (request_) {\n request_->CancelAuth();\n \/\/ Verify that CancelAuth does destroy the request via our delegate.\n DCHECK(request_ != NULL);\n ResetLoginHandlerForRequest(request_);\n }\n }\n\n \/\/ Closes the view_contents from the UI loop.\n void CloseContentsDeferred() {\n DCHECK(MessageLoop::current() == ui_loop_);\n\n \/\/ The hosting ConstrainedWindow may have been freed.\n if (dialog_)\n dialog_->CloseConstrainedWindow();\n }\n\n \/\/ Returns whether authentication had been handled (SetAuth or CancelAuth).\n \/\/ If |set_handled| is true, it will mark authentication as handled.\n bool WasAuthHandled(bool set_handled) {\n AutoLock lock(handled_auth_lock_);\n bool was_handled = handled_auth_;\n if (set_handled)\n handled_auth_ = true;\n return was_handled;\n }\n\n \/\/ Notify observers that authentication is needed or received. The automation\n \/\/ proxy uses this for testing.\n void SendNotifications() {\n DCHECK(MessageLoop::current() == ui_loop_);\n\n NotificationService* service = NotificationService::current();\n WebContents* requesting_contents = GetWebContentsForLogin();\n if (!requesting_contents)\n return;\n\n NavigationController* controller = requesting_contents->controller();\n\n if (!WasAuthHandled(false)) {\n LoginNotificationDetails details(this);\n service->Notify(NotificationType::AUTH_NEEDED,\n Source(controller),\n Details(&details));\n } else {\n service->Notify(NotificationType::AUTH_SUPPLIED,\n Source(controller),\n NotificationService::NoDetails());\n }\n }\n\n \/\/ True if we've handled auth (SetAuth or CancelAuth has been called).\n bool handled_auth_;\n Lock handled_auth_lock_;\n\n \/\/ The ConstrainedWindow that is hosting our LoginView.\n \/\/ This should only be accessed on the ui_loop_.\n ConstrainedWindow* dialog_;\n\n \/\/ The MessageLoop of the thread that the ChromeViewContents lives in.\n MessageLoop* ui_loop_;\n\n \/\/ The request that wants login data.\n \/\/ This should only be accessed on the request_loop_.\n URLRequest* request_;\n\n \/\/ The MessageLoop of the thread that the URLRequest lives in.\n MessageLoop* request_loop_;\n\n \/\/ The LoginView that contains the user's login information\n LoginView* login_view_;\n\n \/\/ The PasswordForm sent to the PasswordManager. This is so we can refer to it\n \/\/ when later notifying the password manager if the credentials were accepted\n \/\/ or rejected.\n \/\/ This should only be accessed on the ui_loop_.\n PasswordForm password_form_;\n\n \/\/ Points to the password manager owned by the TabContents requesting auth.\n \/\/ Can be null if the TabContents is not a WebContents.\n \/\/ This should only be accessed on the ui_loop_.\n PasswordManager* password_manager_;\n\n \/\/ Cached from the URLRequest, in case it goes NULL on us.\n int render_process_host_id_;\n int tab_contents_id_;\n\n DISALLOW_EVIL_CONSTRUCTORS(LoginHandlerImpl);\n};\n\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ LoginDialogTask\n\n\/\/ This task is run on the UI thread and creates a constrained window with\n\/\/ a LoginView to prompt the user. The response will be sent to LoginHandler,\n\/\/ which then routes it to the URLRequest on the I\/O thread.\nclass LoginDialogTask : public Task {\n public:\n LoginDialogTask(net::AuthChallengeInfo* auth_info, LoginHandlerImpl* handler)\n : auth_info_(auth_info), handler_(handler) {\n }\n virtual ~LoginDialogTask() {\n }\n\n void Run() {\n WebContents* parent_contents = handler_->GetWebContentsForLogin();\n if (!parent_contents) {\n \/\/ The request was probably cancelled.\n return;\n }\n\n wstring explanation = auth_info_->realm.empty() ?\n l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION_NO_REALM,\n auth_info_->host) :\n l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION,\n auth_info_->host,\n auth_info_->realm);\n LoginView* view = new LoginView(explanation);\n \/\/ Tell the password manager to look for saved passwords. There is only\n \/\/ a password manager when dealing with a WebContents type.\n if (parent_contents->type() == TAB_CONTENTS_WEB) {\n PasswordManager* password_manager =\n parent_contents->AsWebContents()->GetPasswordManager();\n \/\/ Set the model for the login view. The model (password manager) is owned\n \/\/ by the view's parent TabContents, so natural destruction order means we\n \/\/ don't have to worry about calling SetModel(NULL), because the view will\n \/\/ be deleted before the password manager.\n view->SetModel(password_manager);\n std::vector v;\n MakeInputForPasswordManager(parent_contents->GetURL(), &v);\n password_manager->PasswordFormsSeen(v);\n handler_->set_password_manager(password_manager);\n }\n\n handler_->set_login_view(view);\n ConstrainedWindow* dialog =\n parent_contents->CreateConstrainedDialog(handler_, view);\n handler_->InitWithDialog(dialog);\n }\n\n private:\n \/\/ Helper to create a PasswordForm and stuff it into a vector as input\n \/\/ for PasswordManager::PasswordFormsSeen, the hook into PasswordManager.\n void MakeInputForPasswordManager(\n const GURL& origin_url,\n std::vector* password_manager_input) {\n PasswordForm dialog_form;\n if (LowerCaseEqualsASCII(auth_info_->scheme, \"basic\")) {\n dialog_form.scheme = PasswordForm::SCHEME_BASIC;\n } else if (LowerCaseEqualsASCII(auth_info_->scheme, \"digest\")) {\n dialog_form.scheme = PasswordForm::SCHEME_DIGEST;\n } else {\n dialog_form.scheme = PasswordForm::SCHEME_OTHER;\n }\n dialog_form.origin = origin_url;\n dialog_form.signon_realm = GetSignonRealm(dialog_form.origin, *auth_info_);\n password_manager_input->push_back(dialog_form);\n \/\/ Set the password form for the handler (by copy).\n handler_->set_password_form(dialog_form);\n }\n\n \/\/ Info about who\/where\/what is asking for authentication.\n scoped_refptr auth_info_;\n\n \/\/ Where to send the authentication when obtained.\n \/\/ This is owned by the ResourceDispatcherHost that invoked us.\n LoginHandlerImpl* handler_;\n\n DISALLOW_EVIL_CONSTRUCTORS(LoginDialogTask);\n};\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Public API\n\nLoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,\n URLRequest* request,\n MessageLoop* ui_loop) {\n LoginHandlerImpl* handler = new LoginHandlerImpl(request, ui_loop);\n ui_loop->PostTask(FROM_HERE, new LoginDialogTask(auth_info, handler));\n return handler;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n\n#include \"chrome\/common\/win_safe_util.h\"\n\n#include \"app\/win_util.h\"\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"base\/string_util.h\"\n\nnamespace win_util {\n\n\/\/ This function implementation is based on the attachment execution\n\/\/ services functionally deployed with IE6 or Service pack 2. This\n\/\/ functionality is exposed in the IAttachmentExecute COM interface.\n\/\/ more information at:\n\/\/ http:\/\/msdn2.microsoft.com\/en-us\/library\/ms647048.aspx\nbool SaferOpenItemViaShell(HWND hwnd, const std::wstring& window_title,\n const FilePath& full_path,\n const std::wstring& source_url) {\n ScopedComPtr attachment_services;\n HRESULT hr = attachment_services.CreateInstance(CLSID_AttachmentServices);\n if (FAILED(hr)) {\n \/\/ We don't have Attachment Execution Services, it must be a pre-XP.SP2\n \/\/ Windows installation, or the thread does not have COM initialized.\n if (hr == CO_E_NOTINITIALIZED) {\n NOTREACHED();\n return false;\n }\n return OpenItemViaShell(full_path);\n }\n\n \/\/ This GUID is associated with any 'don't ask me again' settings that the\n \/\/ user can select for different file types.\n \/\/ {2676A9A2-D919-4fee-9187-152100393AB2}\n static const GUID kClientID = { 0x2676a9a2, 0xd919, 0x4fee,\n { 0x91, 0x87, 0x15, 0x21, 0x0, 0x39, 0x3a, 0xb2 } };\n\n attachment_services->SetClientGuid(kClientID);\n\n if (!window_title.empty())\n attachment_services->SetClientTitle(window_title.c_str());\n\n \/\/ To help windows decide if the downloaded file is dangerous we can provide\n \/\/ what the documentation calls evidence. Which we provide now:\n \/\/\n \/\/ Set the file itself as evidence.\n hr = attachment_services->SetLocalPath(full_path.value().c_str());\n if (FAILED(hr))\n return false;\n \/\/ Set the origin URL as evidence.\n hr = attachment_services->SetSource(source_url.c_str());\n if (FAILED(hr))\n return false;\n\n \/\/ Now check the windows policy.\n bool do_prompt;\n hr = attachment_services->CheckPolicy();\n if (S_FALSE == hr) {\n \/\/ The user prompt is required.\n do_prompt = true;\n } else if (S_OK == hr) {\n \/\/ An S_OK means that the file is safe to open without user consent.\n do_prompt = false;\n } else {\n \/\/ It is possible that the last call returns an undocumented result\n \/\/ equal to 0x800c000e which seems to indicate that the URL failed the\n \/\/ the security check. If you proceed with the Prompt() call the\n \/\/ Shell might show a dialog that says:\n \/\/ \"windows found that this file is potentially harmful. To help protect\n \/\/ your computer, Windows has blocked access to this file.\"\n \/\/ Upon dismissal of the dialog windows will delete the file (!!).\n \/\/ So, we can 'return' here but maybe is best to let it happen to fail on\n \/\/ the safe side.\n }\n if (do_prompt) {\n ATTACHMENT_ACTION action;\n \/\/ We cannot control what the prompt says or does directly but it\n \/\/ is a pretty decent dialog; for example, if an excutable is signed it can\n \/\/ decode and show the publisher and the certificate.\n hr = attachment_services->Prompt(hwnd, ATTACHMENT_PROMPT_EXEC, &action);\n if (FAILED(hr) || (ATTACHMENT_ACTION_CANCEL == action))\n {\n \/\/ The user has declined opening the item.\n return false;\n }\n }\n return OpenItemViaShellNoZoneCheck(full_path);\n}\n\nbool SetInternetZoneIdentifier(const FilePath& full_path) {\n const DWORD kShare = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;\n std::wstring path = full_path.value() + L\":Zone.Identifier\";\n HANDLE file = CreateFile(path.c_str(), GENERIC_WRITE, kShare, NULL,\n OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if (INVALID_HANDLE_VALUE == file)\n return false;\n\n const char kIdentifier[] = \"[ZoneTransfer]\\nZoneId=3\";\n DWORD written = 0;\n BOOL result = WriteFile(file, kIdentifier, arraysize(kIdentifier), &written,\n NULL);\n BOOL flush_result = FlushFileBuffers(file);\n CloseHandle(file);\n\n if (!result || !flush_result || written != arraysize(kIdentifier)) {\n NOTREACHED();\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace win_util\nwin_safe_util: fix uninitialized variable\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n\n#include \"chrome\/common\/win_safe_util.h\"\n\n#include \"app\/win_util.h\"\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"base\/string_util.h\"\n\nnamespace win_util {\n\n\/\/ This function implementation is based on the attachment execution\n\/\/ services functionally deployed with IE6 or Service pack 2. This\n\/\/ functionality is exposed in the IAttachmentExecute COM interface.\n\/\/ more information at:\n\/\/ http:\/\/msdn2.microsoft.com\/en-us\/library\/ms647048.aspx\nbool SaferOpenItemViaShell(HWND hwnd, const std::wstring& window_title,\n const FilePath& full_path,\n const std::wstring& source_url) {\n ScopedComPtr attachment_services;\n HRESULT hr = attachment_services.CreateInstance(CLSID_AttachmentServices);\n if (FAILED(hr)) {\n \/\/ We don't have Attachment Execution Services, it must be a pre-XP.SP2\n \/\/ Windows installation, or the thread does not have COM initialized.\n if (hr == CO_E_NOTINITIALIZED) {\n NOTREACHED();\n return false;\n }\n return OpenItemViaShell(full_path);\n }\n\n \/\/ This GUID is associated with any 'don't ask me again' settings that the\n \/\/ user can select for different file types.\n \/\/ {2676A9A2-D919-4fee-9187-152100393AB2}\n static const GUID kClientID = { 0x2676a9a2, 0xd919, 0x4fee,\n { 0x91, 0x87, 0x15, 0x21, 0x0, 0x39, 0x3a, 0xb2 } };\n\n attachment_services->SetClientGuid(kClientID);\n\n if (!window_title.empty())\n attachment_services->SetClientTitle(window_title.c_str());\n\n \/\/ To help windows decide if the downloaded file is dangerous we can provide\n \/\/ what the documentation calls evidence. Which we provide now:\n \/\/\n \/\/ Set the file itself as evidence.\n hr = attachment_services->SetLocalPath(full_path.value().c_str());\n if (FAILED(hr))\n return false;\n \/\/ Set the origin URL as evidence.\n hr = attachment_services->SetSource(source_url.c_str());\n if (FAILED(hr))\n return false;\n\n \/\/ Now check the windows policy.\n if (attachment_services->CheckPolicy() != S_OK) {\n \/\/ It is possible that the above call returns an undocumented result\n \/\/ equal to 0x800c000e which seems to indicate that the URL failed the\n \/\/ the security check. If you proceed with the Prompt() call the\n \/\/ Shell might show a dialog that says:\n \/\/ \"windows found that this file is potentially harmful. To help protect\n \/\/ your computer, Windows has blocked access to this file.\"\n \/\/ Upon dismissal of the dialog windows will delete the file (!!).\n \/\/ So, we can 'return' in that case but maybe is best to let it happen to\n \/\/ fail on the safe side.\n\n ATTACHMENT_ACTION action;\n \/\/ We cannot control what the prompt says or does directly but it\n \/\/ is a pretty decent dialog; for example, if an executable is signed it can\n \/\/ decode and show the publisher and the certificate.\n hr = attachment_services->Prompt(hwnd, ATTACHMENT_PROMPT_EXEC, &action);\n if (FAILED(hr) || (ATTACHMENT_ACTION_CANCEL == action)) {\n \/\/ The user has declined opening the item.\n return false;\n }\n }\n return OpenItemViaShellNoZoneCheck(full_path);\n}\n\nbool SetInternetZoneIdentifier(const FilePath& full_path) {\n const DWORD kShare = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;\n std::wstring path = full_path.value() + L\":Zone.Identifier\";\n HANDLE file = CreateFile(path.c_str(), GENERIC_WRITE, kShare, NULL,\n OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if (INVALID_HANDLE_VALUE == file)\n return false;\n\n const char kIdentifier[] = \"[ZoneTransfer]\\nZoneId=3\";\n DWORD written = 0;\n BOOL result = WriteFile(file, kIdentifier, arraysize(kIdentifier), &written,\n NULL);\n BOOL flush_result = FlushFileBuffers(file);\n CloseHandle(file);\n\n if (!result || !flush_result || written != arraysize(kIdentifier)) {\n NOTREACHED();\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace win_util\n<|endoftext|>"} {"text":"\/*\n * Copyright © 2012 Intel Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see .\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Bitcode\/ReaderWriter.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n\n#include \"sys\/cvar.hpp\"\n#include \"src\/GBEConfig.h\"\n#include \"llvm\/llvm_gen_backend.hpp\"\n#include \"llvm-c\/Linker.h\"\n\nusing namespace llvm;\n\nSVAR(OCL_BITCODE_LIB_PATH, OCL_BITCODE_BIN);\n\nnamespace gbe\n{\n static Module* createOclBitCodeModule(LLVMContext& ctx, bool strictMath)\n {\n std::string bitCodeFiles = OCL_BITCODE_LIB_PATH;\n std::istringstream bitCodeFilePath(bitCodeFiles);\n std::string FilePath;\n bool findBC = false;\n Module* oclLib = NULL;\n SMDiagnostic Err;\n\n while (std::getline(bitCodeFilePath, FilePath, ':')) {\n if(access(FilePath.c_str(), R_OK) == 0) {\n findBC = true;\n break;\n }\n }\n assert(findBC);\n\n#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 5\n oclLib = getLazyIRFileModule(FilePath, Err, ctx);\n#else\n oclLib = getLazyIRFileModule(FilePath, Err, ctx).release();\n#endif\n if (!oclLib) {\n printf(\"Fatal Error: ocl lib can not be opened\\n\");\n return NULL;\n }\n\n if (strictMath) {\n llvm::GlobalVariable* mathFastFlag = oclLib->getGlobalVariable(\"__ocl_math_fastpath_flag\");\n assert(mathFastFlag);\n Type* intTy = IntegerType::get(ctx, 32);\n mathFastFlag->setInitializer(ConstantInt::get(intTy, 0));\n }\n\n return oclLib;\n }\n\n static bool materializedFuncCall(Module& src, Module& lib, llvm::Function &KF, std::set& MFS)\n {\n bool fromSrc = false;\n for (llvm::Function::iterator B = KF.begin(), BE = KF.end(); B != BE; B++) {\n for (BasicBlock::iterator instI = B->begin(),\n instE = B->end(); instI != instE; ++instI) {\n llvm::CallInst* call = dyn_cast(instI);\n if (!call) {\n continue;\n }\n\n if (call->getCalledFunction() &&\n call->getCalledFunction()->getIntrinsicID() != 0)\n continue;\n\n Value *Callee = call->getCalledValue();\n const std::string fnName = Callee->getName();\n\n if (!MFS.insert(fnName).second) {\n continue;\n }\n\n fromSrc = false;\n llvm::Function *newMF = lib.getFunction(fnName);\n if (!newMF) {\n newMF = src.getFunction(fnName);\n if (!newMF) {\n printf(\"Can not find the lib: %s\\n\", fnName.c_str());\n return false;\n }\n fromSrc = true;\n }\n\n std::string ErrInfo;\/\/ = \"Not Materializable\";\n if (!fromSrc && newMF->isMaterializable()) {\n#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 5\n if (newMF->Materialize(&ErrInfo)) {\n printf(\"Can not materialize the function: %s, because %s\\n\", fnName.c_str(), ErrInfo.c_str());\n return false;\n }\n#else\n if (std::error_code EC = newMF->materialize()) {\n printf(\"Can not materialize the function: %s, because %s\\n\", fnName.c_str(), EC.message().c_str());\n return false;\n }\n#endif\n }\n if (!materializedFuncCall(src, lib, *newMF, MFS))\n return false;\n\n }\n }\n\n return true;\n }\n\n\n Module* runBitCodeLinker(Module *mod, bool strictMath)\n {\n LLVMContext& ctx = mod->getContext();\n std::set materializedFuncs;\n Module* clonedLib = createOclBitCodeModule(ctx, strictMath);\n assert(clonedLib && \"Can not create the beignet bitcode\\n\");\n\n std::vector kernels;\n std::vector builtinFuncs;\n \/* Add the memset and memcpy functions here. *\/\n builtinFuncs.push_back(\"__gen_memcpy_gg\");\n builtinFuncs.push_back(\"__gen_memcpy_gp\");\n builtinFuncs.push_back(\"__gen_memcpy_gl\");\n builtinFuncs.push_back(\"__gen_memcpy_pg\");\n builtinFuncs.push_back(\"__gen_memcpy_pp\");\n builtinFuncs.push_back(\"__gen_memcpy_pl\");\n builtinFuncs.push_back(\"__gen_memcpy_lg\");\n builtinFuncs.push_back(\"__gen_memcpy_lp\");\n builtinFuncs.push_back(\"__gen_memcpy_ll\");\n builtinFuncs.push_back(\"__gen_memset_p\");\n builtinFuncs.push_back(\"__gen_memset_g\");\n builtinFuncs.push_back(\"__gen_memset_l\");\n\n builtinFuncs.push_back(\"__gen_memcpy_gg_align\");\n builtinFuncs.push_back(\"__gen_memcpy_gp_align\");\n builtinFuncs.push_back(\"__gen_memcpy_gl_align\");\n builtinFuncs.push_back(\"__gen_memcpy_pg_align\");\n builtinFuncs.push_back(\"__gen_memcpy_pp_align\");\n builtinFuncs.push_back(\"__gen_memcpy_pl_align\");\n builtinFuncs.push_back(\"__gen_memcpy_lg_align\");\n builtinFuncs.push_back(\"__gen_memcpy_lp_align\");\n builtinFuncs.push_back(\"__gen_memcpy_ll_align\");\n builtinFuncs.push_back(\"__gen_memset_p_align\");\n builtinFuncs.push_back(\"__gen_memset_g_align\");\n builtinFuncs.push_back(\"__gen_memset_l_align\");\n\n builtinFuncs.push_back(\"__gen_memcpy_pc\");\n builtinFuncs.push_back(\"__gen_memcpy_gc\");\n builtinFuncs.push_back(\"__gen_memcpy_lc\");\n\n builtinFuncs.push_back(\"__gen_memcpy_pc_align\");\n builtinFuncs.push_back(\"__gen_memcpy_gc_align\");\n builtinFuncs.push_back(\"__gen_memcpy_lc_align\");\n\n for (Module::iterator SF = mod->begin(), E = mod->end(); SF != E; ++SF) {\n if (SF->isDeclaration()) continue;\n if (!isKernelFunction(*SF)) continue;\n kernels.push_back(SF->getName().data());\n\n if (!materializedFuncCall(*mod, *clonedLib, *SF, materializedFuncs)) {\n delete clonedLib;\n return NULL;\n }\n }\n\n if (kernels.empty()) {\n printf(\"One module without kernel function!\\n\");\n delete clonedLib;\n return NULL;\n }\n\n for (auto &f : builtinFuncs) {\n const std::string fnName(f);\n if (!materializedFuncs.insert(fnName).second) {\n continue;\n }\n\n llvm::Function *newMF = clonedLib->getFunction(fnName);\n if (!newMF) {\n printf(\"Can not find the function: %s\\n\", fnName.c_str());\n delete clonedLib;\n return NULL;\n }\n std::string ErrInfo;\/\/ = \"Not Materializable\";\n if (newMF->isMaterializable()) {\n#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 5\n if (newMF->Materialize(&ErrInfo)) {\n printf(\"Can not materialize the function: %s, because %s\\n\", fnName.c_str(), ErrInfo.c_str());\n delete clonedLib;\n return NULL;\n }\n }\n#else\n if (std::error_code EC = newMF->materialize()) {\n printf(\"Can not materialize the function: %s, because %s\\n\", fnName.c_str(), EC.message().c_str();\n delete clonedLib;\n return NULL;\n }\n }\n#endif\n\n if (!materializedFuncCall(*mod, *clonedLib, *newMF, materializedFuncs)) {\n delete clonedLib;\n return NULL;\n }\n\n kernels.push_back(f);\n }\n\n \/* We use beignet's bitcode as dst because it will have a lot of\n lazy functions which will not be loaded. *\/\n char* errorMsg;\n#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 5\n if(LLVMLinkModules(wrap(clonedLib), wrap(mod), LLVMLinkerDestroySource, &errorMsg)) {\n#else\n if(LLVMLinkModules(wrap(clonedLib), wrap(mod), 0, &errorMsg)) {\n#endif\n delete clonedLib;\n printf(\"Fatal Error: link the bitcode error:\\n%s\\n\", errorMsg);\n return NULL;\n }\n\n llvm::PassManager passes;\n\n passes.add(createInternalizePass(kernels));\n passes.add(createGlobalDCEPass());\n\n passes.run(*clonedLib);\n\n return clonedLib;\n }\n\n} \/\/ end namespace\nGBE: fix build error for llvm 3.6.\/*\n * Copyright © 2012 Intel Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see .\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Bitcode\/ReaderWriter.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n\n#include \"sys\/cvar.hpp\"\n#include \"src\/GBEConfig.h\"\n#include \"llvm\/llvm_gen_backend.hpp\"\n#include \"llvm-c\/Linker.h\"\n\nusing namespace llvm;\n\nSVAR(OCL_BITCODE_LIB_PATH, OCL_BITCODE_BIN);\n\nnamespace gbe\n{\n static Module* createOclBitCodeModule(LLVMContext& ctx, bool strictMath)\n {\n std::string bitCodeFiles = OCL_BITCODE_LIB_PATH;\n std::istringstream bitCodeFilePath(bitCodeFiles);\n std::string FilePath;\n bool findBC = false;\n Module* oclLib = NULL;\n SMDiagnostic Err;\n\n while (std::getline(bitCodeFilePath, FilePath, ':')) {\n if(access(FilePath.c_str(), R_OK) == 0) {\n findBC = true;\n break;\n }\n }\n assert(findBC);\n\n#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 5\n oclLib = getLazyIRFileModule(FilePath, Err, ctx);\n#else\n oclLib = getLazyIRFileModule(FilePath, Err, ctx).release();\n#endif\n if (!oclLib) {\n printf(\"Fatal Error: ocl lib can not be opened\\n\");\n return NULL;\n }\n\n if (strictMath) {\n llvm::GlobalVariable* mathFastFlag = oclLib->getGlobalVariable(\"__ocl_math_fastpath_flag\");\n assert(mathFastFlag);\n Type* intTy = IntegerType::get(ctx, 32);\n mathFastFlag->setInitializer(ConstantInt::get(intTy, 0));\n }\n\n return oclLib;\n }\n\n static bool materializedFuncCall(Module& src, Module& lib, llvm::Function &KF, std::set& MFS)\n {\n bool fromSrc = false;\n for (llvm::Function::iterator B = KF.begin(), BE = KF.end(); B != BE; B++) {\n for (BasicBlock::iterator instI = B->begin(),\n instE = B->end(); instI != instE; ++instI) {\n llvm::CallInst* call = dyn_cast(instI);\n if (!call) {\n continue;\n }\n\n if (call->getCalledFunction() &&\n call->getCalledFunction()->getIntrinsicID() != 0)\n continue;\n\n Value *Callee = call->getCalledValue();\n const std::string fnName = Callee->getName();\n\n if (!MFS.insert(fnName).second) {\n continue;\n }\n\n fromSrc = false;\n llvm::Function *newMF = lib.getFunction(fnName);\n if (!newMF) {\n newMF = src.getFunction(fnName);\n if (!newMF) {\n printf(\"Can not find the lib: %s\\n\", fnName.c_str());\n return false;\n }\n fromSrc = true;\n }\n\n std::string ErrInfo;\/\/ = \"Not Materializable\";\n if (!fromSrc && newMF->isMaterializable()) {\n#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 5\n if (newMF->Materialize(&ErrInfo)) {\n printf(\"Can not materialize the function: %s, because %s\\n\", fnName.c_str(), ErrInfo.c_str());\n return false;\n }\n#else\n if (std::error_code EC = newMF->materialize()) {\n printf(\"Can not materialize the function: %s, because %s\\n\", fnName.c_str(), EC.message().c_str());\n return false;\n }\n#endif\n }\n if (!materializedFuncCall(src, lib, *newMF, MFS))\n return false;\n\n }\n }\n\n return true;\n }\n\n\n Module* runBitCodeLinker(Module *mod, bool strictMath)\n {\n LLVMContext& ctx = mod->getContext();\n std::set materializedFuncs;\n Module* clonedLib = createOclBitCodeModule(ctx, strictMath);\n assert(clonedLib && \"Can not create the beignet bitcode\\n\");\n\n std::vector kernels;\n std::vector builtinFuncs;\n \/* Add the memset and memcpy functions here. *\/\n builtinFuncs.push_back(\"__gen_memcpy_gg\");\n builtinFuncs.push_back(\"__gen_memcpy_gp\");\n builtinFuncs.push_back(\"__gen_memcpy_gl\");\n builtinFuncs.push_back(\"__gen_memcpy_pg\");\n builtinFuncs.push_back(\"__gen_memcpy_pp\");\n builtinFuncs.push_back(\"__gen_memcpy_pl\");\n builtinFuncs.push_back(\"__gen_memcpy_lg\");\n builtinFuncs.push_back(\"__gen_memcpy_lp\");\n builtinFuncs.push_back(\"__gen_memcpy_ll\");\n builtinFuncs.push_back(\"__gen_memset_p\");\n builtinFuncs.push_back(\"__gen_memset_g\");\n builtinFuncs.push_back(\"__gen_memset_l\");\n\n builtinFuncs.push_back(\"__gen_memcpy_gg_align\");\n builtinFuncs.push_back(\"__gen_memcpy_gp_align\");\n builtinFuncs.push_back(\"__gen_memcpy_gl_align\");\n builtinFuncs.push_back(\"__gen_memcpy_pg_align\");\n builtinFuncs.push_back(\"__gen_memcpy_pp_align\");\n builtinFuncs.push_back(\"__gen_memcpy_pl_align\");\n builtinFuncs.push_back(\"__gen_memcpy_lg_align\");\n builtinFuncs.push_back(\"__gen_memcpy_lp_align\");\n builtinFuncs.push_back(\"__gen_memcpy_ll_align\");\n builtinFuncs.push_back(\"__gen_memset_p_align\");\n builtinFuncs.push_back(\"__gen_memset_g_align\");\n builtinFuncs.push_back(\"__gen_memset_l_align\");\n\n builtinFuncs.push_back(\"__gen_memcpy_pc\");\n builtinFuncs.push_back(\"__gen_memcpy_gc\");\n builtinFuncs.push_back(\"__gen_memcpy_lc\");\n\n builtinFuncs.push_back(\"__gen_memcpy_pc_align\");\n builtinFuncs.push_back(\"__gen_memcpy_gc_align\");\n builtinFuncs.push_back(\"__gen_memcpy_lc_align\");\n\n for (Module::iterator SF = mod->begin(), E = mod->end(); SF != E; ++SF) {\n if (SF->isDeclaration()) continue;\n if (!isKernelFunction(*SF)) continue;\n kernels.push_back(SF->getName().data());\n\n if (!materializedFuncCall(*mod, *clonedLib, *SF, materializedFuncs)) {\n delete clonedLib;\n return NULL;\n }\n }\n\n if (kernels.empty()) {\n printf(\"One module without kernel function!\\n\");\n delete clonedLib;\n return NULL;\n }\n\n for (auto &f : builtinFuncs) {\n const std::string fnName(f);\n if (!materializedFuncs.insert(fnName).second) {\n continue;\n }\n\n llvm::Function *newMF = clonedLib->getFunction(fnName);\n if (!newMF) {\n printf(\"Can not find the function: %s\\n\", fnName.c_str());\n delete clonedLib;\n return NULL;\n }\n std::string ErrInfo;\/\/ = \"Not Materializable\";\n if (newMF->isMaterializable()) {\n#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 5\n if (newMF->Materialize(&ErrInfo)) {\n printf(\"Can not materialize the function: %s, because %s\\n\", fnName.c_str(), ErrInfo.c_str());\n delete clonedLib;\n return NULL;\n }\n }\n#else\n if (std::error_code EC = newMF->materialize()) {\n printf(\"Can not materialize the function: %s, because %s\\n\", fnName.c_str(), EC.message().c_str());\n delete clonedLib;\n return NULL;\n }\n }\n#endif\n\n if (!materializedFuncCall(*mod, *clonedLib, *newMF, materializedFuncs)) {\n delete clonedLib;\n return NULL;\n }\n\n kernels.push_back(f);\n }\n\n \/* We use beignet's bitcode as dst because it will have a lot of\n lazy functions which will not be loaded. *\/\n char* errorMsg;\n#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 5\n if(LLVMLinkModules(wrap(clonedLib), wrap(mod), LLVMLinkerDestroySource, &errorMsg)) {\n#else\n if(LLVMLinkModules(wrap(clonedLib), wrap(mod), 0, &errorMsg)) {\n#endif\n delete clonedLib;\n printf(\"Fatal Error: link the bitcode error:\\n%s\\n\", errorMsg);\n return NULL;\n }\n\n llvm::PassManager passes;\n\n passes.add(createInternalizePass(kernels));\n passes.add(createGlobalDCEPass());\n\n passes.run(*clonedLib);\n\n return clonedLib;\n }\n\n} \/\/ end namespace\n<|endoftext|>"} {"text":"OBJ_LOADER_DEMO: Allow TiledCull to show all the gbuffers<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nclass MoveGroupInterface {\n moveit::planning_interface::MoveGroup move_group_;\n\n tf2_ros::Buffer buffer_;\n tf2_ros::TransformListener listener_;\n\n geometry_msgs::Pose tomapo_;\n std::vector waypoints_;\n\n static constexpr double eef_length_ {0.3}; \/\/ TODO\n static constexpr double eef_step_ {0.10};\n\n static constexpr double abs_rail_length_ {5.0};\n double sign_;\n\npublic:\n MoveGroupInterface(const std::string& group_name, const double& joint_tolerance)\n : move_group_ {group_name},\n buffer_ {},\n listener_ {buffer_},\n tomapo_ {},\n waypoints_ {},\n sign_ {1.0}\n {\n move_group_.allowReplanning(true);\n move_group_.setGoalJointTolerance(joint_tolerance);\n move_group_.setPlanningTime(5.0);\n }\n\n bool queryTargetExistence()\n {\n try {\n geometry_msgs::TransformStamped transform_stamped_ {buffer_.lookupTransform(\"rail\", \"tomato\", ros::Time(0), ros::Duration(1.0))};\n tomapo_.position.x = transform_stamped_.transform.translation.x;\n tomapo_.position.y = transform_stamped_.transform.translation.y;\n tomapo_.position.z = transform_stamped_.transform.translation.z;\n tomapo_.orientation.x = 0;\n tomapo_.orientation.y = 0;\n tomapo_.orientation.z = 0;\n tomapo_.orientation.w = 1.0;\n return true;\n } catch (const tf2::TransformException& ex) {\n ROS_INFO_STREAM(ex.what());\n return false;\n }\n }\n\n bool startSequence()\n {\n waypoints_.clear();\n\n geometry_msgs::Pose pose1 {tomapo_};\n pose1.position.x -= eef_length_;\n \/\/ waypoints_.push_back(pose1);\n move_group_.setPoseTarget(pose1);\n\n moveit::planning_interface::MoveGroup::Plan plan;\n move_group_.plan(plan);\n if (!move_group_.execute(plan)) return false;\n\n geometry_msgs::Pose pose2 {tomapo_};\n waypoints_.push_back(pose2);\n\n geometry_msgs::Pose pose3 {tomapo_};\n pose3.orientation = tf::createQuaternionMsgFromRollPitchYaw(1.0, 0, 0);\n waypoints_.push_back(pose3);\n\n geometry_msgs::Pose pose4 {tomapo_};\n pose4.position.x -= eef_length_;\n waypoints_.push_back(pose4);\n\n moveit_msgs::RobotTrajectory trajectory_msgs_;\n move_group_.computeCartesianPath(waypoints_, eef_step_, 0.0, trajectory_msgs_);\n\n robot_trajectory::RobotTrajectory robot_trajectory_ {move_group_.getCurrentState()->getRobotModel(), move_group_.getName()};\n robot_trajectory_.setRobotTrajectoryMsg(*move_group_.getCurrentState(), trajectory_msgs_);\n\n trajectory_processing::IterativeParabolicTimeParameterization iptp;\n iptp.computeTimeStamps(robot_trajectory_);\n\n robot_trajectory_.getRobotTrajectoryMsg(trajectory_msgs_);\n\n moveit::planning_interface::MoveGroup::Plan motion_plan_;\n motion_plan_.trajectory_ = trajectory_msgs_;\n\n return move_group_.execute(motion_plan_);\n }\n\n bool shift()\n {\n double tmp;\n\n try {\n geometry_msgs::TransformStamped transform_stamped {buffer_.lookupTransform(\"rail\", \"shaft\", ros::Time(0), ros::Duration(1.0))};\n tmp = transform_stamped.transform.translation.y;\n if (tmp > (abs_rail_length_ - 1.0)) sign_ = -1.0;\n else if (tmp < -(abs_rail_length_ - 1.0)) sign_ = 1.0;\n } catch (const tf2::TransformException& ex) {\n ROS_INFO_STREAM(ex.what());\n return false;\n }\n\n \/\/ auto named_target_values = move_group_.getNamedTargetValues(\"init\");\n \/\/ named_target_values[\"rail_to_shaft_joint\"] += (sign_ * 1.0);\n \/\/ move_group_.setJointValueTarget(named_target_values);\n\n \/\/ move_group_.setNamedTarget(\"init\");\n\n std::vector joint_values = move_group_.getCurrentJointValues();\n \/\/ auto joint_model_group = move_group_.getCurrentState()->getRobotModel()->getJointModelGroup(move_group_.getName());\n \/\/ move_group_.getCurrentState()->copyJointGroupPositions(joint_model_group, joint_values);\n\n \/\/ joint_values[0] += sign_ * 1.0;\n \/\/ joint_values[1] = -0.3927;\n joint_values[1] = 0;\n joint_values[2] = -0.7854;\n joint_values[3] = 1.5707;\n joint_values[4] = -0.7854;\n joint_values[5] = 0;\n\n move_group_.setJointValueTarget(joint_values);\n moveit::planning_interface::MoveGroup::Plan plan;\n move_group_.plan(plan);\n\n move_group_.execute(plan);\n\n joint_values[0] += sign_ * 1.0;\n \/\/ joint_values[1] = -0.3927;\n joint_values[1] = 0;\n joint_values[2] = -0.7854;\n joint_values[3] = 1.5707;\n joint_values[4] = -0.7854;\n joint_values[5] = 0;\n\n move_group_.setJointValueTarget(joint_values);\n \/\/ moveit::planning_interface::MoveGroup::Plan plan;\n move_group_.plan(plan);\n\n return move_group_.execute(plan);\n }\n};\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"arcsys2_move_group_interface_node\");\n ros::NodeHandle node_handle {\"~\"};\n\n ros::AsyncSpinner spinner {1};\n spinner.start();\n\n MoveGroupInterface interface {\"arcsys2\", node_handle.param(\"joint_tolerance\", 0.1)};\n\n while (ros::ok()) {\n while (!interface.queryTargetExistence()) interface.shift();\n interface.startSequence();\n }\n\n spinner.stop();\n\n return 0;\n}\nComment-out unneeded code#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nclass MoveGroupInterface {\n moveit::planning_interface::MoveGroup move_group_;\n\n tf2_ros::Buffer buffer_;\n tf2_ros::TransformListener listener_;\n\n geometry_msgs::Pose tomapo_;\n std::vector waypoints_;\n\n static constexpr double eef_length_ {0.3}; \/\/ TODO\n static constexpr double eef_step_ {0.10};\n\n static constexpr double abs_rail_length_ {5.0};\n double sign_;\n\npublic:\n MoveGroupInterface(const std::string& group_name, const double& joint_tolerance)\n : move_group_ {group_name},\n buffer_ {},\n listener_ {buffer_},\n tomapo_ {},\n waypoints_ {},\n sign_ {1.0}\n {\n move_group_.allowReplanning(true);\n move_group_.setGoalJointTolerance(joint_tolerance);\n move_group_.setPlanningTime(5.0);\n }\n\n bool queryTargetExistence()\n {\n try {\n geometry_msgs::TransformStamped transform_stamped_ {buffer_.lookupTransform(\"rail\", \"tomato\", ros::Time(0), ros::Duration(1.0))};\n tomapo_.position.x = transform_stamped_.transform.translation.x;\n tomapo_.position.y = transform_stamped_.transform.translation.y;\n tomapo_.position.z = transform_stamped_.transform.translation.z;\n tomapo_.orientation.x = 0;\n tomapo_.orientation.y = 0;\n tomapo_.orientation.z = 0;\n tomapo_.orientation.w = 1.0;\n return true;\n } catch (const tf2::TransformException& ex) {\n ROS_INFO_STREAM(ex.what());\n return false;\n }\n }\n\n bool startSequence()\n {\n waypoints_.clear();\n\n geometry_msgs::Pose pose1 {tomapo_};\n pose1.position.x -= eef_length_;\n \/\/ waypoints_.push_back(pose1);\n move_group_.setPoseTarget(pose1);\n\n moveit::planning_interface::MoveGroup::Plan plan;\n move_group_.plan(plan);\n if (!move_group_.execute(plan)) return false;\n\n geometry_msgs::Pose pose2 {tomapo_};\n waypoints_.push_back(pose2);\n\n geometry_msgs::Pose pose3 {tomapo_};\n pose3.orientation = tf::createQuaternionMsgFromRollPitchYaw(1.0, 0, 0);\n waypoints_.push_back(pose3);\n\n geometry_msgs::Pose pose4 {tomapo_};\n pose4.position.x -= eef_length_;\n waypoints_.push_back(pose4);\n\n moveit_msgs::RobotTrajectory trajectory_msgs_;\n move_group_.computeCartesianPath(waypoints_, eef_step_, 0.0, trajectory_msgs_);\n\n robot_trajectory::RobotTrajectory robot_trajectory_ {move_group_.getCurrentState()->getRobotModel(), move_group_.getName()};\n robot_trajectory_.setRobotTrajectoryMsg(*move_group_.getCurrentState(), trajectory_msgs_);\n\n trajectory_processing::IterativeParabolicTimeParameterization iptp;\n iptp.computeTimeStamps(robot_trajectory_);\n\n robot_trajectory_.getRobotTrajectoryMsg(trajectory_msgs_);\n\n moveit::planning_interface::MoveGroup::Plan motion_plan_;\n motion_plan_.trajectory_ = trajectory_msgs_;\n\n return move_group_.execute(motion_plan_);\n }\n\n bool shift()\n {\n double tmp;\n\n try {\n geometry_msgs::TransformStamped transform_stamped {buffer_.lookupTransform(\"rail\", \"shaft\", ros::Time(0), ros::Duration(1.0))};\n tmp = transform_stamped.transform.translation.y;\n if (tmp > (abs_rail_length_ - 1.0)) sign_ = -1.0;\n else if (tmp < -(abs_rail_length_ - 1.0)) sign_ = 1.0;\n } catch (const tf2::TransformException& ex) {\n ROS_INFO_STREAM(ex.what());\n return false;\n }\n\n \/\/ auto named_target_values = move_group_.getNamedTargetValues(\"init\");\n \/\/ named_target_values[\"rail_to_shaft_joint\"] += (sign_ * 1.0);\n \/\/ move_group_.setJointValueTarget(named_target_values);\n\n \/\/ move_group_.setNamedTarget(\"init\");\n\n std::vector joint_values {move_group_.getCurrentJointValues()};\n\n \/\/ joint_values[0] += sign_ * 1.0;\n \/\/ joint_values[1] = -0.3927;\n \/\/ joint_values[1] = 0;\n joint_values[2] = -0.7854;\n joint_values[3] = 1.5707;\n joint_values[4] = -0.7854;\n joint_values[5] = 0;\n\n move_group_.setJointValueTarget(joint_values);\n moveit::planning_interface::MoveGroup::Plan plan;\n move_group_.plan(plan);\n\n move_group_.execute(plan);\n\n joint_values[0] += sign_ * 1.0;\n \/\/ joint_values[1] = -0.3927;\n \/\/ joint_values[1] = 0;\n \/\/ joint_values[2] = -0.7854;\n \/\/ joint_values[3] = 1.5707;\n \/\/ joint_values[4] = -0.7854;\n \/\/ joint_values[5] = 0;\n\n move_group_.setJointValueTarget(joint_values);\n \/\/ moveit::planning_interface::MoveGroup::Plan plan;\n move_group_.plan(plan);\n\n return move_group_.execute(plan);\n }\n};\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"arcsys2_move_group_interface_node\");\n ros::NodeHandle node_handle {\"~\"};\n\n ros::AsyncSpinner spinner {1};\n spinner.start();\n\n MoveGroupInterface interface {\"arcsys2\", node_handle.param(\"joint_tolerance\", 0.1)};\n\n while (ros::ok()) {\n while (!interface.queryTargetExistence()) interface.shift();\n interface.startSequence();\n }\n\n spinner.stop();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2022 ASMlover. 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 ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \"optick\/optick.h\"\n#include \"..\/common\/common.hh\"\n#include \"..\/common\/python_helper.hh\"\n\nclass OptickProfiler final : public common::Singleton {\npublic:\n inline void startup(short listen_port = 8099) noexcept {\n Optick::SetDefaultPort(listen_port);\n }\n\n inline void push_event(const std::string& funcname, const std::string& filename, int lineno) noexcept {\n Optick::EventDescription* desc = Optick::CreateDescription(funcname.c_str(), filename.c_str(), lineno);\n if (desc != nullptr)\n desc->color = static_cast(Optick::Color::GoldenRod);\n Optick::Event::Push(*desc);\n }\n\n inline void pop_event() noexcept { Optick::Event::Pop(); }\n inline void frame_event() noexcept { OPTICK_FRAME(\"Optick.Python\"); }\n};\n\nstatic int _pprofile_tracefunc(PyObject* obj, PyFrameObject* frame, int what, PyObject* arg) {\n switch (what) {\n case PyTrace_CALL:\n {\n PyCodeObject* funccode = frame->f_code;\n auto [funcname, filename] = python_helper::get_from_call(funccode);\n OptickProfiler::get_instance().push_event(funcname, filename, funccode->co_firstlineno);\n } break;\n case PyTrace_C_CALL:\n if (PyCFunction_Check(arg)) {\n PyCFunctionObject* fn = reinterpret_cast(arg);\n auto [funcname, filename] = python_helper::get_from_ccall(fn);\n OptickProfiler::get_instance().push_event(funcname, filename, 0);\n } break;\n case PyTrace_RETURN:\n case PyTrace_C_RETURN:\n OptickProfiler::get_instance().pop_event();\n break;\n case PyTrace_C_EXCEPTION:\n if (PyCFunction_Check(arg))\n OptickProfiler::get_instance().pop_event();\n break;\n default: break;\n }\n return 0;\n}\n\nstatic PyObject* _pprofile_startup(PyObject* obj, PyObject* args, PyObject* kwds) {\n (void)obj, (void)args;\n\n static char* kwdslist[] = {(char*)\"port\", nullptr};\n\n int listen_port = 8099;\n if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|i:startup\", kwdslist, &listen_port))\n return nullptr;\n\n OptickProfiler::get_instance().startup(static_cast(listen_port));\n Py_RETURN_NONE;\n}\n\nstatic PyObject* _pprofile_enable(PyObject* obj, PyObject* args) {\n (void)obj, (void)args;\n\n PyEval_SetProfile(_pprofile_tracefunc, nullptr);\n Py_RETURN_NONE;\n}\n\nstatic PyObject* _pprofile_disable(PyObject* obj, PyObject* args) {\n (void)obj, (void)args;\n\n PyEval_SetProfile(nullptr, nullptr);\n Py_RETURN_NONE;\n}\n\nstatic PyObject* _pprofile_frame(PyObject* obj, PyObject* args) {\n (void)obj, (void)args;\n\n OptickProfiler::get_instance().frame_event();\n Py_RETURN_NONE;\n}\n\nPyMODINIT_FUNC PyInit_cpprofile() {\n static PyMethodDef _pprofile_methods[] = {\n {\"startup\", (PyCFunction)_pprofile_startup, METH_VARARGS | METH_KEYWORDS, \"cpprofile.startup(port=8099) -> None\"},\n {\"enable\", _pprofile_enable, METH_NOARGS, \"cpprofile.enable() -> None\"},\n {\"disable\", _pprofile_disable, METH_NOARGS, \"cpprofile.disable() -> None\"},\n {\"frame\", _pprofile_frame, METH_NOARGS, \"cpprofile.frame() -> None\"},\n {nullptr},\n };\n static PyModuleDef _pprofile_module = {\n PyModuleDef_HEAD_INIT,\n \"cpprofile\", \/\/ m_name\n \"CXX profile with Optick binding\", \/\/ m_doc\n -1, \/\/ m_size\n _pprofile_methods, \/\/ m_methods\n nullptr, \/\/ m_reload\n nullptr, \/\/ m_traverse\n nullptr, \/\/ m_clear\n nullptr, \/\/ m_free\n };\n\n return PyModule_Create(&_pprofile_module);\n}\n:construction: chore(profile): updated the implementation of profile with optick binding\/\/ Copyright (c) 2022 ASMlover. 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 ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \"optick\/optick.h\"\n#include \"..\/common\/common.hh\"\n#include \"..\/common\/python_helper.hh\"\n\nclass OptickProfiler final : public common::Singleton {\npublic:\n inline void startup(short listen_port = 8099) noexcept {\n Optick::SetDefaultPort(listen_port);\n }\n\n inline void push_event(const std::string& funcname, const std::string& filename, int lineno) noexcept {\n Optick::EventDescription* desc = Optick::CreateDescription(funcname.c_str(), filename.c_str(), lineno);\n if (desc != nullptr)\n desc->color = static_cast(Optick::Color::GoldenRod);\n Optick::Event::Push(*desc);\n }\n\n inline void pop_event() noexcept { Optick::Event::Pop(); }\n inline void frame_event() noexcept { OPTICK_FRAME(\"Optick.Python\"); }\n};\n\nstatic int _pprofile_tracefunc(PyObject* obj, PyFrameObject* frame, int what, PyObject* arg) {\n switch (what) {\n case PyTrace_CALL:\n {\n PyCodeObject* funccode = frame->f_code;\n auto [funcname, filename] = python_helper::get_from_call(funccode);\n OptickProfiler::get_instance().push_event(funcname, filename, funccode->co_firstlineno);\n } break;\n case PyTrace_C_CALL:\n if (PyCFunction_Check(arg)) {\n PyCFunctionObject* fn = reinterpret_cast(arg);\n auto [funcname, filename] = python_helper::get_from_ccall(fn);\n OptickProfiler::get_instance().push_event(funcname, filename, 0);\n } break;\n case PyTrace_RETURN:\n case PyTrace_C_RETURN:\n OptickProfiler::get_instance().pop_event();\n break;\n case PyTrace_C_EXCEPTION:\n if (PyCFunction_Check(arg))\n OptickProfiler::get_instance().pop_event();\n break;\n default: break;\n }\n return 0;\n}\n\nstatic PyObject* _pprofile_startup(PyObject* obj, PyObject* args, PyObject* kwds) {\n (void)obj;\n\n static char* kwdslist[] = {(char*)\"port\", nullptr};\n\n int listen_port = 8099;\n if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|i:startup\", kwdslist, &listen_port))\n return nullptr;\n\n OptickProfiler::get_instance().startup(static_cast(listen_port));\n Py_RETURN_NONE;\n}\n\nstatic PyObject* _pprofile_enable(PyObject* obj, PyObject* args) {\n (void)obj, (void)args;\n\n PyEval_SetProfile(_pprofile_tracefunc, nullptr);\n Py_RETURN_NONE;\n}\n\nstatic PyObject* _pprofile_disable(PyObject* obj, PyObject* args) {\n (void)obj, (void)args;\n\n PyEval_SetProfile(nullptr, nullptr);\n Py_RETURN_NONE;\n}\n\nstatic PyObject* _pprofile_frame(PyObject* obj, PyObject* args) {\n (void)obj, (void)args;\n\n OptickProfiler::get_instance().frame_event();\n Py_RETURN_NONE;\n}\n\nPyMODINIT_FUNC PyInit_cpprofile() {\n static PyMethodDef _pprofile_methods[] = {\n {\"startup\", (PyCFunction)_pprofile_startup, METH_VARARGS | METH_KEYWORDS, \"cpprofile.startup(port: int = 8099) -> None\"},\n {\"enable\", _pprofile_enable, METH_NOARGS, \"cpprofile.enable() -> None\"},\n {\"disable\", _pprofile_disable, METH_NOARGS, \"cpprofile.disable() -> None\"},\n {\"frame\", _pprofile_frame, METH_NOARGS, \"cpprofile.frame() -> None\"},\n {nullptr},\n };\n static PyModuleDef _pprofile_module = {\n PyModuleDef_HEAD_INIT,\n \"cpprofile\", \/\/ m_name\n \"CXX profile with Optick binding\", \/\/ m_doc\n -1, \/\/ m_size\n _pprofile_methods, \/\/ m_methods\n nullptr, \/\/ m_reload\n nullptr, \/\/ m_traverse\n nullptr, \/\/ m_clear\n nullptr, \/\/ m_free\n };\n\n return PyModule_Create(&_pprofile_module);\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2017, EPL-Vizards\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 EPL-Vizards 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 COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n * ANY 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 EPL-Vizards 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 * \\file DefaultPluginEditor.cpp\r\n *\/\r\n\r\n#include \"DefaultPluginEditor.hpp\"\r\n\r\nDefaultPluginEditor::DefaultPluginEditor(PluginEditorWidget *parent) : PluginEditorBase(parent) {\r\n layout = new QGridLayout(this);\r\n}\r\n\r\nDefaultPluginEditor::~DefaultPluginEditor() {}\r\n\r\nvoid DefaultPluginEditor::createWidget() {\r\n if (!widget) {\r\n \/\/ The widget does not yet exist, create a new one\r\n widget = new QPlainTextEdit(this);\r\n layout->addWidget(widget);\r\n connect(widget->document(), SIGNAL(modificationChanged(bool)), this, SLOT(modified()));\r\n }\r\n\r\n widget->document()->setPlainText(contents[current]);\r\n\r\n \/\/ Check if the file was dirty\r\n if (!dirtyFiles.contains(current)) {\r\n widget->document()->setModified(false); \/\/ Setting the text of the editor modifies it\r\n }\r\n}\r\n\r\nvoid DefaultPluginEditor::updateStatusBar(bool enabled) { (void)enabled; }\r\n\r\nvoid DefaultPluginEditor::openConfig() {\r\n QMessageBox::information(0, \"Info\", tr(\"There is currently no configuration for this editor\"));\r\n}\r\n\r\nvoid DefaultPluginEditor::selectDocument(QString plugin) {\r\n if (widget) {\r\n \/\/ Check if the file is dirty\r\n if (widget->document()->isModified() && !dirtyFiles.contains(current)) {\r\n dirtyFiles.append(current);\r\n contents[current] = widget->document()->toPlainText(); \/\/ Also stash the changes\r\n }\r\n }\r\n current = plugin;\r\n createWidget();\r\n}\r\n\r\nvoid DefaultPluginEditor::closeDocument(QString name) {\r\n \/\/ Only try to close if the editor is open\r\n if (!widget)\r\n return;\r\n\r\n if (dirtyFiles.contains(name)) {\r\n \/\/ TODO Add notification to make sure the user keeps his changes\r\n\r\n dirtyFiles.removeOne(name);\r\n }\r\n\r\n files.remove(name);\r\n contents.remove(name);\r\n\r\n current = QString();\r\n layout->removeWidget(widget);\r\n delete widget;\r\n widget = nullptr;\r\n}\r\n\r\nvoid DefaultPluginEditor::openDocument(QUrl file) {\r\n QFileInfo fileInfo(file.toLocalFile());\r\n QString fileName;\r\n QString filePath;\r\n\r\n if (fileInfo.exists() && fileInfo.isFile()) {\r\n fileName = fileInfo.fileName();\r\n filePath = fileInfo.filePath();\r\n\r\n files.insert(fileName, filePath);\r\n } else {\r\n QMessageBox::critical(0, \"Error\", tr(\"Could not open file '%1'.\").arg(filePath));\r\n return;\r\n }\r\n\r\n QFile f(filePath);\r\n\r\n if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {\r\n QMessageBox::critical(0, \"Error\", tr(\"Could not open file '%1'.\").arg(filePath));\r\n return;\r\n }\r\n\r\n QTextStream in(&f);\r\n\r\n contents.insert(fileName, in.readAll());\r\n current = fileName;\r\n\r\n createWidget();\r\n}\r\n\r\nvoid DefaultPluginEditor::cleanUp() {\r\n QMessageBox msg(this);\r\n QPushButton *saveButton = msg.addButton(\"Save\", QMessageBox::ActionRole);\r\n QPushButton *saveAllButton = msg.addButton(\"Save All\", QMessageBox::ActionRole);\r\n QPushButton *discardButton = msg.addButton(\"Discard\", QMessageBox::ActionRole);\r\n QPushButton *discardAllButton = msg.addButton(\"Discard All\", QMessageBox::ActionRole);\r\n\r\n\r\n msg.setInformativeText(\"Would you like to save them?\");\r\n msg.setDefaultButton(saveAllButton);\r\n\r\n bool saveAll = false;\r\n\r\n \/\/ Since dirty files are only acknowledged when \"stashing them\", check if the current file is dirty\r\n if (widget && !dirtyFiles.contains(current) && widget->document()->isModified()) {\r\n dirtyFiles.append(current);\r\n }\r\n\r\n QList list = dirtyFiles;\r\n\r\n for (QString file : list) {\r\n if (saveAll) {\r\n current = file;\r\n save();\r\n continue;\r\n }\r\n\r\n msg.setText(\"The file '\" + file + \"' has unsaved changes.\");\r\n\r\n msg.exec();\r\n\r\n QPushButton *clicked = dynamic_cast(msg.clickedButton());\r\n\r\n if (clicked == saveButton) {\r\n \/\/ Save the changes to this document\r\n current = file;\r\n save();\r\n continue;\r\n } else if (clicked == saveAllButton) {\r\n \/\/ Save the changes to this document and remember the choice\r\n current = file;\r\n save();\r\n saveAll = true;\r\n continue;\r\n } else if (clicked == discardButton) {\r\n \/\/ Discard changes for current document\r\n continue;\r\n } else if (clicked == discardAllButton) {\r\n \/\/ Discard all changes\r\n break;\r\n }\r\n }\r\n\r\n QMap savedFiles;\r\n\r\n \/\/ Destroy all documents and add them to the map of saved plugins\r\n for (QString file : files.keys()) {\r\n QString localFile = files[file];\r\n\r\n if (!dirtyFiles.contains(file)) {\r\n if (QFile::exists(localFile)) {\r\n savedFiles.insert(file, localFile);\r\n }\r\n }\r\n }\r\n\r\n\r\n emit pluginsSaved(savedFiles);\r\n files.clear();\r\n contents.clear();\r\n dirtyFiles.clear();\r\n current = QString();\r\n layout->removeWidget(widget);\r\n delete widget;\r\n widget = nullptr;\r\n newCounter = 1;\r\n}\r\n\r\nvoid DefaultPluginEditor::writeToFile(QString filePath) {\r\n\r\n QFile file(filePath);\r\n\r\n contents[current] = widget->document()->toPlainText();\r\n\r\n \/\/ Try to open the file write-only, truncating any previous contents\r\n if (file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {\r\n QTextStream out(&file);\r\n\r\n \/\/ Write the current editors content to the file\r\n out << contents[current] << \"\\n\";\r\n\r\n file.close();\r\n emit modifiedChanged(false); \/\/ The file is now saved\r\n\r\n dirtyFiles.removeOne(current);\r\n } else {\r\n QMessageBox::critical(0, \"Error\", tr(\"Could not save to file '%1'.\").arg(filePath));\r\n }\r\n}\r\n\r\nvoid DefaultPluginEditor::save() {\r\n \/\/ Abort when the editor is not open\r\n if (!widget)\r\n return;\r\n\r\n QString filePath = files[current];\r\n\r\n \/\/ If the file is not yet saved, save as instead\r\n if (filePath == QString()) {\r\n saveAs();\r\n return;\r\n }\r\n\r\n writeToFile(filePath);\r\n}\r\n\r\nvoid DefaultPluginEditor::saveAs() {\r\n \/\/ Abort when the editor is not open\r\n if (!widget)\r\n return;\r\n\r\n \/\/ Ask for a file to save to\r\n QString filePath =\r\n QFileDialog::getSaveFileName(this, tr(\"Save Document\"), \"\", tr(\"Python files (*.py);;All Files (*)\"));\r\n\r\n \/\/ Check if user selected a file\r\n if (filePath == QString::null)\r\n return;\r\n\r\n writeToFile(filePath);\r\n\r\n \/\/ Check if the name or path changed\r\n QFileInfo fileInfo(filePath);\r\n\r\n if (fileInfo.exists() && fileInfo.isFile()) {\r\n QString newName = fileInfo.fileName();\r\n\r\n \/\/ Check if the path changed\r\n if (filePath != files[current]) {\r\n\r\n \/\/ A name change can only occur when the path changes\r\n if (newName != current) {\r\n QString content = contents[current]; \/\/ Keep content\r\n\r\n files.remove(current); \/\/ Remove the entry as the key is invalid\r\n\r\n \/\/ Check if file was marked as dirty\r\n if (dirtyFiles.contains(current)) {\r\n dirtyFiles.removeOne(current);\r\n }\r\n\r\n current = newName;\r\n\r\n files.insert(current, filePath);\r\n contents.insert(current, content);\r\n nameChange();\r\n } else {\r\n files[current] = filePath; \/\/ Update the file path\r\n }\r\n\r\n urlChange();\r\n }\r\n }\r\n}\r\n\r\nvoid DefaultPluginEditor::newDocument() {\r\n if (newCounter > 1)\r\n current = QString(\"Untitled (%1)\").arg(newCounter);\r\n else\r\n current = \"Untitled\";\r\n newCounter++;\r\n\r\n files.insert(current, QString());\r\n contents.insert(current, QString());\r\n\r\n createWidget();\r\n widget->document()->setModified(false);\r\n}\r\n\r\nvoid DefaultPluginEditor::modified() { emit modifiedChanged(widget->document()->isModified()); }\r\n\r\nvoid DefaultPluginEditor::nameChange() { emit nameChanged(current); }\r\n\r\nvoid DefaultPluginEditor::urlChange() { emit urlChanged(files[current]); }\r\nAdded dialog box for closing a dirty file in the default plugin editor\/* Copyright (c) 2017, EPL-Vizards\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 EPL-Vizards 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 COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n * ANY 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 EPL-Vizards 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 * \\file DefaultPluginEditor.cpp\r\n *\/\r\n\r\n#include \"DefaultPluginEditor.hpp\"\r\n\r\nDefaultPluginEditor::DefaultPluginEditor(PluginEditorWidget *parent) : PluginEditorBase(parent) {\r\n layout = new QGridLayout(this);\r\n}\r\n\r\nDefaultPluginEditor::~DefaultPluginEditor() {}\r\n\r\nvoid DefaultPluginEditor::createWidget() {\r\n if (!widget) {\r\n \/\/ The widget does not yet exist, create a new one\r\n widget = new QPlainTextEdit(this);\r\n layout->addWidget(widget);\r\n connect(widget->document(), SIGNAL(modificationChanged(bool)), this, SLOT(modified()));\r\n }\r\n\r\n widget->document()->setPlainText(contents[current]);\r\n\r\n \/\/ Check if the file was dirty\r\n if (!dirtyFiles.contains(current)) {\r\n widget->document()->setModified(false); \/\/ Setting the text of the editor modifies it\r\n }\r\n}\r\n\r\nvoid DefaultPluginEditor::updateStatusBar(bool enabled) { (void)enabled; }\r\n\r\nvoid DefaultPluginEditor::openConfig() {\r\n QMessageBox::information(0, \"Info\", tr(\"There is currently no configuration for this editor\"));\r\n}\r\n\r\nvoid DefaultPluginEditor::selectDocument(QString plugin) {\r\n if (widget) {\r\n \/\/ Check if the file is dirty\r\n if (widget->document()->isModified() && !dirtyFiles.contains(current)) {\r\n dirtyFiles.append(current);\r\n contents[current] = widget->document()->toPlainText(); \/\/ Also stash the changes\r\n }\r\n }\r\n current = plugin;\r\n createWidget();\r\n}\r\n\r\nvoid DefaultPluginEditor::closeDocument(QString name) {\r\n \/\/ Only try to close if the editor is open\r\n if (!widget)\r\n return;\r\n\r\n \/\/ Check if file is dirty\r\n if (dirtyFiles.contains(name) || (name == current && widget->document()->isModified())) {\r\n \/\/ Ask user for further input\r\n QMessageBox msg(this);\r\n\r\n QPushButton *saveButton = msg.addButton(\"Save\", QMessageBox::ActionRole);\r\n msg.addButton(\"Discard\", QMessageBox::ActionRole);\r\n\r\n\r\n msg.setText(\"The file '\" + name + \"' has unsaved changes.\");\r\n msg.setInformativeText(\"Would you like to save them?\");\r\n msg.setDefaultButton(saveButton);\r\n\r\n \/\/ Open message box\r\n msg.exec();\r\n\r\n QPushButton *clicked = dynamic_cast(msg.clickedButton());\r\n\r\n if (clicked == saveButton) {\r\n \/\/ Save the changes to this document\r\n save();\r\n } else {\r\n \/\/ Discard button was pressed, remove from dirty files\r\n dirtyFiles.removeOne(name);\r\n }\r\n }\r\n\r\n files.remove(name);\r\n contents.remove(name);\r\n\r\n current = QString();\r\n layout->removeWidget(widget);\r\n delete widget;\r\n widget = nullptr;\r\n}\r\n\r\nvoid DefaultPluginEditor::openDocument(QUrl file) {\r\n QFileInfo fileInfo(file.toLocalFile());\r\n QString fileName;\r\n QString filePath;\r\n\r\n if (fileInfo.exists() && fileInfo.isFile()) {\r\n fileName = fileInfo.fileName();\r\n filePath = fileInfo.filePath();\r\n\r\n files.insert(fileName, filePath);\r\n } else {\r\n QMessageBox::critical(0, \"Error\", tr(\"Could not open file '%1'.\").arg(filePath));\r\n return;\r\n }\r\n\r\n QFile f(filePath);\r\n\r\n if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {\r\n QMessageBox::critical(0, \"Error\", tr(\"Could not open file '%1'.\").arg(filePath));\r\n return;\r\n }\r\n\r\n QTextStream in(&f);\r\n\r\n contents.insert(fileName, in.readAll());\r\n current = fileName;\r\n\r\n createWidget();\r\n}\r\n\r\nvoid DefaultPluginEditor::cleanUp() {\r\n QMessageBox msg(this);\r\n QPushButton *saveButton = msg.addButton(\"Save\", QMessageBox::ActionRole);\r\n QPushButton *saveAllButton = msg.addButton(\"Save All\", QMessageBox::ActionRole);\r\n QPushButton *discardButton = msg.addButton(\"Discard\", QMessageBox::ActionRole);\r\n QPushButton *discardAllButton = msg.addButton(\"Discard All\", QMessageBox::ActionRole);\r\n\r\n\r\n msg.setInformativeText(\"Would you like to save them?\");\r\n msg.setDefaultButton(saveAllButton);\r\n\r\n bool saveAll = false;\r\n\r\n \/\/ Since dirty files are only acknowledged when \"stashing them\", check if the current file is dirty\r\n if (widget && !dirtyFiles.contains(current) && widget->document()->isModified()) {\r\n dirtyFiles.append(current);\r\n }\r\n\r\n QList list = dirtyFiles;\r\n\r\n for (QString file : list) {\r\n if (saveAll) {\r\n current = file;\r\n save();\r\n continue;\r\n }\r\n\r\n msg.setText(\"The file '\" + file + \"' has unsaved changes.\");\r\n\r\n msg.exec();\r\n\r\n QPushButton *clicked = dynamic_cast(msg.clickedButton());\r\n\r\n if (clicked == saveButton) {\r\n \/\/ Save the changes to this document\r\n current = file;\r\n save();\r\n continue;\r\n } else if (clicked == saveAllButton) {\r\n \/\/ Save the changes to this document and remember the choice\r\n current = file;\r\n save();\r\n saveAll = true;\r\n continue;\r\n } else if (clicked == discardButton) {\r\n \/\/ Discard changes for current document\r\n continue;\r\n } else if (clicked == discardAllButton) {\r\n \/\/ Discard all changes\r\n break;\r\n }\r\n }\r\n\r\n QMap savedFiles;\r\n\r\n \/\/ Destroy all documents and add them to the map of saved plugins\r\n for (QString file : files.keys()) {\r\n QString localFile = files[file];\r\n\r\n if (!dirtyFiles.contains(file)) {\r\n if (QFile::exists(localFile)) {\r\n savedFiles.insert(file, localFile);\r\n }\r\n }\r\n }\r\n\r\n\r\n emit pluginsSaved(savedFiles);\r\n files.clear();\r\n contents.clear();\r\n dirtyFiles.clear();\r\n current = QString();\r\n layout->removeWidget(widget);\r\n delete widget;\r\n widget = nullptr;\r\n newCounter = 1;\r\n}\r\n\r\nvoid DefaultPluginEditor::writeToFile(QString filePath) {\r\n\r\n QFile file(filePath);\r\n\r\n contents[current] = widget->document()->toPlainText();\r\n\r\n \/\/ Try to open the file write-only, truncating any previous contents\r\n if (file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {\r\n QTextStream out(&file);\r\n\r\n \/\/ Write the current editors content to the file\r\n out << contents[current] << \"\\n\";\r\n\r\n file.close();\r\n emit modifiedChanged(false); \/\/ The file is now saved\r\n\r\n dirtyFiles.removeOne(current);\r\n } else {\r\n QMessageBox::critical(0, \"Error\", tr(\"Could not save to file '%1'.\").arg(filePath));\r\n }\r\n}\r\n\r\nvoid DefaultPluginEditor::save() {\r\n \/\/ Abort when the editor is not open\r\n if (!widget)\r\n return;\r\n\r\n QString filePath = files[current];\r\n\r\n \/\/ If the file is not yet saved, save as instead\r\n if (filePath == QString()) {\r\n saveAs();\r\n return;\r\n }\r\n\r\n writeToFile(filePath);\r\n}\r\n\r\nvoid DefaultPluginEditor::saveAs() {\r\n \/\/ Abort when the editor is not open\r\n if (!widget)\r\n return;\r\n\r\n \/\/ Ask for a file to save to\r\n QString filePath =\r\n QFileDialog::getSaveFileName(this, tr(\"Save Document\"), \"\", tr(\"Python files (*.py);;All Files (*)\"));\r\n\r\n \/\/ Check if user selected a file\r\n if (filePath == QString::null)\r\n return;\r\n\r\n writeToFile(filePath);\r\n\r\n \/\/ Check if the name or path changed\r\n QFileInfo fileInfo(filePath);\r\n\r\n if (fileInfo.exists() && fileInfo.isFile()) {\r\n QString newName = fileInfo.fileName();\r\n\r\n \/\/ Check if the path changed\r\n if (filePath != files[current]) {\r\n\r\n \/\/ A name change can only occur when the path changes\r\n if (newName != current) {\r\n QString content = contents[current]; \/\/ Keep content\r\n\r\n files.remove(current); \/\/ Remove the entry as the key is invalid\r\n\r\n \/\/ Check if file was marked as dirty\r\n if (dirtyFiles.contains(current)) {\r\n dirtyFiles.removeOne(current);\r\n }\r\n\r\n current = newName;\r\n\r\n files.insert(current, filePath);\r\n contents.insert(current, content);\r\n nameChange();\r\n } else {\r\n files[current] = filePath; \/\/ Update the file path\r\n }\r\n\r\n urlChange();\r\n }\r\n }\r\n}\r\n\r\nvoid DefaultPluginEditor::newDocument() {\r\n if (newCounter > 1)\r\n current = QString(\"Untitled (%1)\").arg(newCounter);\r\n else\r\n current = \"Untitled\";\r\n newCounter++;\r\n\r\n files.insert(current, QString());\r\n contents.insert(current, QString());\r\n\r\n createWidget();\r\n widget->document()->setModified(false);\r\n}\r\n\r\nvoid DefaultPluginEditor::modified() { emit modifiedChanged(widget->document()->isModified()); }\r\n\r\nvoid DefaultPluginEditor::nameChange() { emit nameChanged(current); }\r\n\r\nvoid DefaultPluginEditor::urlChange() { emit urlChanged(files[current]); }\r\n<|endoftext|>"} {"text":"Added param descrs collection to ackermannize_bv_tactic<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"webkit\/glue\/plugins\/plugin_switches.h\"\n\nnamespace {\n\n\/\/ Platform-specific filename relative to the chrome executable.\n#if defined(OS_WIN)\nconst wchar_t library_name[] = L\"ppapi_tests.dll\";\n#elif defined(OS_MACOSX)\nconst char library_name[] = \"ppapi_tests.plugin\";\n#elif defined(OS_POSIX)\nconst char library_name[] = \"libppapi_tests.so\";\n#endif\n\n} \/\/ namespace\n\nclass PPAPITest : public UITest {\n public:\n PPAPITest() {\n \/\/ Append the switch to register the pepper plugin.\n \/\/ library name = \/.\n \/\/ MIME type = application\/x-ppapi-\n FilePath plugin_dir;\n PathService::Get(base::DIR_EXE, &plugin_dir);\n\n FilePath plugin_lib = plugin_dir.Append(library_name);\n EXPECT_TRUE(file_util::PathExists(plugin_lib));\n FilePath::StringType pepper_plugin = plugin_lib.value();\n pepper_plugin.append(FILE_PATH_LITERAL(\";application\/x-ppapi-tests\"));\n launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,\n pepper_plugin);\n\n \/\/ The test sends us the result via a cookie.\n launch_arguments_.AppendSwitch(switches::kEnableFileCookies);\n\n \/\/ Some stuff is hung off of the testing interface which is not enabled\n \/\/ by default.\n launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);\n }\n\n void RunTest(const std::string& test_case) {\n FilePath test_path;\n PathService::Get(base::DIR_SOURCE_ROOT, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"third_party\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"ppapi\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"tests\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"test_case.html\"));\n\n \/\/ Sanity check the file name.\n EXPECT_TRUE(file_util::PathExists(test_path));\n\n GURL::Replacements replacements;\n replacements.SetQuery(test_case.c_str(),\n url_parse::Component(0, test_case.size()));\n GURL test_url = net::FilePathToFileURL(test_path);\n RunTestURL(test_url.ReplaceComponents(replacements));\n }\n\n void RunTestViaHTTP(const std::string& test_case) {\n net::TestServer test_server(\n net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"third_party\/ppapi\/tests\")));\n ASSERT_TRUE(test_server.Start());\n RunTestURL(test_server.GetURL(\"files\/test_case.html?\" + test_case));\n }\n\n private:\n void RunTestURL(const GURL& test_url) {\n scoped_refptr tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(test_url));\n std::string escaped_value =\n WaitUntilCookieNonEmpty(tab.get(), test_url,\n \"COMPLETION_COOKIE\", action_max_timeout_ms());\n EXPECT_STREQ(\"PASS\", escaped_value.c_str());\n }\n};\n\nTEST_F(PPAPITest, FAILS_Instance) {\n RunTest(\"Instance\");\n}\n\n\/\/ http:\/\/crbug.com\/54150\nTEST_F(PPAPITest, FLAKY_Graphics2D) {\n RunTest(\"Graphics2D\");\n}\n\n\/\/ TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.\n\/\/ Possibly all the image allocations slow things down on a loaded bot too much.\nTEST_F(PPAPITest, FLAKY_ImageData) {\n RunTest(\"ImageData\");\n}\n\nTEST_F(PPAPITest, Buffer) {\n RunTest(\"Buffer\");\n}\n\nTEST_F(PPAPITest, URLLoader) {\n RunTestViaHTTP(\"URLLoader\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/51012\nTEST_F(PPAPITest, FLAKY_PaintAggregator) {\n RunTestViaHTTP(\"PaintAggregator\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/48544.\nTEST_F(PPAPITest, FLAKY_Scrollbar) {\n RunTest(\"Scrollbar\");\n}\n\nTEST_F(PPAPITest, UrlUtil) {\n RunTest(\"UrlUtil\");\n}\n\nTEST_F(PPAPITest, CharSet) {\n RunTest(\"CharSet\");\n}\nMark PPAPITest.URLLoader as flaky.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"webkit\/glue\/plugins\/plugin_switches.h\"\n\nnamespace {\n\n\/\/ Platform-specific filename relative to the chrome executable.\n#if defined(OS_WIN)\nconst wchar_t library_name[] = L\"ppapi_tests.dll\";\n#elif defined(OS_MACOSX)\nconst char library_name[] = \"ppapi_tests.plugin\";\n#elif defined(OS_POSIX)\nconst char library_name[] = \"libppapi_tests.so\";\n#endif\n\n} \/\/ namespace\n\nclass PPAPITest : public UITest {\n public:\n PPAPITest() {\n \/\/ Append the switch to register the pepper plugin.\n \/\/ library name = \/.\n \/\/ MIME type = application\/x-ppapi-\n FilePath plugin_dir;\n PathService::Get(base::DIR_EXE, &plugin_dir);\n\n FilePath plugin_lib = plugin_dir.Append(library_name);\n EXPECT_TRUE(file_util::PathExists(plugin_lib));\n FilePath::StringType pepper_plugin = plugin_lib.value();\n pepper_plugin.append(FILE_PATH_LITERAL(\";application\/x-ppapi-tests\"));\n launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,\n pepper_plugin);\n\n \/\/ The test sends us the result via a cookie.\n launch_arguments_.AppendSwitch(switches::kEnableFileCookies);\n\n \/\/ Some stuff is hung off of the testing interface which is not enabled\n \/\/ by default.\n launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);\n }\n\n void RunTest(const std::string& test_case) {\n FilePath test_path;\n PathService::Get(base::DIR_SOURCE_ROOT, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"third_party\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"ppapi\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"tests\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"test_case.html\"));\n\n \/\/ Sanity check the file name.\n EXPECT_TRUE(file_util::PathExists(test_path));\n\n GURL::Replacements replacements;\n replacements.SetQuery(test_case.c_str(),\n url_parse::Component(0, test_case.size()));\n GURL test_url = net::FilePathToFileURL(test_path);\n RunTestURL(test_url.ReplaceComponents(replacements));\n }\n\n void RunTestViaHTTP(const std::string& test_case) {\n net::TestServer test_server(\n net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"third_party\/ppapi\/tests\")));\n ASSERT_TRUE(test_server.Start());\n RunTestURL(test_server.GetURL(\"files\/test_case.html?\" + test_case));\n }\n\n private:\n void RunTestURL(const GURL& test_url) {\n scoped_refptr tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(test_url));\n std::string escaped_value =\n WaitUntilCookieNonEmpty(tab.get(), test_url,\n \"COMPLETION_COOKIE\", action_max_timeout_ms());\n EXPECT_STREQ(\"PASS\", escaped_value.c_str());\n }\n};\n\nTEST_F(PPAPITest, FAILS_Instance) {\n RunTest(\"Instance\");\n}\n\n\/\/ http:\/\/crbug.com\/54150\nTEST_F(PPAPITest, FLAKY_Graphics2D) {\n RunTest(\"Graphics2D\");\n}\n\n\/\/ TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.\n\/\/ Possibly all the image allocations slow things down on a loaded bot too much.\nTEST_F(PPAPITest, FLAKY_ImageData) {\n RunTest(\"ImageData\");\n}\n\nTEST_F(PPAPITest, Buffer) {\n RunTest(\"Buffer\");\n}\n\nTEST_F(PPAPITest, FLAKY_URLLoader) {\n RunTestViaHTTP(\"URLLoader\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/51012\nTEST_F(PPAPITest, FLAKY_PaintAggregator) {\n RunTestViaHTTP(\"PaintAggregator\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/48544.\nTEST_F(PPAPITest, FLAKY_Scrollbar) {\n RunTest(\"Scrollbar\");\n}\n\nTEST_F(PPAPITest, UrlUtil) {\n RunTest(\"UrlUtil\");\n}\n\nTEST_F(PPAPITest, CharSet) {\n RunTest(\"CharSet\");\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: b2drange.hxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: kz $ $Date: 2005-11-02 13:54:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _BGFX_RANGE_B2DRANGE_HXX\n#define _BGFX_RANGE_B2DRANGE_HXX\n\n#ifndef _BGFX_VECTOR_B2DVECTOR_HXX\n#include \n#endif\n#ifndef _BGFX_POINT_B2DPOINT_HXX\n#include \n#endif\n#ifndef _BGFX_TUPLE_B2DTUPLE_HXX\n#include \n#endif\n\n#ifndef _BGFX_RANGE_BASICRANGE_HXX\n#include \n#endif\n\n#include \n\n\nnamespace basegfx\n{\n \/\/ predeclarations\n class B2IRange;\n\n class B2DRange\n {\n public:\n typedef double ValueType;\n typedef DoubleTraits TraitsType;\n\n B2DRange()\n {\n }\n\n explicit B2DRange(const B2DTuple& rTuple)\n : maRangeX(rTuple.getX()),\n maRangeY(rTuple.getY())\n {\n }\n\n B2DRange(double x1,\n double y1,\n double x2,\n double y2)\n : maRangeX(x1),\n maRangeY(y1)\n {\n maRangeX.expand(x2);\n maRangeY.expand(y2);\n }\n\n B2DRange(const B2DTuple& rTuple1,\n const B2DTuple& rTuple2)\n : maRangeX(rTuple1.getX()),\n maRangeY(rTuple1.getY())\n {\n expand( rTuple2 );\n }\n\n B2DRange(const B2DRange& rRange)\n : maRangeX(rRange.maRangeX),\n maRangeY(rRange.maRangeY)\n {\n }\n\n explicit B2DRange(const B2IRange& rRange);\n\n bool isEmpty() const\n {\n return (\n maRangeX.isEmpty()\n || maRangeY.isEmpty()\n );\n }\n\n void reset()\n {\n maRangeX.reset();\n maRangeY.reset();\n }\n\n bool operator==( const B2DRange& rRange ) const\n {\n return (maRangeX == rRange.maRangeX\n && maRangeY == rRange.maRangeY);\n }\n\n bool operator!=( const B2DRange& rRange ) const\n {\n return (maRangeX != rRange.maRangeX\n || maRangeY != rRange.maRangeY);\n }\n\n void operator=(const B2DRange& rRange)\n {\n maRangeX = rRange.maRangeX;\n maRangeY = rRange.maRangeY;\n }\n\n bool equal(const B2DRange& rRange) const\n {\n return (maRangeX.equal(rRange.maRangeX)\n && maRangeY.equal(rRange.maRangeY));\n }\n\n bool equal(const B2DRange& rRange, const double& rfSmallValue) const\n {\n return (maRangeX.equal(rRange.maRangeX,rfSmallValue)\n && maRangeY.equal(rRange.maRangeY,rfSmallValue));\n }\n\n double getMinX() const\n {\n return maRangeX.getMinimum();\n }\n\n double getMinY() const\n {\n return maRangeY.getMinimum();\n }\n\n double getMaxX() const\n {\n return maRangeX.getMaximum();\n }\n\n double getMaxY() const\n {\n return maRangeY.getMaximum();\n }\n\n double getWidth() const\n {\n return maRangeX.getRange();\n }\n\n double getHeight() const\n {\n return maRangeY.getRange();\n }\n\n B2DPoint getMinimum() const\n {\n return B2DPoint(\n maRangeX.getMinimum(),\n maRangeY.getMinimum()\n );\n }\n\n B2DPoint getMaximum() const\n {\n return B2DPoint(\n maRangeX.getMaximum(),\n maRangeY.getMaximum()\n );\n }\n\n B2DVector getRange() const\n {\n return B2DVector(\n maRangeX.getRange(),\n maRangeY.getRange()\n );\n }\n\n B2DPoint getCenter() const\n {\n return B2DPoint(\n maRangeX.getCenter(),\n maRangeY.getCenter()\n );\n }\n\n double getCenterX() const\n {\n return maRangeX.getCenter();\n }\n\n double getCenterY() const\n {\n return maRangeY.getCenter();\n }\n\n bool isInside(const B2DTuple& rTuple) const\n {\n return (\n maRangeX.isInside(rTuple.getX())\n && maRangeY.isInside(rTuple.getY())\n );\n }\n\n bool isInside(const B2DRange& rRange) const\n {\n return (\n maRangeX.isInside(rRange.maRangeX)\n && maRangeY.isInside(rRange.maRangeY)\n );\n }\n\n bool overlaps(const B2DRange& rRange) const\n {\n return (\n maRangeX.overlaps(rRange.maRangeX)\n && maRangeY.overlaps(rRange.maRangeY)\n );\n }\n\n void expand(const B2DTuple& rTuple)\n {\n maRangeX.expand(rTuple.getX());\n maRangeY.expand(rTuple.getY());\n }\n\n void expand(const B2DRange& rRange)\n {\n maRangeX.expand(rRange.maRangeX);\n maRangeY.expand(rRange.maRangeY);\n }\n\n void intersect(const B2DRange& rRange)\n {\n maRangeX.intersect(rRange.maRangeX);\n maRangeY.intersect(rRange.maRangeY);\n }\n\n void grow(double fValue)\n {\n maRangeX.grow(fValue);\n maRangeY.grow(fValue);\n }\n\n private:\n typedef ::basegfx::BasicRange< ValueType, TraitsType > MyBasicRange;\n\n MyBasicRange maRangeX;\n MyBasicRange maRangeY;\n };\n\n \/** Round double to nearest integer for 2D range\n\n @return the nearest integer for this range\n *\/\n B2IRange fround(const B2DRange& rRange);\n\n \/** Compute the set difference of the two given ranges\n\n This method calculates the symmetric difference (aka XOR)\n between the two given ranges, and returning the resulting\n ranges. Thus, the result will contain all areas where one, but\n not both ranges lie.\n\n @param o_rResult\n Result vector. The up to four difference ranges are returned\n within this vector\n\n @param rFirst\n The first range\n\n @param rSecond\n The second range\n\n @return the input vector\n *\/\n ::std::vector< B2DRange >& computeSetDifference( ::std::vector< B2DRange >& o_rResult,\n const B2DRange& rFirst,\n const B2DRange& rSecond );\n\n} \/\/ end of namespace basegfx\n\n\n#endif \/* _BGFX_RANGE_B2DRANGE_HXX *\/\nINTEGRATION: CWS aw024 (1.15.4); FILE MERGED 2006\/03\/15 11:12:27 aw 1.15.4.1: #i39528# Added transform to B2DRange\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: b2drange.hxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: ihi $ $Date: 2006-11-14 14:06:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _BGFX_RANGE_B2DRANGE_HXX\n#define _BGFX_RANGE_B2DRANGE_HXX\n\n#ifndef _BGFX_VECTOR_B2DVECTOR_HXX\n#include \n#endif\n#ifndef _BGFX_POINT_B2DPOINT_HXX\n#include \n#endif\n#ifndef _BGFX_TUPLE_B2DTUPLE_HXX\n#include \n#endif\n\n#ifndef _BGFX_RANGE_BASICRANGE_HXX\n#include \n#endif\n\n#include \n\n\nnamespace basegfx\n{\n \/\/ predeclarations\n class B2IRange;\n\n class B2DRange\n {\n public:\n typedef double ValueType;\n typedef DoubleTraits TraitsType;\n\n B2DRange()\n {\n }\n\n explicit B2DRange(const B2DTuple& rTuple)\n : maRangeX(rTuple.getX()),\n maRangeY(rTuple.getY())\n {\n }\n\n B2DRange(double x1,\n double y1,\n double x2,\n double y2)\n : maRangeX(x1),\n maRangeY(y1)\n {\n maRangeX.expand(x2);\n maRangeY.expand(y2);\n }\n\n B2DRange(const B2DTuple& rTuple1,\n const B2DTuple& rTuple2)\n : maRangeX(rTuple1.getX()),\n maRangeY(rTuple1.getY())\n {\n expand( rTuple2 );\n }\n\n B2DRange(const B2DRange& rRange)\n : maRangeX(rRange.maRangeX),\n maRangeY(rRange.maRangeY)\n {\n }\n\n explicit B2DRange(const B2IRange& rRange);\n\n bool isEmpty() const\n {\n return (\n maRangeX.isEmpty()\n || maRangeY.isEmpty()\n );\n }\n\n void reset()\n {\n maRangeX.reset();\n maRangeY.reset();\n }\n\n bool operator==( const B2DRange& rRange ) const\n {\n return (maRangeX == rRange.maRangeX\n && maRangeY == rRange.maRangeY);\n }\n\n bool operator!=( const B2DRange& rRange ) const\n {\n return (maRangeX != rRange.maRangeX\n || maRangeY != rRange.maRangeY);\n }\n\n void operator=(const B2DRange& rRange)\n {\n maRangeX = rRange.maRangeX;\n maRangeY = rRange.maRangeY;\n }\n\n bool equal(const B2DRange& rRange) const\n {\n return (maRangeX.equal(rRange.maRangeX)\n && maRangeY.equal(rRange.maRangeY));\n }\n\n bool equal(const B2DRange& rRange, const double& rfSmallValue) const\n {\n return (maRangeX.equal(rRange.maRangeX,rfSmallValue)\n && maRangeY.equal(rRange.maRangeY,rfSmallValue));\n }\n\n double getMinX() const\n {\n return maRangeX.getMinimum();\n }\n\n double getMinY() const\n {\n return maRangeY.getMinimum();\n }\n\n double getMaxX() const\n {\n return maRangeX.getMaximum();\n }\n\n double getMaxY() const\n {\n return maRangeY.getMaximum();\n }\n\n double getWidth() const\n {\n return maRangeX.getRange();\n }\n\n double getHeight() const\n {\n return maRangeY.getRange();\n }\n\n B2DPoint getMinimum() const\n {\n return B2DPoint(\n maRangeX.getMinimum(),\n maRangeY.getMinimum()\n );\n }\n\n B2DPoint getMaximum() const\n {\n return B2DPoint(\n maRangeX.getMaximum(),\n maRangeY.getMaximum()\n );\n }\n\n B2DVector getRange() const\n {\n return B2DVector(\n maRangeX.getRange(),\n maRangeY.getRange()\n );\n }\n\n B2DPoint getCenter() const\n {\n return B2DPoint(\n maRangeX.getCenter(),\n maRangeY.getCenter()\n );\n }\n\n double getCenterX() const\n {\n return maRangeX.getCenter();\n }\n\n double getCenterY() const\n {\n return maRangeY.getCenter();\n }\n\n bool isInside(const B2DTuple& rTuple) const\n {\n return (\n maRangeX.isInside(rTuple.getX())\n && maRangeY.isInside(rTuple.getY())\n );\n }\n\n bool isInside(const B2DRange& rRange) const\n {\n return (\n maRangeX.isInside(rRange.maRangeX)\n && maRangeY.isInside(rRange.maRangeY)\n );\n }\n\n bool overlaps(const B2DRange& rRange) const\n {\n return (\n maRangeX.overlaps(rRange.maRangeX)\n && maRangeY.overlaps(rRange.maRangeY)\n );\n }\n\n void expand(const B2DTuple& rTuple)\n {\n maRangeX.expand(rTuple.getX());\n maRangeY.expand(rTuple.getY());\n }\n\n void expand(const B2DRange& rRange)\n {\n maRangeX.expand(rRange.maRangeX);\n maRangeY.expand(rRange.maRangeY);\n }\n\n void intersect(const B2DRange& rRange)\n {\n maRangeX.intersect(rRange.maRangeX);\n maRangeY.intersect(rRange.maRangeY);\n }\n\n void grow(double fValue)\n {\n maRangeX.grow(fValue);\n maRangeY.grow(fValue);\n }\n\n void transform(const B2DHomMatrix& rMatrix);\n\n private:\n typedef ::basegfx::BasicRange< ValueType, TraitsType > MyBasicRange;\n\n MyBasicRange maRangeX;\n MyBasicRange maRangeY;\n };\n\n \/** Round double to nearest integer for 2D range\n\n @return the nearest integer for this range\n *\/\n B2IRange fround(const B2DRange& rRange);\n\n \/** Compute the set difference of the two given ranges\n\n This method calculates the symmetric difference (aka XOR)\n between the two given ranges, and returning the resulting\n ranges. Thus, the result will contain all areas where one, but\n not both ranges lie.\n\n @param o_rResult\n Result vector. The up to four difference ranges are returned\n within this vector\n\n @param rFirst\n The first range\n\n @param rSecond\n The second range\n\n @return the input vector\n *\/\n ::std::vector< B2DRange >& computeSetDifference( ::std::vector< B2DRange >& o_rResult,\n const B2DRange& rFirst,\n const B2DRange& rSecond );\n\n} \/\/ end of namespace basegfx\n\n\n#endif \/* _BGFX_RANGE_B2DRANGE_HXX *\/\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\/worker_host\/worker_service.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n\nstatic const char kTestCompleteCookie[] = \"status\";\nstatic const char kTestCompleteSuccess[] = \"OK\";\n\nclass WorkerTest : public UILayoutTest {\n protected:\n virtual ~WorkerTest() { }\n\n void RunTest(const std::wstring& test_case) {\n scoped_refptr tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n\n GURL url = GetTestUrl(L\"workers\", test_case);\n ASSERT_TRUE(tab->NavigateToURL(url));\n\n std::string value = WaitUntilCookieNonEmpty(tab.get(), url,\n kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);\n ASSERT_STREQ(kTestCompleteSuccess, value.c_str());\n }\n};\n\nTEST_F(WorkerTest, SingleWorker) {\n RunTest(L\"single_worker.html\");\n}\n\nTEST_F(WorkerTest, MultipleWorkers) {\n RunTest(L\"multi_worker.html\");\n}\n\n\/\/ WorkerFastLayoutTests works on the linux try servers, but fails on the\n\/\/ build bots and fails on mac valgrind.\n#if !defined(OS_WIN)\n#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests\n#endif\n\nTEST_F(WorkerTest, WorkerFastLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \"stress-js-execution.html\",\n#if defined(OS_WIN)\n \/\/ Workers don't properly initialize the V8 stack guard.\n \/\/ (http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=21653).\n \"use-machine-stack.html\",\n#endif\n \"worker-call.html\",\n \/\/ Disabled because cloning ports are too slow in Chromium to meet the\n \/\/ thresholds in this test.\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22780\n \/\/ \"worker-cloneport.html\",\n\n \"worker-close.html\",\n \"worker-constructor.html\",\n \"worker-context-gc.html\",\n \"worker-context-multi-port.html\",\n \"worker-event-listener.html\",\n \"worker-gc.html\",\n \/\/ worker-lifecycle.html relies on layoutTestController.workerThreadCount\n \/\/ which is not currently implemented.\n \/\/ \"worker-lifecycle.html\",\n \"worker-location.html\",\n \"worker-messageport.html\",\n \/\/ Disabled after r27089 (WebKit merge), http:\/\/crbug.com\/22947\n \/\/ \"worker-messageport-gc.html\",\n \"worker-multi-port.html\",\n \"worker-navigator.html\",\n \"worker-replace-global-constructor.html\",\n \"worker-replace-self.html\",\n \"worker-script-error.html\",\n \"worker-terminate.html\",\n \"worker-timeout.html\"\n };\n\n FilePath fast_test_dir;\n fast_test_dir = fast_test_dir.AppendASCII(\"LayoutTests\");\n fast_test_dir = fast_test_dir.AppendASCII(\"fast\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);\n\n \/\/ Worker tests also rely on common files in js\/resources.\n FilePath js_dir = fast_test_dir.AppendASCII(\"js\");\n FilePath resource_dir;\n resource_dir = resource_dir.AppendASCII(\"resources\");\n AddResourceForLayoutTest(js_dir, resource_dir);\n\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], false);\n}\n\nTEST_F(WorkerTest, WorkerHttpLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \/\/ flakey? BUG 16934 \"text-encoding.html\",\n#if defined(OS_WIN)\n \/\/ Fails on the mac (and linux?):\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22599\n \"worker-importScripts.html\",\n#endif\n \"worker-redirect.html\",\n };\n\n FilePath http_test_dir;\n http_test_dir = http_test_dir.AppendASCII(\"LayoutTests\");\n http_test_dir = http_test_dir.AppendASCII(\"http\");\n http_test_dir = http_test_dir.AppendASCII(\"tests\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(http_test_dir, worker_test_dir, true);\n\n StartHttpServer(new_http_root_dir_);\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], true);\n StopHttpServer();\n}\n\nTEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \"abort-exception-assert.html\",\n#if defined(OS_WIN)\n \/\/ Fails on the mac (and linux?):\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22599\n \"close.html\",\n#endif\n \/\/\"methods-async.html\",\n \/\/\"methods.html\",\n \"xmlhttprequest-file-not-found.html\"\n };\n\n FilePath http_test_dir;\n http_test_dir = http_test_dir.AppendASCII(\"LayoutTests\");\n http_test_dir = http_test_dir.AppendASCII(\"http\");\n http_test_dir = http_test_dir.AppendASCII(\"tests\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"xmlhttprequest\");\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(http_test_dir, worker_test_dir, true);\n\n StartHttpServer(new_http_root_dir_);\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], true);\n StopHttpServer();\n}\n\nTEST_F(WorkerTest, MessagePorts) {\n static const char* kLayoutTestFiles[] = {\n \"message-channel-gc.html\",\n \"message-channel-gc-2.html\",\n \"message-channel-gc-3.html\",\n \"message-channel-gc-4.html\",\n \"message-port.html\",\n \"message-port-clone.html\",\n \"message-port-constructor-for-deleted-document.html\",\n \"message-port-deleted-document.html\",\n \"message-port-deleted-frame.html\",\n \"message-port-inactive-document.html\",\n \"message-port-multi.html\",\n \"message-port-no-wrapper.html\",\n \/\/ Only works with run-webkit-tests --leaks.\n \/\/\"message-channel-listener-circular-ownership.html\",\n };\n\n FilePath fast_test_dir;\n fast_test_dir = fast_test_dir.AppendASCII(\"LayoutTests\");\n fast_test_dir = fast_test_dir.AppendASCII(\"fast\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"events\");\n InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);\n\n \/\/ MessagePort tests also rely on common files in js\/resources.\n FilePath js_dir = fast_test_dir.AppendASCII(\"js\");\n FilePath resource_dir;\n resource_dir = resource_dir.AppendASCII(\"resources\");\n AddResourceForLayoutTest(js_dir, resource_dir);\n\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], false);\n}\n\n\/\/ Disable LimitPerPage on Linux. Seems to work on Mac though:\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22608\n#if !defined(OS_LINUX)\nTEST_F(WorkerTest, LimitPerPage) {\n int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;\n GURL url = GetTestUrl(L\"workers\", L\"many_workers.html\");\n url = GURL(url.spec() + StringPrintf(\"?count=%d\", max_workers_per_tab + 1));\n\n scoped_refptr tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(url));\n\n EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),\n UITest::GetBrowserProcessCount());\n}\n#endif\n\n\/\/ Disable LimitTotal on Linux and Mac.\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22608\n#if defined(OS_WIN)\nTEST_F(WorkerTest, LimitTotal) {\n int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;\n int total_workers = WorkerService::kMaxWorkersWhenSeparate;\n\n int tab_count = (total_workers \/ max_workers_per_tab) + 1;\n GURL url = GetTestUrl(L\"workers\", L\"many_workers.html\");\n url = GURL(url.spec() + StringPrintf(\"?count=%d\", max_workers_per_tab));\n\n scoped_refptr tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(url));\n scoped_refptr window(automation()->GetBrowserWindow(0));\n for (int i = 1; i < tab_count; ++i)\n window->AppendTab(url);\n\n \/\/ Check that we didn't create more than the max number of workers.\n EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),\n UITest::GetBrowserProcessCount());\n\n \/\/ Now close the first tab and check that the queued workers were started.\n tab->Close(true);\n tab->NavigateToURL(GetTestUrl(L\"google\", L\"google.html\"));\n\n EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),\n UITest::GetBrowserProcessCount());\n}\n#endif\nDisabling failing WorkerTest.MessagePorts after WebKit roll.\/\/ 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\/worker_host\/worker_service.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n\nstatic const char kTestCompleteCookie[] = \"status\";\nstatic const char kTestCompleteSuccess[] = \"OK\";\n\nclass WorkerTest : public UILayoutTest {\n protected:\n virtual ~WorkerTest() { }\n\n void RunTest(const std::wstring& test_case) {\n scoped_refptr tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n\n GURL url = GetTestUrl(L\"workers\", test_case);\n ASSERT_TRUE(tab->NavigateToURL(url));\n\n std::string value = WaitUntilCookieNonEmpty(tab.get(), url,\n kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);\n ASSERT_STREQ(kTestCompleteSuccess, value.c_str());\n }\n};\n\nTEST_F(WorkerTest, SingleWorker) {\n RunTest(L\"single_worker.html\");\n}\n\nTEST_F(WorkerTest, MultipleWorkers) {\n RunTest(L\"multi_worker.html\");\n}\n\n\/\/ WorkerFastLayoutTests works on the linux try servers, but fails on the\n\/\/ build bots and fails on mac valgrind.\n#if !defined(OS_WIN)\n#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests\n#endif\n\nTEST_F(WorkerTest, WorkerFastLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \"stress-js-execution.html\",\n#if defined(OS_WIN)\n \/\/ Workers don't properly initialize the V8 stack guard.\n \/\/ (http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=21653).\n \"use-machine-stack.html\",\n#endif\n \"worker-call.html\",\n \/\/ Disabled because cloning ports are too slow in Chromium to meet the\n \/\/ thresholds in this test.\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22780\n \/\/ \"worker-cloneport.html\",\n\n \"worker-close.html\",\n \"worker-constructor.html\",\n \"worker-context-gc.html\",\n \"worker-context-multi-port.html\",\n \"worker-event-listener.html\",\n \"worker-gc.html\",\n \/\/ worker-lifecycle.html relies on layoutTestController.workerThreadCount\n \/\/ which is not currently implemented.\n \/\/ \"worker-lifecycle.html\",\n \"worker-location.html\",\n \"worker-messageport.html\",\n \/\/ Disabled after r27089 (WebKit merge), http:\/\/crbug.com\/22947\n \/\/ \"worker-messageport-gc.html\",\n \"worker-multi-port.html\",\n \"worker-navigator.html\",\n \"worker-replace-global-constructor.html\",\n \"worker-replace-self.html\",\n \"worker-script-error.html\",\n \"worker-terminate.html\",\n \"worker-timeout.html\"\n };\n\n FilePath fast_test_dir;\n fast_test_dir = fast_test_dir.AppendASCII(\"LayoutTests\");\n fast_test_dir = fast_test_dir.AppendASCII(\"fast\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);\n\n \/\/ Worker tests also rely on common files in js\/resources.\n FilePath js_dir = fast_test_dir.AppendASCII(\"js\");\n FilePath resource_dir;\n resource_dir = resource_dir.AppendASCII(\"resources\");\n AddResourceForLayoutTest(js_dir, resource_dir);\n\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], false);\n}\n\nTEST_F(WorkerTest, WorkerHttpLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \/\/ flakey? BUG 16934 \"text-encoding.html\",\n#if defined(OS_WIN)\n \/\/ Fails on the mac (and linux?):\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22599\n \"worker-importScripts.html\",\n#endif\n \"worker-redirect.html\",\n };\n\n FilePath http_test_dir;\n http_test_dir = http_test_dir.AppendASCII(\"LayoutTests\");\n http_test_dir = http_test_dir.AppendASCII(\"http\");\n http_test_dir = http_test_dir.AppendASCII(\"tests\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(http_test_dir, worker_test_dir, true);\n\n StartHttpServer(new_http_root_dir_);\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], true);\n StopHttpServer();\n}\n\nTEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \"abort-exception-assert.html\",\n#if defined(OS_WIN)\n \/\/ Fails on the mac (and linux?):\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22599\n \"close.html\",\n#endif\n \/\/\"methods-async.html\",\n \/\/\"methods.html\",\n \"xmlhttprequest-file-not-found.html\"\n };\n\n FilePath http_test_dir;\n http_test_dir = http_test_dir.AppendASCII(\"LayoutTests\");\n http_test_dir = http_test_dir.AppendASCII(\"http\");\n http_test_dir = http_test_dir.AppendASCII(\"tests\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"xmlhttprequest\");\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(http_test_dir, worker_test_dir, true);\n\n StartHttpServer(new_http_root_dir_);\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], true);\n StopHttpServer();\n}\n\nTEST_F(WorkerTest, DISABLED_MessagePorts) {\n static const char* kLayoutTestFiles[] = {\n \"message-channel-gc.html\",\n \"message-channel-gc-2.html\",\n \"message-channel-gc-3.html\",\n \"message-channel-gc-4.html\",\n \"message-port.html\",\n \"message-port-clone.html\",\n \"message-port-constructor-for-deleted-document.html\",\n \"message-port-deleted-document.html\",\n \"message-port-deleted-frame.html\",\n \"message-port-inactive-document.html\",\n \"message-port-multi.html\",\n \"message-port-no-wrapper.html\",\n \/\/ Only works with run-webkit-tests --leaks.\n \/\/\"message-channel-listener-circular-ownership.html\",\n };\n\n FilePath fast_test_dir;\n fast_test_dir = fast_test_dir.AppendASCII(\"LayoutTests\");\n fast_test_dir = fast_test_dir.AppendASCII(\"fast\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"events\");\n InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);\n\n \/\/ MessagePort tests also rely on common files in js\/resources.\n FilePath js_dir = fast_test_dir.AppendASCII(\"js\");\n FilePath resource_dir;\n resource_dir = resource_dir.AppendASCII(\"resources\");\n AddResourceForLayoutTest(js_dir, resource_dir);\n\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], false);\n}\n\n\/\/ Disable LimitPerPage on Linux. Seems to work on Mac though:\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22608\n#if !defined(OS_LINUX)\nTEST_F(WorkerTest, LimitPerPage) {\n int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;\n GURL url = GetTestUrl(L\"workers\", L\"many_workers.html\");\n url = GURL(url.spec() + StringPrintf(\"?count=%d\", max_workers_per_tab + 1));\n\n scoped_refptr tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(url));\n\n EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),\n UITest::GetBrowserProcessCount());\n}\n#endif\n\n\/\/ Disable LimitTotal on Linux and Mac.\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22608\n#if defined(OS_WIN)\nTEST_F(WorkerTest, LimitTotal) {\n int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;\n int total_workers = WorkerService::kMaxWorkersWhenSeparate;\n\n int tab_count = (total_workers \/ max_workers_per_tab) + 1;\n GURL url = GetTestUrl(L\"workers\", L\"many_workers.html\");\n url = GURL(url.spec() + StringPrintf(\"?count=%d\", max_workers_per_tab));\n\n scoped_refptr tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(url));\n scoped_refptr window(automation()->GetBrowserWindow(0));\n for (int i = 1; i < tab_count; ++i)\n window->AppendTab(url);\n\n \/\/ Check that we didn't create more than the max number of workers.\n EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),\n UITest::GetBrowserProcessCount());\n\n \/\/ Now close the first tab and check that the queued workers were started.\n tab->Close(true);\n tab->NavigateToURL(GetTestUrl(L\"google\", L\"google.html\"));\n\n EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),\n UITest::GetBrowserProcessCount());\n}\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_UTILS_LOG_HPP\n#define OUZEL_UTILS_LOG_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/math\/Matrix.hpp\"\n#include \"..\/math\/Quaternion.hpp\"\n#include \"..\/math\/Size.hpp\"\n#include \"..\/math\/Vector.hpp\"\n#include \"..\/storage\/Path.hpp\"\n#include \"Thread.hpp\"\n#include \"Utils.hpp\"\n\nnamespace ouzel\n{\n class Logger;\n\n class Log final\n {\n public:\n enum class Level\n {\n off,\n error,\n warning,\n info,\n all\n };\n\n explicit Log(const Logger& initLogger, Level initLevel = Level::info):\n logger(initLogger), level(initLevel)\n {\n }\n\n Log(const Log& other):\n logger(other.logger),\n level(other.level),\n s(other.s)\n {\n }\n\n Log(Log&& other) noexcept:\n logger(other.logger),\n level(other.level),\n s(std::move(other.s))\n {\n other.level = Level::info;\n }\n\n Log& operator=(const Log& other)\n {\n if (&other == this) return *this;\n\n level = other.level;\n s = other.s;\n\n return *this;\n }\n\n Log& operator=(Log&& other) noexcept\n {\n if (&other == this) return *this;\n\n level = other.level;\n other.level = Level::info;\n s = std::move(other.s);\n\n return *this;\n }\n\n ~Log();\n\n Log& operator<<(const bool val)\n {\n s += val ? \"true\" : \"false\";\n return *this;\n }\n\n Log& operator<<(const uint8_t val)\n {\n constexpr char digits[] = \"0123456789abcdef\";\n\n for (std::uint32_t p = 0; p < 2; ++p)\n s.push_back(digits[(val >> (4 - p * 4)) & 0x0F]);\n\n return *this;\n }\n\n template &&\n !std::is_same_v &&\n !std::is_same_v>* = nullptr>\n Log& operator<<(const T val)\n {\n s += std::to_string(val);\n return *this;\n }\n\n Log& operator<<(const std::string& val)\n {\n s += val;\n return *this;\n }\n\n Log& operator<<(const char* val)\n {\n s += val;\n return *this;\n }\n\n template >* = nullptr>\n Log& operator<<(const T* val)\n {\n constexpr char digits[] = \"0123456789abcdef\";\n\n const auto ptrValue = bitCast(val);\n\n for (std::size_t i = 0; i < sizeof(val) * 2; ++i)\n s.push_back(digits[(ptrValue >> (sizeof(ptrValue) * 2 - i - 1) * 4) & 0x0F]);\n\n return *this;\n }\n\n Log& operator<<(const storage::Path& val)\n {\n s += val;\n return *this;\n }\n\n template\n struct isContainer: std::false_type {};\n\n template\n struct isContainer().begin()),\n decltype(std::declval().end())\n >>: std::true_type {};\n\n template ::value>* = nullptr>\n Log& operator<<(const T& val)\n {\n bool first = true;\n for (const auto& i : val)\n {\n if (!first) s += \", \";\n first = false;\n operator<<(i);\n }\n\n return *this;\n }\n\n template \n Log& operator<<(const Matrix& val)\n {\n bool first = true;\n\n for (const T c : val.m)\n {\n if (!first) s += \",\";\n first = false;\n s += std::to_string(c);\n }\n\n return *this;\n }\n\n template \n Log& operator<<(const Quaternion& val)\n {\n s += std::to_string(val.v[0]) + \",\" + std::to_string(val.v[1]) + \",\" +\n std::to_string(val.v[2]) + \",\" + std::to_string(val.v[3]);\n return *this;\n }\n\n template \n Log& operator<<(const Size& val)\n {\n bool first = true;\n\n for (const T c : val.v)\n {\n if (!first) s += \",\";\n first = false;\n s += std::to_string(c);\n }\n return *this;\n }\n\n template \n Log& operator<<(const Vector& val)\n {\n bool first = true;\n\n for (const T c : val.v)\n {\n if (!first) s += \",\";\n first = false;\n s += std::to_string(c);\n }\n return *this;\n }\n\n private:\n const Logger& logger;\n Level level = Level::info;\n std::string s;\n };\n\n class Logger final\n {\n public:\n explicit Logger(Log::Level initThreshold = Log::Level::all):\n threshold(initThreshold)\n {\n#if !defined(__EMSCRIPTEN__)\n logThread = Thread(&Logger::logLoop, this);\n#endif\n }\n\n Logger(const Logger&) = delete;\n Logger& operator=(const Logger&) = delete;\n Logger(Logger&&) = delete;\n Logger& operator=(Logger&&) = delete;\n\n ~Logger()\n {\n#if !defined(__EMSCRIPTEN__)\n std::unique_lock lock(queueMutex);\n commandQueue.push(Command(Command::Type::quit));\n lock.unlock();\n queueCondition.notify_all();\n#endif\n }\n\n Log log(const Log::Level level = Log::Level::info) const\n {\n return Log(*this, level);\n }\n\n void log(const std::string& str, const Log::Level level = Log::Level::info) const\n {\n if (level <= threshold)\n {\n#if defined(__EMSCRIPTEN__)\n logString(str, level);\n#else\n std::unique_lock lock(queueMutex);\n commandQueue.push(Command(Command::Type::logString, level, str));\n lock.unlock();\n queueCondition.notify_all();\n#endif\n }\n }\n\n private:\n static void logString(const std::string& str, const Log::Level level = Log::Level::info);\n\n#ifdef DEBUG\n std::atomic threshold{Log::Level::all};\n#else\n std::atomic threshold{Log::Level::info};\n#endif\n\n#if !defined(__EMSCRIPTEN__)\n class Command final\n {\n public:\n enum class Type\n {\n logString,\n quit\n };\n\n explicit Command(const Type initType):\n type(initType)\n {\n }\n\n Command(const Type initType, const Log::Level initLevel,\n const std::string& initString):\n type(initType),\n level(initLevel),\n str(initString)\n {\n }\n\n Type type;\n Log::Level level = Log::Level::all;\n std::string str;\n };\n\n void logLoop()\n {\n for (;;)\n {\n std::unique_lock lock(queueMutex);\n while (commandQueue.empty()) queueCondition.wait(lock);\n auto command = std::move(commandQueue.front());\n commandQueue.pop();\n lock.unlock();\n\n if (command.type == Command::Type::logString)\n logString(command.str, command.level);\n else if (command.type == Command::Type::quit)\n break;\n }\n }\n\n mutable std::condition_variable queueCondition;\n mutable std::mutex queueMutex;\n mutable std::queue commandQueue;\n Thread logThread;\n#endif\n };\n}\n\n#endif \/\/ OUZEL_UTILS_LOG_HPP\nCheck also for arrays\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_UTILS_LOG_HPP\n#define OUZEL_UTILS_LOG_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/math\/Matrix.hpp\"\n#include \"..\/math\/Quaternion.hpp\"\n#include \"..\/math\/Size.hpp\"\n#include \"..\/math\/Vector.hpp\"\n#include \"..\/storage\/Path.hpp\"\n#include \"Thread.hpp\"\n#include \"Utils.hpp\"\n\nnamespace ouzel\n{\n class Logger;\n\n class Log final\n {\n public:\n enum class Level\n {\n off,\n error,\n warning,\n info,\n all\n };\n\n explicit Log(const Logger& initLogger, Level initLevel = Level::info):\n logger(initLogger), level(initLevel)\n {\n }\n\n Log(const Log& other):\n logger(other.logger),\n level(other.level),\n s(other.s)\n {\n }\n\n Log(Log&& other) noexcept:\n logger(other.logger),\n level(other.level),\n s(std::move(other.s))\n {\n other.level = Level::info;\n }\n\n Log& operator=(const Log& other)\n {\n if (&other == this) return *this;\n\n level = other.level;\n s = other.s;\n\n return *this;\n }\n\n Log& operator=(Log&& other) noexcept\n {\n if (&other == this) return *this;\n\n level = other.level;\n other.level = Level::info;\n s = std::move(other.s);\n\n return *this;\n }\n\n ~Log();\n\n Log& operator<<(const bool val)\n {\n s += val ? \"true\" : \"false\";\n return *this;\n }\n\n Log& operator<<(const uint8_t val)\n {\n constexpr char digits[] = \"0123456789abcdef\";\n\n for (std::uint32_t p = 0; p < 2; ++p)\n s.push_back(digits[(val >> (4 - p * 4)) & 0x0F]);\n\n return *this;\n }\n\n template &&\n !std::is_same_v &&\n !std::is_same_v>* = nullptr>\n Log& operator<<(const T val)\n {\n s += std::to_string(val);\n return *this;\n }\n\n Log& operator<<(const std::string& val)\n {\n s += val;\n return *this;\n }\n\n Log& operator<<(const char* val)\n {\n s += val;\n return *this;\n }\n\n template >* = nullptr>\n Log& operator<<(const T* val)\n {\n constexpr char digits[] = \"0123456789abcdef\";\n\n const auto ptrValue = bitCast(val);\n\n for (std::size_t i = 0; i < sizeof(val) * 2; ++i)\n s.push_back(digits[(ptrValue >> (sizeof(ptrValue) * 2 - i - 1) * 4) & 0x0F]);\n\n return *this;\n }\n\n Log& operator<<(const storage::Path& val)\n {\n s += val;\n return *this;\n }\n\n template\n struct isContainer: std::false_type {};\n\n template\n struct isContainer().begin()),\n decltype(std::declval().end())\n >>: std::true_type {};\n\n template ::value || std::is_array_v>* = nullptr>\n Log& operator<<(const T& val)\n {\n bool first = true;\n for (const auto& i : val)\n {\n if (!first) s += \", \";\n first = false;\n operator<<(i);\n }\n\n return *this;\n }\n\n template \n Log& operator<<(const Matrix& val)\n {\n bool first = true;\n\n for (const T c : val.m)\n {\n if (!first) s += \",\";\n first = false;\n s += std::to_string(c);\n }\n\n return *this;\n }\n\n template \n Log& operator<<(const Quaternion& val)\n {\n s += std::to_string(val.v[0]) + \",\" + std::to_string(val.v[1]) + \",\" +\n std::to_string(val.v[2]) + \",\" + std::to_string(val.v[3]);\n return *this;\n }\n\n template \n Log& operator<<(const Size& val)\n {\n bool first = true;\n\n for (const T c : val.v)\n {\n if (!first) s += \",\";\n first = false;\n s += std::to_string(c);\n }\n return *this;\n }\n\n template \n Log& operator<<(const Vector& val)\n {\n bool first = true;\n\n for (const T c : val.v)\n {\n if (!first) s += \",\";\n first = false;\n s += std::to_string(c);\n }\n return *this;\n }\n\n private:\n const Logger& logger;\n Level level = Level::info;\n std::string s;\n };\n\n class Logger final\n {\n public:\n explicit Logger(Log::Level initThreshold = Log::Level::all):\n threshold(initThreshold)\n {\n#if !defined(__EMSCRIPTEN__)\n logThread = Thread(&Logger::logLoop, this);\n#endif\n }\n\n Logger(const Logger&) = delete;\n Logger& operator=(const Logger&) = delete;\n Logger(Logger&&) = delete;\n Logger& operator=(Logger&&) = delete;\n\n ~Logger()\n {\n#if !defined(__EMSCRIPTEN__)\n std::unique_lock lock(queueMutex);\n commandQueue.push(Command(Command::Type::quit));\n lock.unlock();\n queueCondition.notify_all();\n#endif\n }\n\n Log log(const Log::Level level = Log::Level::info) const\n {\n return Log(*this, level);\n }\n\n void log(const std::string& str, const Log::Level level = Log::Level::info) const\n {\n if (level <= threshold)\n {\n#if defined(__EMSCRIPTEN__)\n logString(str, level);\n#else\n std::unique_lock lock(queueMutex);\n commandQueue.push(Command(Command::Type::logString, level, str));\n lock.unlock();\n queueCondition.notify_all();\n#endif\n }\n }\n\n private:\n static void logString(const std::string& str, const Log::Level level = Log::Level::info);\n\n#ifdef DEBUG\n std::atomic threshold{Log::Level::all};\n#else\n std::atomic threshold{Log::Level::info};\n#endif\n\n#if !defined(__EMSCRIPTEN__)\n class Command final\n {\n public:\n enum class Type\n {\n logString,\n quit\n };\n\n explicit Command(const Type initType):\n type(initType)\n {\n }\n\n Command(const Type initType, const Log::Level initLevel,\n const std::string& initString):\n type(initType),\n level(initLevel),\n str(initString)\n {\n }\n\n Type type;\n Log::Level level = Log::Level::all;\n std::string str;\n };\n\n void logLoop()\n {\n for (;;)\n {\n std::unique_lock lock(queueMutex);\n while (commandQueue.empty()) queueCondition.wait(lock);\n auto command = std::move(commandQueue.front());\n commandQueue.pop();\n lock.unlock();\n\n if (command.type == Command::Type::logString)\n logString(command.str, command.level);\n else if (command.type == Command::Type::quit)\n break;\n }\n }\n\n mutable std::condition_variable queueCondition;\n mutable std::mutex queueMutex;\n mutable std::queue commandQueue;\n Thread logThread;\n#endif\n };\n}\n\n#endif \/\/ OUZEL_UTILS_LOG_HPP\n<|endoftext|>"} {"text":"Temporarily disable a failing ui test.<|endoftext|>"} {"text":"Uncrash BrowserFocusTest.*<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#define NAMESPACE \"bench.objects\"\n\n\/\/ Calls MongoDB function, checks for error and discards result\n#define CHECK_ERROR(func, conn, ...) \\\n conn.func(__VA_ARGS__); \\\n \\\n std::string error = conn.getLastError(); \\\n if (error != \"\") throw std::runtime_error(#func + error);\n\n\/\/ Calls MongoDB function, checks for error and store result in `result`\n#define CHECK_ERROR_STORE(func, conn, result, ...) \\\n auto result = conn.func(__VA_ARGS__); \\\n \\\n std::string error = conn.getLastError(); \\\n if (error != \"\") throw std::runtime_error(#func + error);\n\nusing namespace bench::tests::mongodb;\n\nmongodb_facade::mongodb_facade()\n{\n}\n\nmongodb_facade::~mongodb_facade()\n{\n}\n\nvoid\nmongodb_facade::connect(const std::string & cluster_uri) {\n _conn.connect(cluster_uri);\n}\n\n\/* static *\/ mongo::BSONObj mongodb_facade::server_status(const std::string & node_uri) {\n mongo::DBClientConnection conn;\n conn.connect(node_uri);\n\n mongo::BSONObj serverStatus;\n\n if (!conn.runCommand(\"bench\", BSON(\"serverStatus\" << 1), serverStatus)) {\n throw std::runtime_error(\"node_status: serverStatus\");\n }\n\n return BSON(\"server\" << serverStatus << \"db\" << mongodb_facade::db_status(node_uri));\n}\n\n\/* static *\/ mongo::BSONObj mongodb_facade::db_status(const std::string & node_uri) {\n mongo::DBClientConnection conn;\n conn.connect(node_uri);\n\n mongo::BSONObj dbStats;\n if (!conn.runCommand(\"bench\", BSON(\"dbStats\" << 1), dbStats)) {\n throw std::runtime_error(\"node_status: dbStats\");\n }\n\n return dbStats;\n}\n\n\n\/* static *\/ std::vector mongodb_facade::resolve_topology(const std::string & node_uri) {\n mongo::DBClientConnection conn;\n conn.connect(node_uri);\n\n \/*\n Our `node_uri` can be any of the following:\n\n * an entry to a `mongos` instance, a sharded cluster;\n * an entry to a replica set;\n * a single node configuration.\n\n We are going to probe for what kind of configuration we are\n dealing with by executing the relevant admin commands, and\n based on those responses resolve the entire topology.\n *\/\n\n mongo::BSONObj response;\n\n std::vector result;\n\n if (conn.runCommand(\"admin\", BSON(\"listShards\" << 1), response)) {\n \/\/ We are in sharded cluster.\n\n for (mongo::BSONElement const & member : response[\"shards\"].Array()) {\n \/\/ Member can be either a replica set, which looks like\n \/\/ `rs0\/1.2.3.4:1234,4.3.2.1:4321`, or it is a regular\n \/\/ host, which looks like `1.2.3.4:1234`.\n std::string host = member[\"host\"].String();\n\n std::vector tokens;\n boost::split(tokens, host, boost::is_any_of(\"\/\"));\n\n if (tokens.size() == 1) {\n \/\/ A regular host\n result.push_back(tokens.at(0));\n } else if (tokens.size() == 2) {\n std::vector hosts;\n\n boost::split(hosts, tokens.at(1), boost::is_any_of(\",\"));\n\n std::copy(hosts.begin(), hosts.end(),\n std::back_insert_iterator>(result));\n } else {\n throw std::runtime_error(\"Invalid host: \" + host);\n }\n }\n\n } else if (conn.runCommand(\"admin\", BSON(\"replSetGetStatus\" << 1), response)) {\n \/\/ A replica set has been configured.\n for (mongo::BSONElement const & member : response[\"members\"].Array()) {\n result.push_back(member[\"name\"].String());\n }\n\n } else {\n \/\/ Single node configuration.\n result.push_back(node_uri);\n }\n\n return result;\n}\n\nvoid mongodb_facade::remove(const std::string & alias)\n{\n CHECK_ERROR(remove, _conn, NAMESPACE, MONGO_QUERY(\"_id\" << alias), true, NULL);\n}\n\nvoid mongodb_facade::blob_put(const std::string & alias, const std::string & content)\n{\n CHECK_ERROR(insert, _conn, NAMESPACE, BSON(\"_id\" << alias << \"content\" << content));\n}\n\nvoid mongodb_facade::blob_update(const std::string & alias, const std::string & content)\n{\n CHECK_ERROR(findAndModify, _conn, NAMESPACE, BSON(\"_id\" << alias), BSON(\"content\" << content),\n false, true);\n}\n\nstd::string mongodb_facade::blob_get(const std::string & alias)\n{\n CHECK_ERROR_STORE(query, _conn, cursor, NAMESPACE, MONGO_QUERY(\"_id\" << alias));\n\n return cursor->next().getField(\"content\").String();\n}\n\nvoid mongodb_facade::int_put(const std::string & alias, std::int64_t value)\n{\n CHECK_ERROR(insert, _conn, NAMESPACE,\n BSON(\"_id\" << alias << \"num\" << static_cast(value)));\n}\n\nstd::int64_t mongodb_facade::int_add(const std::string & alias, std::int64_t value)\n{\n CHECK_ERROR_STORE(findAndModify, _conn, obj, NAMESPACE, BSON(\"_id\" << alias),\n BSON(\"$inc\" << BSON(\"num\" << static_cast(value))), false, true);\n\n return obj.getField(\"num\").Long();\n}\nMake MongoDB sync to Journal, like quasardb does.#include \n#include \n#include \n#include \n\n#define NAMESPACE \"bench.objects\"\n\n\/\/ Calls MongoDB function, checks for error and discards result\n#define CHECK_ERROR(func, conn, ...) \\\n conn.func(__VA_ARGS__); \\\n \\\n std::string error = conn.getLastError(); \\\n if (error != \"\") throw std::runtime_error(#func + error);\n\n\/\/ Calls MongoDB function, checks for error and store result in `result`\n#define CHECK_ERROR_STORE(func, conn, result, ...) \\\n auto result = conn.func(__VA_ARGS__); \\\n \\\n std::string error = conn.getLastError(); \\\n if (error != \"\") throw std::runtime_error(#func + error);\n\nusing namespace bench::tests::mongodb;\n\nmongodb_facade::mongodb_facade()\n{\n}\n\nmongodb_facade::~mongodb_facade()\n{\n}\n\nvoid mongodb_facade::connect(const std::string & cluster_uri)\n{\n _conn.connect(cluster_uri);\n}\n\n\/* static *\/ mongo::BSONObj mongodb_facade::server_status(const std::string & node_uri)\n{\n mongo::DBClientConnection conn;\n conn.connect(node_uri);\n\n mongo::BSONObj serverStatus;\n\n if (!conn.runCommand(\"bench\", BSON(\"serverStatus\" << 1), serverStatus))\n {\n throw std::runtime_error(\"node_status: serverStatus\");\n }\n\n return BSON(\"server\" << serverStatus << \"db\" << mongodb_facade::db_status(node_uri));\n}\n\n\/* static *\/ mongo::BSONObj mongodb_facade::db_status(const std::string & node_uri)\n{\n mongo::DBClientConnection conn;\n conn.connect(node_uri);\n\n mongo::BSONObj dbStats;\n if (!conn.runCommand(\"bench\", BSON(\"dbStats\" << 1), dbStats))\n {\n throw std::runtime_error(\"node_status: dbStats\");\n }\n\n return dbStats;\n}\n\n\/* static *\/ std::vector mongodb_facade::resolve_topology(const std::string & node_uri)\n{\n mongo::DBClientConnection conn;\n conn.connect(node_uri);\n\n \/*\n Our `node_uri` can be any of the following:\n\n * an entry to a `mongos` instance, a sharded cluster;\n * an entry to a replica set;\n * a single node configuration.\n\n We are going to probe for what kind of configuration we are\n dealing with by executing the relevant admin commands, and\n based on those responses resolve the entire topology.\n *\/\n\n mongo::BSONObj response;\n\n std::vector result;\n\n if (conn.runCommand(\"admin\", BSON(\"listShards\" << 1), response))\n {\n \/\/ We are in sharded cluster.\n\n for (mongo::BSONElement const & member : response[\"shards\"].Array())\n {\n \/\/ Member can be either a replica set, which looks like\n \/\/ `rs0\/1.2.3.4:1234,4.3.2.1:4321`, or it is a regular\n \/\/ host, which looks like `1.2.3.4:1234`.\n std::string host = member[\"host\"].String();\n\n std::vector tokens;\n boost::split(tokens, host, boost::is_any_of(\"\/\"));\n\n if (tokens.size() == 1)\n {\n \/\/ A regular host\n result.push_back(tokens.at(0));\n }\n else if (tokens.size() == 2)\n {\n std::vector hosts;\n\n boost::split(hosts, tokens.at(1), boost::is_any_of(\",\"));\n\n std::copy(hosts.begin(), hosts.end(), std::back_insert_iterator>(result));\n }\n else\n {\n throw std::runtime_error(\"Invalid host: \" + host);\n }\n }\n }\n else if (conn.runCommand(\"admin\", BSON(\"replSetGetStatus\" << 1), response))\n {\n \/\/ A replica set has been configured.\n for (mongo::BSONElement const & member : response[\"members\"].Array())\n {\n result.push_back(member[\"name\"].String());\n }\n }\n else\n {\n \/\/ Single node configuration.\n result.push_back(node_uri);\n }\n\n return result;\n}\n\nvoid mongodb_facade::remove(const std::string & alias)\n{\n CHECK_ERROR(remove, _conn, NAMESPACE, MONGO_QUERY(\"_id\" << alias), 0, &mongo::WriteConcern::journaled);\n}\n\nvoid mongodb_facade::blob_put(const std::string & alias, const std::string & content)\n{\n CHECK_ERROR(insert, _conn, NAMESPACE, BSON(\"_id\" << alias << \"content\" << content), 0,\n &mongo::WriteConcern::journaled);\n}\n\nvoid mongodb_facade::blob_update(const std::string & alias, const std::string & content)\n{\n CHECK_ERROR(findAndModify, _conn, NAMESPACE, BSON(\"_id\" << alias), BSON(\"content\" << content), false, true,\n mongo::BSONObj(), mongo::BSONObj(), &mongo::WriteConcern::journaled);\n}\n\nstd::string mongodb_facade::blob_get(const std::string & alias)\n{\n CHECK_ERROR_STORE(query, _conn, cursor, NAMESPACE, MONGO_QUERY(\"_id\" << alias));\n\n return cursor->next().getField(\"content\").String();\n}\n\nvoid mongodb_facade::int_put(const std::string & alias, std::int64_t value)\n{\n CHECK_ERROR(insert, _conn, NAMESPACE, BSON(\"_id\" << alias << \"num\" << static_cast(value)), 0,\n &mongo::WriteConcern::journaled);\n}\n\nstd::int64_t mongodb_facade::int_add(const std::string & alias, std::int64_t value)\n{\n CHECK_ERROR_STORE(findAndModify, _conn, obj, NAMESPACE, BSON(\"_id\" << alias),\n BSON(\"$inc\" << BSON(\"num\" << static_cast(value))), false, true, mongo::BSONObj(),\n mongo::BSONObj(), &mongo::WriteConcern::journaled);\n\n return obj.getField(\"num\").Long();\n}\n<|endoftext|>"} {"text":"#include \"pacmanplugin.h\"\n\n#include \n#include \n\nPacmanPlugin::PacmanPlugin(QObject *parent) :\n\tPackageManagerPlugin(parent)\n{\n\n}\n\n\nvoid PacmanPlugin::initialize()\n{\n}\n\nQList PacmanPlugin::extraFilters()\n{\n\tQList list;\n\tlist.append({QStringLiteral(\"&Explicitly installed\"), QStringLiteral(\"Only explicitly installed packages\"), false});\n\tlist.append({QStringLiteral(\"&Leaf packages\"), QStringLiteral(\"Only leaf packages\"), false});\n\tlist.append({QStringLiteral(\"&AUR packages only\"), QStringLiteral(\"\"), true});\n\tlist.append({QStringLiteral(\"&Native packages only\"), QStringLiteral(\"\"), true});\n\treturn list;\n}\n\nQStringList PacmanPlugin::listAllPackages()\n{\/\/pacman -Qq\n\n}\n\nQStringList PacmanPlugin::listPackages(QVector extraFilters)\n{\n\tif(extraFilters[2] && extraFilters[3])\n\t\treturn {};\n\n\tauto queryString = QStringLiteral(\"-Qq\");\n\n\tif(extraFilters[0])\n\t\tqueryString += QLatin1Char('e');\n\tif(extraFilters[1])\n\t\tqueryString += QLatin1Char('t');\n\tif(extraFilters[2])\n\t\tqueryString += QLatin1Char('m');\n\tif(extraFilters[3])\n\t\tqueryString += QLatin1Char('n');\n\n\tQProcess p;\n\tp.start(QStringLiteral(\"pacman\"), {queryString});\n\tif(!p.waitForFinished(5000))\n\t\treturn {};\n\n\tauto list = QString::fromUtf8(p.readAll()).split(QStringLiteral(\"\\n\"), QString::SkipEmptyParts);\n\tqDebug() << list;\n\treturn list;\n}\n\nQString PacmanPlugin::installationCmd(const QStringList &packages)\n{\n}\n\nQString PacmanPlugin::uninstallationCmd(const QStringList &packages)\n{\n}\n\nbool PacmanPlugin::startGuiInstall(const QStringList &packages)\n{\n}\n\nbool PacmanPlugin::startGuiUninstall(const QStringList &packages)\n{\n}\n\nQList PacmanPlugin::listSettings()\n{\n}\npacmanplugin wip#include \"pacmanplugin.h\"\n\n#include \n#include \n\nPacmanPlugin::PacmanPlugin(QObject *parent) :\n\tPackageManagerPlugin(parent)\n{\n\n}\n\n\nvoid PacmanPlugin::initialize()\n{\n}\n\nQList PacmanPlugin::extraFilters()\n{\n\tQList list;\n\tlist.append({QStringLiteral(\"&Explicitly installed\"), QStringLiteral(\"Only explicitly installed packages\"), false});\n\tlist.append({QStringLiteral(\"&Leaf packages\"), QStringLiteral(\"Only leaf packages\"), false});\n\tlist.append({QStringLiteral(\"&AUR packages only\"), QStringLiteral(\"\"), false});\n\tlist.append({QStringLiteral(\"&Native packages only\"), QStringLiteral(\"\"), false});\n\treturn list;\n}\n\nQStringList PacmanPlugin::listAllPackages()\n{\/\/pacman -Qq\n\treturn listPackages({false, false, false, false});\n}\n\nQStringList PacmanPlugin::listPackages(QVector extraFilters)\n{\n\tif(extraFilters[2] && extraFilters[3])\n\t\treturn {};\n\n\tauto queryString = QStringLiteral(\"-Qq\");\n\n\tif(extraFilters[0])\n\t\tqueryString += QLatin1Char('e');\n\tif(extraFilters[1])\n\t\tqueryString += QLatin1Char('t');\n\tif(extraFilters[2])\n\t\tqueryString += QLatin1Char('m');\n\tif(extraFilters[3])\n\t\tqueryString += QLatin1Char('n');\n\n\tQProcess p;\n\tp.start(QStringLiteral(\"pacman\"), {queryString});\n\tif(!p.waitForFinished(5000))\n\t\treturn {};\n\n\tauto list = QString::fromUtf8(p.readAll()).split(QStringLiteral(\"\\n\"), QString::SkipEmptyParts);\n\tqDebug() << list;\n\treturn list;\n}\n\nQString PacmanPlugin::installationCmd(const QStringList &packages)\n{\n}\n\nQString PacmanPlugin::uninstallationCmd(const QStringList &packages)\n{\n}\n\nbool PacmanPlugin::startGuiInstall(const QStringList &packages)\n{\n}\n\nbool PacmanPlugin::startGuiUninstall(const QStringList &packages)\n{\n}\n\nQList PacmanPlugin::listSettings()\n{\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2007, 2008 libmv authors.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include \n#include \n#include \n\n#include \"libmv\/image\/array_nd.h\"\n#include \"libmv\/image\/surf.h\"\n#include \"libmv\/image\/surf_descriptor.h\"\n#include \"libmv\/multiview\/projection.h\"\n#include \"libmv\/multiview\/fundamental.h\"\n#include \"libmv\/multiview\/focal_from_fundamental.h\"\n#include \"libmv\/multiview\/nviewtriangulation.h\"\n#include \"libmv\/logging\/logging.h\"\n#include \"ui\/tvr\/main_window.h\"\n\n\nTvrMainWindow::TvrMainWindow(QWidget *parent)\n : QMainWindow(parent) {\n\n viewer2d_ = new MatchViewer();\n viewer3d_ = new Viewer3D();\n setCentralWidget(viewer2d_);\n current_view_ = view2d;\n\n CreateActions();\n CreateMenus();\n}\n\nTvrMainWindow::~TvrMainWindow() {\n}\n\nvoid TvrMainWindow::CreateActions() {\n open_images_action_ = new QAction(tr(\"&Open Images...\"), this);\n open_images_action_->setShortcut(tr(\"Ctrl+O\"));\n open_images_action_->setStatusTip(tr(\"Open an image pair\"));\n connect(open_images_action_, SIGNAL(triggered()),\n this, SLOT(OpenImages()));\n\n toggle_view_action_ = new QAction(tr(\"&Toggle View\"), this);\n toggle_view_action_->setShortcut(tr(\"TAB\"));\n toggle_view_action_->setStatusTip(tr(\"Toggle between 2D and 3D\"));\n connect(toggle_view_action_, SIGNAL(triggered()),\n this, SLOT(ToggleView()));\n\n save_blender_action_ = new QAction(tr(\"&Save as Blender...\"), this);\n save_blender_action_->setShortcut(tr(\"Ctrl+S\"));\n save_blender_action_->setStatusTip(tr(\"Save Scene as a Blender Script\"));\n connect(save_blender_action_, SIGNAL(triggered()),\n this, SLOT(SaveBlender()));\n \n\n compute_features_action_ = new QAction(tr(\"&Compute Features\"), this);\n compute_features_action_->setStatusTip(tr(\"Compute Surf Features\"));\n connect(compute_features_action_, SIGNAL(triggered()),\n this, SLOT(ComputeFeatures()));\n \n compute_candidate_matches_action_ =\n new QAction(tr(\"&Compute Candidate Matches\"), this);\n compute_candidate_matches_action_->setStatusTip(\n tr(\"Compute Candidate Matches\"));\n connect(compute_candidate_matches_action_, SIGNAL(triggered()),\n this, SLOT(ComputeCandidateMatches()));\n \n compute_robust_matches_action_ = new QAction(tr(\"&Compute Robust Matches\"),\n this);\n compute_robust_matches_action_->setStatusTip(tr(\"Compute Robust Matches\"));\n connect(compute_robust_matches_action_, SIGNAL(triggered()),\n this, SLOT(ComputeRobustMatches()));\n\n focal_from_fundamental_action_ = new QAction(tr(\"&Focal from Fundamental\"),\n this);\n focal_from_fundamental_action_->setStatusTip(\n tr(\"Compute Focal Distance from the Fundamental MatrixRobust Matrix\"));\n connect(focal_from_fundamental_action_, SIGNAL(triggered()),\n this, SLOT(FocalFromFundamental()));\n\n metric_reconstruction_action_ = new QAction(tr(\"&Metric Reconstruction\"), this);\n metric_reconstruction_action_->setStatusTip(tr(\n \"Compute a metric reconstrution given the current focal length estimates\"));\n connect(metric_reconstruction_action_, SIGNAL(triggered()),\n this, SLOT(MetricReconstruction()));\n}\n\nvoid TvrMainWindow::CreateMenus() {\n file_menu_ = menuBar()->addMenu(tr(\"&File\"));\n file_menu_->addAction(open_images_action_);\n file_menu_->addAction(save_blender_action_);\n view_menu_ = menuBar()->addMenu(tr(\"&View\"));\n view_menu_->addAction(toggle_view_action_);\n matching_menu_ = menuBar()->addMenu(tr(\"&Matching\"));\n matching_menu_->addAction(compute_features_action_);\n matching_menu_->addAction(compute_candidate_matches_action_);\n matching_menu_->addAction(compute_robust_matches_action_);\n calibration_menu_ = menuBar()->addMenu(tr(\"&Calibration\"));\n calibration_menu_->addAction(focal_from_fundamental_action_);\n calibration_menu_->addAction(metric_reconstruction_action_);\n}\n\nvoid TvrMainWindow::OpenImages() {\n QStringList filenames = QFileDialog::getOpenFileNames(this,\n \"Select Two Images\", \"\", \"Image Files (*.png *.jpg *.bmp *.ppm *.pgm *.xpm)\");\n\n if (filenames.size() == 2) {\n for (int i = 0; i < 2; ++i) {\n document_.images[i].load(filenames[i]);\n }\n viewer2d_->SetDocument(&document_);\n viewer3d_->SetDocument(&document_);\n } else if (filenames.size() != 0) {\n QMessageBox::information(this, tr(\"TVR\"),\n tr(\"Please select 2 images.\"));\n OpenImages();\n }\n}\n\nvoid TvrMainWindow::SaveBlender() {\n QString filename = QFileDialog::getSaveFileName(this,\n \"Save as Blender Script\", \"\", \"Blender Python Script (*.py)\");\n if(filename.isNull())\n return;\n document_.SaveAsBlender(filename.toAscii().data());\n}\n\nvoid TvrMainWindow::ToggleView() {\n if(current_view_ == view2d) {\n setCentralWidget(viewer3d_);\n current_view_ = view3d;\n } else {\n setCentralWidget(viewer2d_);\n current_view_ = view2d;\n }\n}\n\nvoid TvrMainWindow::ComputeFeatures() {\n for (int i = 0; i < 2; ++i) {\n ComputeFeatures(i);\n }\n}\n \nvoid TvrMainWindow::ComputeFeatures(int image_index) {\n QImage &qimage = document_.images[image_index];\n int width = qimage.width(), height = qimage.height();\n SurfFeatureSet &fs = document_.feature_sets[image_index];\n \n \/\/ Convert to gray-scale.\n \/\/ TODO(keir): Make a libmv image <-> QImage interop library inside libmv for\n \/\/ easy bidirectional exchange of images between Qt and libmv.\n libmv::Array3Df image(height, width, 1);\n for (int y = 0; y < height; ++y) {\n for (int x = 0; x < width; ++x) {\n \/\/ TODO(pau): there are better ways to compute intensity.\n \/\/ Implement one and put it on libmv\/image.\n int depth = qimage.depth() \/ 8;\n image(y, x) = 0;\n for (int c = 0; c < depth; ++c) {\n if (c != 3) { \/\/ Skip alpha channel for RGBA.\n image(y, x) = float(qimage.bits()[depth*(y * width + x) + c]);\n }\n }\n image(y, x) \/= depth == 4 ? 3 : depth;\n }\n }\n libmv::SurfFeatures(image, 3, 4, &fs.features);\n\n \/\/ Build the kd-tree.\n fs.tree.Build(&fs.features[0], fs.features.size(), 64, 10);\n\n viewer2d_->updateGL();\n}\n\nvoid TvrMainWindow::ComputeCandidateMatches() {\n FindCandidateMatches(document_.feature_sets[0],\n document_.feature_sets[1],\n &document_.correspondences);\n viewer2d_->updateGL();\n}\n\nvoid TvrMainWindow::ComputeRobustMatches() {\n libmv::Correspondences new_correspondences;\n\n ComputeFundamental(document_.correspondences,\n &document_.F, &new_correspondences);\n \n \/\/ TODO(pau) Make sure this is not copying too many things. We could\n \/\/ implement an efficient swap for the biparted graph (just swaping\n \/\/ the maps), or remove outlier tracks from the candidate matches\n \/\/ instead of constructing a new correspondance set.\n std::swap(document_.correspondences, new_correspondences);\n viewer2d_->updateGL();\n}\n\nvoid TvrMainWindow::FocalFromFundamental() {\n libmv::Vec2 p0((document_.images[0].width() - 1) \/ 2.,\n (document_.images[0].height() - 1) \/ 2.);\n libmv::Vec2 p1((document_.images[1].width() - 1) \/ 2.,\n (document_.images[1].height() - 1) \/ 2.);\n libmv::FocalFromFundamental(document_.F, p0, p1,\n &document_.focal_distance[0],\n &document_.focal_distance[1]);\n\n LOG(INFO) << \"focal 0: \" << document_.focal_distance[0]\n << \" focal 1: \" << document_.focal_distance[1] << \"\\n\";\n\n viewer2d_->updateGL();\n}\n\nvoid TvrMainWindow::MetricReconstruction() {\n using namespace libmv;\n\n Vec2 p0((document_.images[0].width() - 1) \/ 2.,\n (document_.images[0].height() - 1) \/ 2.);\n Vec2 p1((document_.images[1].width() - 1) \/ 2.,\n (document_.images[1].height() - 1) \/ 2.);\n double f0 = document_.focal_distance[0];\n double f1 = document_.focal_distance[1];\n Mat3 K0, K1;\n K0 << f0, 0, p0(0),\n 0, f0, p0(1),\n 0, 0, 1;\n K1 << f1, 0, p1(0),\n 0, f1, p1(1),\n 0, 0, 1;\n \n \/\/ Compute essential matrix\n Mat3 E;\n EssentialFromFundamental(document_.F, K0, K1, &E);\n\n \/\/ Get one match from the corresponcence structure.\n Vec2 x[2];\n {\n Correspondences::TrackIterator t =\n document_.correspondences.ScanAllTracks();\n PointCorrespondences::Iterator it =\n PointCorrespondences(&document_.correspondences)\n .ScanFeaturesForTrack(t.track());\n x[it.image()](0) = it.feature()->x();\n x[it.image()](1) = it.feature()->y();\n it.Next();\n x[it.image()](0) = it.feature()->x();\n x[it.image()](1) = it.feature()->y();\n }\n\n \/\/ Recover R, t from E and K\n Mat3 R;\n Vec3 t;\n MotionFromEssentialAndCorrespondence(E, K0, x[0], K1, x[1], &R, &t);\n\n LOG(INFO) << \"R:\\n\" << R << \"\\nt:\\n\" << t;\n\n document_.K[0] = K0;\n document_.R[0] = Mat3::Identity();\n document_.t[0] = Vec3::Zero();\n document_.K[1] = K1;\n document_.R[1] = R;\n document_.t[1] = t;\n\n \/\/ Triangulate features.\n {\n std::vector Ps(2);\n P_From_KRt(document_.K[0], document_.R[0], document_.t[0], &Ps[0]);\n P_From_KRt(document_.K[1], document_.R[1], document_.t[1], &Ps[1]);\n int n = document_.correspondences.NumTracks();\n document_.X.resize(n);\n int i = 0;\n for (Correspondences::TrackIterator t =\n document_.correspondences.ScanAllTracks(); !t.Done(); t.Next()) {\n PointCorrespondences::Iterator it =\n PointCorrespondences(&document_.correspondences)\n .ScanFeaturesForTrack(t.track());\n Mat2X x(2, 2);\n Vec4 X;\n x(0, it.image()) = it.feature()->x();\n x(1, it.image()) = it.feature()->y();\n it.Next();\n x(0, it.image()) = it.feature()->x();\n x(1, it.image()) = it.feature()->y();\n NViewTriangulate(x, Ps, &X);\n X \/= X(3);\n document_.X[i] = X.start<3>();\n i++;\n }\n }\n}\nFixed segfault on changing view in tvr.\/\/ Copyright (c) 2007, 2008 libmv authors.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\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\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include \n#include \n#include \n\n#include \"libmv\/image\/array_nd.h\"\n#include \"libmv\/image\/surf.h\"\n#include \"libmv\/image\/surf_descriptor.h\"\n#include \"libmv\/multiview\/projection.h\"\n#include \"libmv\/multiview\/fundamental.h\"\n#include \"libmv\/multiview\/focal_from_fundamental.h\"\n#include \"libmv\/multiview\/nviewtriangulation.h\"\n#include \"libmv\/logging\/logging.h\"\n#include \"ui\/tvr\/main_window.h\"\n\n\nTvrMainWindow::TvrMainWindow(QWidget *parent)\n : QMainWindow(parent) {\n\n viewer2d_ = new MatchViewer();\n setCentralWidget(viewer2d_);\n current_view_ = view2d;\n\n CreateActions();\n CreateMenus();\n}\n\nTvrMainWindow::~TvrMainWindow() {\n}\n\nvoid TvrMainWindow::CreateActions() {\n open_images_action_ = new QAction(tr(\"&Open Images...\"), this);\n open_images_action_->setShortcut(tr(\"Ctrl+O\"));\n open_images_action_->setStatusTip(tr(\"Open an image pair\"));\n connect(open_images_action_, SIGNAL(triggered()),\n this, SLOT(OpenImages()));\n\n toggle_view_action_ = new QAction(tr(\"&Toggle View\"), this);\n toggle_view_action_->setShortcut(tr(\"TAB\"));\n toggle_view_action_->setStatusTip(tr(\"Toggle between 2D and 3D\"));\n connect(toggle_view_action_, SIGNAL(triggered()),\n this, SLOT(ToggleView()));\n\n save_blender_action_ = new QAction(tr(\"&Save as Blender...\"), this);\n save_blender_action_->setShortcut(tr(\"Ctrl+S\"));\n save_blender_action_->setStatusTip(tr(\"Save Scene as a Blender Script\"));\n connect(save_blender_action_, SIGNAL(triggered()),\n this, SLOT(SaveBlender()));\n \n\n compute_features_action_ = new QAction(tr(\"&Compute Features\"), this);\n compute_features_action_->setStatusTip(tr(\"Compute Surf Features\"));\n connect(compute_features_action_, SIGNAL(triggered()),\n this, SLOT(ComputeFeatures()));\n \n compute_candidate_matches_action_ =\n new QAction(tr(\"&Compute Candidate Matches\"), this);\n compute_candidate_matches_action_->setStatusTip(\n tr(\"Compute Candidate Matches\"));\n connect(compute_candidate_matches_action_, SIGNAL(triggered()),\n this, SLOT(ComputeCandidateMatches()));\n \n compute_robust_matches_action_ = new QAction(tr(\"&Compute Robust Matches\"),\n this);\n compute_robust_matches_action_->setStatusTip(tr(\"Compute Robust Matches\"));\n connect(compute_robust_matches_action_, SIGNAL(triggered()),\n this, SLOT(ComputeRobustMatches()));\n\n focal_from_fundamental_action_ = new QAction(tr(\"&Focal from Fundamental\"),\n this);\n focal_from_fundamental_action_->setStatusTip(\n tr(\"Compute Focal Distance from the Fundamental MatrixRobust Matrix\"));\n connect(focal_from_fundamental_action_, SIGNAL(triggered()),\n this, SLOT(FocalFromFundamental()));\n\n metric_reconstruction_action_ = new QAction(tr(\"&Metric Reconstruction\"), this);\n metric_reconstruction_action_->setStatusTip(tr(\n \"Compute a metric reconstrution given the current focal length estimates\"));\n connect(metric_reconstruction_action_, SIGNAL(triggered()),\n this, SLOT(MetricReconstruction()));\n}\n\nvoid TvrMainWindow::CreateMenus() {\n file_menu_ = menuBar()->addMenu(tr(\"&File\"));\n file_menu_->addAction(open_images_action_);\n file_menu_->addAction(save_blender_action_);\n view_menu_ = menuBar()->addMenu(tr(\"&View\"));\n view_menu_->addAction(toggle_view_action_);\n matching_menu_ = menuBar()->addMenu(tr(\"&Matching\"));\n matching_menu_->addAction(compute_features_action_);\n matching_menu_->addAction(compute_candidate_matches_action_);\n matching_menu_->addAction(compute_robust_matches_action_);\n calibration_menu_ = menuBar()->addMenu(tr(\"&Calibration\"));\n calibration_menu_->addAction(focal_from_fundamental_action_);\n calibration_menu_->addAction(metric_reconstruction_action_);\n}\n\nvoid TvrMainWindow::OpenImages() {\n QStringList filenames = QFileDialog::getOpenFileNames(this,\n \"Select Two Images\", \"\", \"Image Files (*.png *.jpg *.bmp *.ppm *.pgm *.xpm)\");\n\n if (filenames.size() == 2) {\n for (int i = 0; i < 2; ++i) {\n document_.images[i].load(filenames[i]);\n }\n if(current_view_ != view2d)\n ToggleView();\n viewer2d_->SetDocument(&document_);\n } else if (filenames.size() != 0) {\n QMessageBox::information(this, tr(\"TVR\"),\n tr(\"Please select 2 images.\"));\n OpenImages();\n }\n}\n\nvoid TvrMainWindow::SaveBlender() {\n QString filename = QFileDialog::getSaveFileName(this,\n \"Save as Blender Script\", \"\", \"Blender Python Script (*.py)\");\n if(filename.isNull())\n return;\n document_.SaveAsBlender(filename.toAscii().data());\n}\n\nvoid TvrMainWindow::ToggleView() {\n if(current_view_ == view2d) {\n viewer3d_ = new Viewer3D();\n viewer3d_->SetDocument(&document_);\n setCentralWidget(viewer3d_);\n current_view_ = view3d;\n } else {\n viewer2d_ = new MatchViewer();\n viewer2d_->SetDocument(&document_);\n setCentralWidget(viewer2d_);\n current_view_ = view2d;\n }\n}\n\nvoid TvrMainWindow::ComputeFeatures() {\n for (int i = 0; i < 2; ++i) {\n ComputeFeatures(i);\n }\n}\n \nvoid TvrMainWindow::ComputeFeatures(int image_index) {\n QImage &qimage = document_.images[image_index];\n int width = qimage.width(), height = qimage.height();\n SurfFeatureSet &fs = document_.feature_sets[image_index];\n \n \/\/ Convert to gray-scale.\n \/\/ TODO(keir): Make a libmv image <-> QImage interop library inside libmv for\n \/\/ easy bidirectional exchange of images between Qt and libmv.\n libmv::Array3Df image(height, width, 1);\n for (int y = 0; y < height; ++y) {\n for (int x = 0; x < width; ++x) {\n \/\/ TODO(pau): there are better ways to compute intensity.\n \/\/ Implement one and put it on libmv\/image.\n int depth = qimage.depth() \/ 8;\n image(y, x) = 0;\n for (int c = 0; c < depth; ++c) {\n if (c != 3) { \/\/ Skip alpha channel for RGBA.\n image(y, x) = float(qimage.bits()[depth*(y * width + x) + c]);\n }\n }\n image(y, x) \/= depth == 4 ? 3 : depth;\n }\n }\n libmv::SurfFeatures(image, 3, 4, &fs.features);\n\n \/\/ Build the kd-tree.\n fs.tree.Build(&fs.features[0], fs.features.size(), 64, 10);\n\n viewer2d_->updateGL();\n}\n\nvoid TvrMainWindow::ComputeCandidateMatches() {\n FindCandidateMatches(document_.feature_sets[0],\n document_.feature_sets[1],\n &document_.correspondences);\n viewer2d_->updateGL();\n}\n\nvoid TvrMainWindow::ComputeRobustMatches() {\n libmv::Correspondences new_correspondences;\n\n ComputeFundamental(document_.correspondences,\n &document_.F, &new_correspondences);\n \n \/\/ TODO(pau) Make sure this is not copying too many things. We could\n \/\/ implement an efficient swap for the biparted graph (just swaping\n \/\/ the maps), or remove outlier tracks from the candidate matches\n \/\/ instead of constructing a new correspondance set.\n std::swap(document_.correspondences, new_correspondences);\n viewer2d_->updateGL();\n}\n\nvoid TvrMainWindow::FocalFromFundamental() {\n libmv::Vec2 p0((document_.images[0].width() - 1) \/ 2.,\n (document_.images[0].height() - 1) \/ 2.);\n libmv::Vec2 p1((document_.images[1].width() - 1) \/ 2.,\n (document_.images[1].height() - 1) \/ 2.);\n libmv::FocalFromFundamental(document_.F, p0, p1,\n &document_.focal_distance[0],\n &document_.focal_distance[1]);\n\n LOG(INFO) << \"focal 0: \" << document_.focal_distance[0]\n << \" focal 1: \" << document_.focal_distance[1] << \"\\n\";\n\n viewer2d_->updateGL();\n}\n\nvoid TvrMainWindow::MetricReconstruction() {\n using namespace libmv;\n\n Vec2 p0((document_.images[0].width() - 1) \/ 2.,\n (document_.images[0].height() - 1) \/ 2.);\n Vec2 p1((document_.images[1].width() - 1) \/ 2.,\n (document_.images[1].height() - 1) \/ 2.);\n double f0 = document_.focal_distance[0];\n double f1 = document_.focal_distance[1];\n Mat3 K0, K1;\n K0 << f0, 0, p0(0),\n 0, f0, p0(1),\n 0, 0, 1;\n K1 << f1, 0, p1(0),\n 0, f1, p1(1),\n 0, 0, 1;\n \n \/\/ Compute essential matrix\n Mat3 E;\n EssentialFromFundamental(document_.F, K0, K1, &E);\n\n \/\/ Get one match from the corresponcence structure.\n Vec2 x[2];\n {\n Correspondences::TrackIterator t =\n document_.correspondences.ScanAllTracks();\n PointCorrespondences::Iterator it =\n PointCorrespondences(&document_.correspondences)\n .ScanFeaturesForTrack(t.track());\n x[it.image()](0) = it.feature()->x();\n x[it.image()](1) = it.feature()->y();\n it.Next();\n x[it.image()](0) = it.feature()->x();\n x[it.image()](1) = it.feature()->y();\n }\n\n \/\/ Recover R, t from E and K\n Mat3 R;\n Vec3 t;\n MotionFromEssentialAndCorrespondence(E, K0, x[0], K1, x[1], &R, &t);\n\n LOG(INFO) << \"R:\\n\" << R << \"\\nt:\\n\" << t;\n\n document_.K[0] = K0;\n document_.R[0] = Mat3::Identity();\n document_.t[0] = Vec3::Zero();\n document_.K[1] = K1;\n document_.R[1] = R;\n document_.t[1] = t;\n\n \/\/ Triangulate features.\n {\n std::vector Ps(2);\n P_From_KRt(document_.K[0], document_.R[0], document_.t[0], &Ps[0]);\n P_From_KRt(document_.K[1], document_.R[1], document_.t[1], &Ps[1]);\n int n = document_.correspondences.NumTracks();\n document_.X.resize(n);\n int i = 0;\n for (Correspondences::TrackIterator t =\n document_.correspondences.ScanAllTracks(); !t.Done(); t.Next()) {\n PointCorrespondences::Iterator it =\n PointCorrespondences(&document_.correspondences)\n .ScanFeaturesForTrack(t.track());\n Mat2X x(2, 2);\n Vec4 X;\n x(0, it.image()) = it.feature()->x();\n x(1, it.image()) = it.feature()->y();\n it.Next();\n x(0, it.image()) = it.feature()->x();\n x(1, it.image()) = it.feature()->y();\n NViewTriangulate(x, Ps, &X);\n X \/= X(3);\n document_.X[i] = X.start<3>();\n i++;\n }\n }\n}\n<|endoftext|>"} {"text":"#ifndef __EXTENSION_EXPLICIT_COUNTERSTRATEGY_HPP\n#define __EXTENSION_EXPLICIT_COUNTERSTRATEGY_HPP\n\n#include \"gr1context.hpp\"\n#include \n\n\/**\n * A class that computes an explicit state counterstrategy for an unrealizable specification\n *\/\ntemplate class XExtractExplicitCounterStrategy : public T {\nprotected:\n \/\/ New variables\n std::string outputFilename;\n\n \/\/ Inherited stuff used\n using T::mgr;\n using T::strategyDumpingData;\n using T::livenessGuarantees;\n using T::livenessAssumptions;\n using T::varVectorPre;\n using T::varVectorPost;\n using T::varCubePostOutput;\n using T::varCubePostInput;\n using T::varCubePreOutput;\n using T::varCubePreInput;\n using T::varCubePre;\n using T::varCubePost;\n using T::safetyEnv;\n using T::safetySys;\n using T::winningPositions;\n using T::initEnv;\n using T::initSys;\n using T::preVars;\n using T::postVars;\n using T::variableTypes;\n using T::variables;\n using T::variableNames;\n using T::realizable;\n using T::determinize;\n using T::postInputVars;\n using T::postOutputVars;\n using T::doesVariableInheritType;\n\n XExtractExplicitCounterStrategy(std::list &filenames) : T(filenames) {\n if (filenames.size()==1) {\n outputFilename = \"\";\n } else {\n outputFilename = filenames.front();\n filenames.pop_front();\n }\n }\n\npublic:\n\n\/**\n * @brief Compute and print out (to stdout) an explicit-state counter strategy that is winning for\n * the environment. The output is compatible with the old JTLV output of LTLMoP.\n * This function requires that the unrealizability of the specification has already been\n * detected and that the variables \"strategyDumpingData\" and\n * \"winningPositions\" have been filled by the synthesis algorithm with meaningful data.\n * @param outputStream - Where the strategy shall be printed to.\n *\/\nvoid execute() {\n T::execute();\n if (!realizable) {\n if (outputFilename==\"\") {\n computeAndPrintExplicitStateStrategy(std::cout);\n } else {\n std::ofstream of(outputFilename.c_str());\n if (of.fail()) {\n SlugsException ex(false);\n ex << \"Error: Could not open output file'\" << outputFilename << \"\\n\";\n throw ex;\n }\n computeAndPrintExplicitStateStrategy(of);\n if (of.fail()) {\n SlugsException ex(false);\n ex << \"Error: Writing to output file'\" << outputFilename << \"failed. \\n\";\n throw ex;\n }\n of.close();\n }\n }\n}\n\n \nvoid computeAndPrintExplicitStateStrategy(std::ostream &outputStream) {\n\n \/\/ We don't want any reordering from this point onwards, as\n \/\/ the BDD manipulations from this point onwards are 'kind of simple'.\n mgr.setAutomaticOptimisation(false);\n\n \/\/ List of states in existance so far. The first map\n \/\/ maps from a BF node pointer (for the pre variable valuation) and a goal\n \/\/ to a state number. The vector then contains the concrete valuation.\n std::map >, unsigned int > lookupTableForPastStates;\n std::vector bfsUsedInTheLookupTable;\n std::list > > todoList;\n\n \n \/\/ Prepare positional strategies for the individual goals\n std::vector > positionalStrategiesForTheIndividualGoals(livenessAssumptions.size());\n for (unsigned int i=0;i strategy(livenessGuarantees.size()+1);\n for (unsigned int j=0;j(*it) == i) {\n \/\/Have to cover each guarantee (since the winning strategy depends on which guarantee is being pursued)\n \/\/Essentially, the choice of which guarantee to pursue can be thought of as a system \"move\".\n \/\/The environment always to chooses that prevent the appropriate guarantee.\n strategy[boost::get<1>(*it)] |= boost::get<2>(*it).UnivAbstract(varCubePostOutput) & !(strategy[boost::get<1>(*it)].ExistAbstract(varCubePost));\n }\n }\n positionalStrategiesForTheIndividualGoals[i] = strategy;\n }\n \n \/\/ Prepare initial to-do list from the allowed initial states. Select a single initial input valuation.\n\n \/\/ TODO: Support for non-special-robotics semantics\n BF todoInit = (winningPositions & initEnv & initSys);\n while (!(todoInit.isFalse())) {\n BF concreteState = determinize(todoInit,preVars);\n \n \/\/find which liveness guarantee is being prevented (finds the first liveness in order specified)\n \/\/ Note by Ruediger here: Removed \"!livenessGuarantees[j]\" as condition as it is non-positional\n unsigned int found_j_index = 0;\n for (unsigned int j=0;j > lookup = std::pair >(concreteState.getHashCode(),std::pair(0,found_j_index));\n lookupTableForPastStates[lookup] = bfsUsedInTheLookupTable.size();\n bfsUsedInTheLookupTable.push_back(concreteState);\n \/\/from now on use the same initial input valuation (but consider all other initial output valuations)\n todoInit &= !concreteState;\n todoList.push_back(lookup);\n }\n\n \/\/ Extract strategy\n while (todoList.size()>0) {\n std::pair > current = todoList.front();\n todoList.pop_front();\n unsigned int stateNum = lookupTableForPastStates[current];\n BF currentPossibilities = bfsUsedInTheLookupTable[stateNum];\n \/\/ Print state information\n outputStream << \"State \" << stateNum << \" with rank (\" << current.second.first << \",\" << current.second.second << \") -> <\";\n bool first = true;\n for (unsigned int i=0;i\\n\\tWith successors : \";\n first = true;\n\n \/\/ Can we enforce a deadlock?\n BF deadlockInput = (currentPossibilities & safetyEnv & !safetySys).UnivAbstract(varCubePostOutput);\n if (deadlockInput!=mgr.constantFalse()) {\n addDeadlocked(deadlockInput, current, bfsUsedInTheLookupTable, lookupTableForPastStates, outputStream);\n } else {\n\n \/\/ No deadlock in sight -> Jump to a different liveness guarantee if necessary.\n while ((currentPossibilities & positionalStrategiesForTheIndividualGoals[current.second.first][current.second.second])==mgr.constantFalse()) current.second.second = (current.second.second + 1) % livenessGuarantees.size();\n currentPossibilities &= positionalStrategiesForTheIndividualGoals[current.second.first][current.second.second];\n assert(currentPossibilities != mgr.constantFalse());\n BF remainingTransitions = currentPossibilities;\n\n \/\/ Choose one next input and stick to it!\n remainingTransitions = determinize(remainingTransitions,postInputVars);\n\n \/\/ Switching goals\n while (!(remainingTransitions & safetySys).isFalse()) {\n\n BF safeTransition = remainingTransitions & safetySys;\n BF newCombination = determinize(safeTransition, postOutputVars);\n\n \/\/ Jump as much forward in the liveness assumption list as possible (\"stuttering avoidance\")\n unsigned int nextLivenessAssumption = current.second.first;\n bool firstTry = true;\n while (((nextLivenessAssumption != current.second.first) | firstTry) && !((livenessAssumptions[nextLivenessAssumption] & newCombination).isFalse())) {\n nextLivenessAssumption = (nextLivenessAssumption + 1) % livenessAssumptions.size();\n firstTry = false;\n }\n\n \/\/Mark which input has been captured by this case. Use the same input for other successors\n remainingTransitions &= !newCombination;\n\n \/\/ We don't need the pre information from the point onwards anymore.\n newCombination = newCombination.ExistAbstract(varCubePre).SwapVariables(varVectorPre,varVectorPost);\n\n unsigned int tn;\n\n std::pair > target;\n\n target = std::pair >(newCombination.getHashCode(),std::pair(nextLivenessAssumption, current.second.second));\n\n if (lookupTableForPastStates.count(target)==0) {\n tn = lookupTableForPastStates[target] = bfsUsedInTheLookupTable.size();\n bfsUsedInTheLookupTable.push_back(newCombination);\n todoList.push_back(target);\n } else {\n tn = lookupTableForPastStates[target];\n }\n\n \/\/ Print\n if (first) {\n first = false;\n } else {\n outputStream << \", \";\n }\n outputStream << tn;\n\n }\n }\n\n outputStream << \"\\n\";\n }\n }\n\n\n \/\/This function adds a new successor-less \"state\" that captures the deadlock-causing input values\n \/\/The outputvalues are omitted (indeed, no valuation exists that satisfies the system safeties)\n \/\/Format compatible with JTLV counterstrategy\n\n void addDeadlocked(BF targetPositionCandidateSet, std::pair > current, std::vector &bfsUsedInTheLookupTable, std::map >, unsigned int > &lookupTableForPastStates, std::ostream &outputStream) {\n \n BF newCombination = determinize(targetPositionCandidateSet, postVars) ;\n \n newCombination = (newCombination.ExistAbstract(varCubePostOutput).ExistAbstract(varCubePre)).SwapVariables(varVectorPre,varVectorPost);\n \n std::pair > target = std::pair >(newCombination.getHashCode(),std::pair(current.second.first, current.second.second));\n unsigned int tn;\n \n if (lookupTableForPastStates.count(target)==0) {\n tn = lookupTableForPastStates[target] = bfsUsedInTheLookupTable.size();\n bfsUsedInTheLookupTable.push_back(newCombination); \n outputStream << tn << \"\\n\";\n \n \/\/Note that since we are printing here, we usually end up with the states being printed out of order.\n \/\/TOTO: print in order\n outputStream << \"State \" << tn << \" with rank (\" << current.second.first << \",\" << current.second.second << \") -> <\";\n bool first = true;\n for (unsigned int i=0;i\\n\\tWith no successors.\";\n \n } else {\n tn = lookupTableForPastStates[target];\n outputStream << tn;\n }\n \n}\n\n\n static GR1Context* makeInstance(std::list &filenames) {\n return new XExtractExplicitCounterStrategy(filenames);\n }\n};\n\n#endif\n\ncounterstrategy for transition goals -- fixes #10#ifndef __EXTENSION_EXPLICIT_COUNTERSTRATEGY_HPP\n#define __EXTENSION_EXPLICIT_COUNTERSTRATEGY_HPP\n\n#include \"gr1context.hpp\"\n#include \n\n\/**\n * A class that computes an explicit state counterstrategy for an unrealizable specification\n *\/\ntemplate class XExtractExplicitCounterStrategy : public T {\nprotected:\n \/\/ New variables\n std::string outputFilename;\n\n \/\/ Inherited stuff used\n using T::mgr;\n using T::strategyDumpingData;\n using T::livenessGuarantees;\n using T::livenessAssumptions;\n using T::varVectorPre;\n using T::varVectorPost;\n using T::varCubePostOutput;\n using T::varCubePostInput;\n using T::varCubePreOutput;\n using T::varCubePreInput;\n using T::varCubePre;\n using T::varCubePost;\n using T::safetyEnv;\n using T::safetySys;\n using T::winningPositions;\n using T::initEnv;\n using T::initSys;\n using T::preVars;\n using T::postVars;\n using T::variableTypes;\n using T::variables;\n using T::variableNames;\n using T::realizable;\n using T::determinize;\n using T::postInputVars;\n using T::postOutputVars;\n using T::doesVariableInheritType;\n\n XExtractExplicitCounterStrategy(std::list &filenames) : T(filenames) {\n if (filenames.size()==1) {\n outputFilename = \"\";\n } else {\n outputFilename = filenames.front();\n filenames.pop_front();\n }\n }\n\npublic:\n\n\/**\n * @brief Compute and print out (to stdout) an explicit-state counter strategy that is winning for\n * the environment. The output is compatible with the old JTLV output of LTLMoP.\n * This function requires that the unrealizability of the specification has already been\n * detected and that the variables \"strategyDumpingData\" and\n * \"winningPositions\" have been filled by the synthesis algorithm with meaningful data.\n * @param outputStream - Where the strategy shall be printed to.\n *\/\nvoid execute() {\n T::execute();\n if (!realizable) {\n if (outputFilename==\"\") {\n computeAndPrintExplicitStateStrategy(std::cout);\n } else {\n std::ofstream of(outputFilename.c_str());\n if (of.fail()) {\n SlugsException ex(false);\n ex << \"Error: Could not open output file'\" << outputFilename << \"\\n\";\n throw ex;\n }\n computeAndPrintExplicitStateStrategy(of);\n if (of.fail()) {\n SlugsException ex(false);\n ex << \"Error: Writing to output file'\" << outputFilename << \"failed. \\n\";\n throw ex;\n }\n of.close();\n }\n }\n}\n\n \nvoid computeAndPrintExplicitStateStrategy(std::ostream &outputStream) {\n\n \/\/ We don't want any reordering from this point onwards, as\n \/\/ the BDD manipulations from this point onwards are 'kind of simple'.\n mgr.setAutomaticOptimisation(false);\n\n \/\/ List of states in existance so far. The first map\n \/\/ maps from a BF node pointer (for the pre variable valuation) and a goal\n \/\/ to a state number. The vector then contains the concrete valuation.\n std::map >, unsigned int > lookupTableForPastStates;\n std::vector bfsUsedInTheLookupTable;\n std::list > > todoList;\n\n \n \/\/ Prepare positional strategies for the individual goals\n std::vector > positionalStrategiesForTheIndividualGoals(livenessAssumptions.size());\n for (unsigned int i=0;i strategy(livenessGuarantees.size()+1);\n for (unsigned int j=0;j(*it) == i) {\n \/\/Have to cover each guarantee (since the winning strategy depends on which guarantee is being pursued)\n \/\/Essentially, the choice of which guarantee to pursue can be thought of as a system \"move\".\n \/\/The environment always to chooses that prevent the appropriate guarantee.\n strategy[boost::get<1>(*it)] |= boost::get<2>(*it).UnivAbstract(varCubePostOutput) & !(strategy[boost::get<1>(*it)].ExistAbstract(varCubePost));\n }\n }\n positionalStrategiesForTheIndividualGoals[i] = strategy;\n }\n \n \/\/ Prepare initial to-do list from the allowed initial states. Select a single initial input valuation.\n\n \/\/ TODO: Support for non-special-robotics semantics\n BF todoInit = (winningPositions & initEnv & initSys);\n while (!(todoInit.isFalse())) {\n BF concreteState = determinize(todoInit,preVars);\n \n \/\/find which liveness guarantee is being prevented (finds the first liveness in order specified)\n \/\/ Note by Ruediger here: Removed \"!livenessGuarantees[j]\" as condition as it is non-positional\n unsigned int found_j_index = 0;\n for (unsigned int j=0;j > lookup = std::pair >(concreteState.getHashCode(),std::pair(0,found_j_index));\n lookupTableForPastStates[lookup] = bfsUsedInTheLookupTable.size();\n bfsUsedInTheLookupTable.push_back(concreteState);\n \/\/from now on use the same initial input valuation (but consider all other initial output valuations)\n todoInit &= !concreteState;\n todoList.push_back(lookup);\n }\n\n \/\/ Extract strategy\n while (todoList.size()>0) {\n std::pair > current = todoList.front();\n todoList.pop_front();\n unsigned int stateNum = lookupTableForPastStates[current];\n BF currentPossibilities = bfsUsedInTheLookupTable[stateNum];\n \/\/ Print state information\n outputStream << \"State \" << stateNum << \" with rank (\" << current.second.first << \",\" << current.second.second << \") -> <\";\n bool first = true;\n for (unsigned int i=0;i\\n\\tWith successors : \";\n first = true;\n\n \/\/ Can we enforce a deadlock?\n BF deadlockInput = (currentPossibilities & safetyEnv & !safetySys).UnivAbstract(varCubePostOutput);\n if (deadlockInput!=mgr.constantFalse()) {\n addDeadlocked(deadlockInput, current, bfsUsedInTheLookupTable, lookupTableForPastStates, outputStream);\n } else {\n\n \/\/ No deadlock in sight -> Jump to a different liveness guarantee if necessary.\n while ((currentPossibilities & positionalStrategiesForTheIndividualGoals[current.second.first][current.second.second])==mgr.constantFalse()) current.second.second = (current.second.second + 1) % livenessGuarantees.size();\n currentPossibilities &= positionalStrategiesForTheIndividualGoals[current.second.first][current.second.second];\n assert(currentPossibilities != mgr.constantFalse());\n BF remainingTransitions = currentPossibilities;\n\n \/\/ Choose one next input and stick to it!\n if (!((remainingTransitions & ! livenessGuarantees[current.second.second]).isFalse())) {\n\t remainingTransitions = remainingTransitions & ! livenessGuarantees[current.second.second];\n\t }\n\t remainingTransitions = determinize(remainingTransitions,postInputVars);\n\n \/\/ Switching goals\n while (!(remainingTransitions & safetySys).isFalse()) {\n\n BF safeTransition = remainingTransitions & safetySys;\n BF newCombination = determinize(safeTransition, postOutputVars);\n\n \/\/ Jump as much forward in the liveness assumption list as possible (\"stuttering avoidance\")\n unsigned int nextLivenessAssumption = current.second.first;\n bool firstTry = true;\n while (((nextLivenessAssumption != current.second.first) | firstTry) && !((livenessAssumptions[nextLivenessAssumption] & newCombination).isFalse())) {\n nextLivenessAssumption = (nextLivenessAssumption + 1) % livenessAssumptions.size();\n firstTry = false;\n }\n\n \/\/Mark which input has been captured by this case. Use the same input for other successors\n remainingTransitions &= !newCombination;\n\n \/\/ We don't need the pre information from the point onwards anymore.\n newCombination = newCombination.ExistAbstract(varCubePre).SwapVariables(varVectorPre,varVectorPost);\n\n unsigned int tn;\n\n std::pair > target;\n\n target = std::pair >(newCombination.getHashCode(),std::pair(nextLivenessAssumption, current.second.second));\n\n if (lookupTableForPastStates.count(target)==0) {\n tn = lookupTableForPastStates[target] = bfsUsedInTheLookupTable.size();\n bfsUsedInTheLookupTable.push_back(newCombination);\n todoList.push_back(target);\n } else {\n tn = lookupTableForPastStates[target];\n }\n\n \/\/ Print\n if (first) {\n first = false;\n } else {\n outputStream << \", \";\n }\n outputStream << tn;\n\n }\n }\n\n outputStream << \"\\n\";\n }\n }\n\n\n \/\/This function adds a new successor-less \"state\" that captures the deadlock-causing input values\n \/\/The outputvalues are omitted (indeed, no valuation exists that satisfies the system safeties)\n \/\/Format compatible with JTLV counterstrategy\n\n void addDeadlocked(BF targetPositionCandidateSet, std::pair > current, std::vector &bfsUsedInTheLookupTable, std::map >, unsigned int > &lookupTableForPastStates, std::ostream &outputStream) {\n \n BF newCombination = determinize(targetPositionCandidateSet, postVars) ;\n \n newCombination = (newCombination.ExistAbstract(varCubePostOutput).ExistAbstract(varCubePre)).SwapVariables(varVectorPre,varVectorPost);\n \n std::pair > target = std::pair >(newCombination.getHashCode(),std::pair(current.second.first, current.second.second));\n unsigned int tn;\n \n if (lookupTableForPastStates.count(target)==0) {\n tn = lookupTableForPastStates[target] = bfsUsedInTheLookupTable.size();\n bfsUsedInTheLookupTable.push_back(newCombination); \n outputStream << tn << \"\\n\";\n \n \/\/Note that since we are printing here, we usually end up with the states being printed out of order.\n \/\/TOTO: print in order\n outputStream << \"State \" << tn << \" with rank (\" << current.second.first << \",\" << current.second.second << \") -> <\";\n bool first = true;\n for (unsigned int i=0;i\\n\\tWith no successors.\";\n \n } else {\n tn = lookupTableForPastStates[target];\n outputStream << tn;\n }\n \n}\n\n\n static GR1Context* makeInstance(std::list &filenames) {\n return new XExtractExplicitCounterStrategy(filenames);\n }\n};\n\n#endif\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"core\/Halite.hpp\"\n\ninline std::istream & operator>>(std::istream & i, std::pair & p) {\n i >> p.first >> p.second;\n return i;\n}\ninline std::ostream & operator<<(std::ostream & o, const std::pair & p) {\n o << p.first << ' ' << p.second;\n return o;\n}\nnamespace TCLAP {\ntemplate<> struct ArgTraits< std::pair > {\n typedef TCLAP::ValueLike ValueCategory;\n};\n}\n\nbool quiet_output = false; \/\/Need to be passed to a bunch of classes; extern is cleaner.\nHalite * my_game; \/\/Is a pointer to avoid problems with assignment, dynamic memory, and default constructors.\n\nNetworking promptNetworking();\nvoid promptDimensions(unsigned short & w, unsigned short & h);\n\nint main(int argc, char ** argv) {\n srand(time(NULL)); \/\/For all non-seeded randomness.\n\n if(argc == 1) {\n std::cout << \"You've provided the environment with no arguments.\\n\"\n << \"If this was intentional, please ignore this message.\\n\"\n << \"Else, please use the -h (--help) flag for usage details.\\n\";\n }\n \n Networking networking;\n std::vector * names = NULL;\n unsigned int id = std::chrono::duration_cast(std::chrono::high_resolution_clock().now().time_since_epoch()).count();\n\n TCLAP::CmdLine cmd(\"Halite Game Environment\", ' ', \"1.0\");\n\n \/\/Switch Args.\n TCLAP::SwitchArg quietSwitch(\"q\", \"quiet\", \"Runs game in quiet mode, producing machine-parsable output.\", cmd, false);\n TCLAP::SwitchArg overrideSwitch(\"o\", \"override\", \"Overrides player-sent names using cmd args [SERVER ONLY].\", cmd, false);\n TCLAP::SwitchArg timeoutSwitch(\"t\", \"timeout\", \"Causes game environment to ignore timeouts (give all bots infinite time).\", cmd, false);\n\n \/\/Value Args\n TCLAP::ValueArg< std::pair > dimensionArgs(\"d\", \"dimensions\", \"The dimensions of the map.\", false, { 0, 0 }, \"a string containing two space-seprated positive integers\", cmd);\n TCLAP::ValueArg seedArg(\"s\", \"seed\", \"The seed for the map generator.\", false, 0, \"positive integer\", cmd);\n\n \/\/Remaining Args, be they start commands and\/or override names. Description only includes start commands since it will only be seen on local testing.\n TCLAP::UnlabeledMultiArg otherArgs(\"NonspecifiedArgs\", \"Start commands for bots.\", false, \"Array of strings\", cmd);\n\n cmd.parse(argc, argv);\n\n unsigned short mapWidth = dimensionArgs.getValue().first;\n unsigned short mapHeight = dimensionArgs.getValue().second;\n\n unsigned int seed;\n if(seedArg.getValue() != 0) seed = seedArg.getValue();\n else seed = (std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() % 4294967295);\n\n quiet_output = quietSwitch.getValue();\n bool override_names = overrideSwitch.getValue();\n bool ignore_timeout = timeoutSwitch.getValue();\n\n std::vector unlabeledArgsVector = otherArgs.getValue();\n std::list unlabeledArgs;\n for(auto a = unlabeledArgsVector.begin(); a != unlabeledArgsVector.end(); a++) {\n unlabeledArgs.push_back(*a);\n }\n\n if(mapWidth == 0 && mapHeight == 0) {\n promptDimensions(mapWidth, mapHeight);\n }\n\n if(override_names) {\n if(unlabeledArgs.size() < 4 || unlabeledArgs.size() % 2 != 0) {\n std::cout << \"Invalid player parameters from argv. Prompting instead (override disabled):\" << std::endl;\n networking = promptNetworking();\n }\n else {\n try {\n names = new std::vector();\n while(!unlabeledArgs.empty()) {\n networking.startAndConnectBot(unlabeledArgs.front());\n unlabeledArgs.pop_front();\n names->push_back(unlabeledArgs.front());\n unlabeledArgs.pop_front();\n }\n }\n catch(...) {\n std::cout << \"Invalid player parameters from argv. Prompting instead (override disabled):\" << std::endl;\n networking = promptNetworking();\n delete names;\n names = NULL;\n }\n }\n }\n else {\n if(unlabeledArgs.size() < 2) {\n std::cout << \"Invalid player parameters from argv. Prompting instead:\" << std::endl;\n networking = promptNetworking();\n }\n try {\n while(!unlabeledArgs.empty()) {\n std::cout << unlabeledArgs.front() << std::endl;\n networking.startAndConnectBot(unlabeledArgs.front());\n unlabeledArgs.pop_front();\n }\n }\n catch(...) {\n std::cout << \"Invalid player parameters from argv. Prompting instead:\" << std::endl;\n networking = promptNetworking();\n }\n }\n\n \/\/Create game. Null parameters will be ignored.\n my_game = new Halite(mapWidth, mapHeight, seed, networking, ignore_timeout);\n\n GameStatistics stats = my_game->runGame(names, seed, id);\n if(names != NULL) delete names;\n\n std::string victoryOut;\n if(quiet_output) {\n std::cout << stats;\n }\n else {\n for(unsigned int a = 0; a < stats.player_statistics.size(); a++) std::cout << \"Player #\" << stats.player_statistics[a].tag << \", \" << my_game->getName(stats.player_statistics[a].tag) << \", came in rank #\" << stats.player_statistics[a].rank << \"!\\n\";\n }\n\n delete my_game;\n\n return 0;\n}\n\nNetworking promptNetworking() {\n Networking n;\n std::string in;\n bool done = false;\n for(int np = 0; !done; np++) {\n \/\/If less than 2, bypass this step: Ask if the user like to add another AI\n if (np >= 2) {\n std::cout << \"Would you like to add another player? Please enter Yes or No: \";\n while (true) {\n std::getline(std::cin, in);\n std::transform(in.begin(), in.end(), in.begin(), ::tolower);\n if (in == \"n\" || in == \"no\" || in == \"nope\" || in == \"y\" || in == \"yes\" || in == \"yep\") break;\n std::cout << \"That isn't a valid input. Please enter Yes or No: \";\n }\n if (in == \"n\" || in == \"no\" || in == \"nope\") break;\n }\n\n while (true) {\n std::string startCommand;\n std::cout << \"What is the start command for this bot: \";\n std::getline(std::cin, startCommand);\n\n try{\n n.startAndConnectBot(startCommand);\n break;\n }\n catch (int e) {\n std::cout << \"There was a problem with that start command. Please enter another one.\\n\";\n }\n }\n\n std::cout << \"Connected to player #\" << int(np + 1) << std::endl;\n }\n return n;\n}\n\nvoid promptDimensions(unsigned short & w, unsigned short & h) {\n std::string in;\n std::cout << \"Please enter the width of the map: \";\n std::getline(std::cin, in);\n while(true) {\n try{\n w = std::stoi(in);\n break;\n }\n catch(std::exception e) {\n std::cout << \"That isn't a valid input. Please enter a positive integer width of the map: \";\n std::getline(std::cin, in);\n }\n }\n std::cout << \"Please enter the height of the map: \";\n std::getline(std::cin, in);\n while(true) {\n try{\n h = std::stoi(in);\n break;\n }\n catch(std::exception e) {\n std::cout << \"That isn't a valid input. Please enter a positive integer height of the map: \";\n std::getline(std::cin, in);\n }\n }\n}\nMinor change to env docs#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"core\/Halite.hpp\"\n\ninline std::istream & operator>>(std::istream & i, std::pair & p) {\n i >> p.first >> p.second;\n return i;\n}\ninline std::ostream & operator<<(std::ostream & o, const std::pair & p) {\n o << p.first << ' ' << p.second;\n return o;\n}\nnamespace TCLAP {\ntemplate<> struct ArgTraits< std::pair > {\n typedef TCLAP::ValueLike ValueCategory;\n};\n}\n\nbool quiet_output = false; \/\/Need to be passed to a bunch of classes; extern is cleaner.\nHalite * my_game; \/\/Is a pointer to avoid problems with assignment, dynamic memory, and default constructors.\n\nNetworking promptNetworking();\nvoid promptDimensions(unsigned short & w, unsigned short & h);\n\nint main(int argc, char ** argv) {\n srand(time(NULL)); \/\/For all non-seeded randomness.\n\n if(argc == 1) {\n std::cout << \"You've provided the environment with no arguments.\\n\"\n << \"If this was intentional, please ignore this message.\\n\"\n << \"Else, please use the --help flag for usage details.\\n\";\n }\n \n Networking networking;\n std::vector * names = NULL;\n unsigned int id = std::chrono::duration_cast(std::chrono::high_resolution_clock().now().time_since_epoch()).count();\n\n TCLAP::CmdLine cmd(\"Halite Game Environment\", ' ', \"1.0.1\");\n\n \/\/Switch Args.\n TCLAP::SwitchArg quietSwitch(\"q\", \"quiet\", \"Runs game in quiet mode, producing machine-parsable output.\", cmd, false);\n TCLAP::SwitchArg overrideSwitch(\"o\", \"override\", \"Overrides player-sent names using cmd args [SERVER ONLY].\", cmd, false);\n TCLAP::SwitchArg timeoutSwitch(\"t\", \"timeout\", \"Causes game environment to ignore timeouts (give all bots infinite time).\", cmd, false);\n\n \/\/Value Args\n TCLAP::ValueArg< std::pair > dimensionArgs(\"d\", \"dimensions\", \"The dimensions of the map.\", false, { 0, 0 }, \"a string containing two space-seprated positive integers\", cmd);\n TCLAP::ValueArg seedArg(\"s\", \"seed\", \"The seed for the map generator.\", false, 0, \"positive integer\", cmd);\n\n \/\/Remaining Args, be they start commands and\/or override names. Description only includes start commands since it will only be seen on local testing.\n TCLAP::UnlabeledMultiArg otherArgs(\"NonspecifiedArgs\", \"Start commands for bots.\", false, \"Array of strings\", cmd);\n\n cmd.parse(argc, argv);\n\n unsigned short mapWidth = dimensionArgs.getValue().first;\n unsigned short mapHeight = dimensionArgs.getValue().second;\n\n unsigned int seed;\n if(seedArg.getValue() != 0) seed = seedArg.getValue();\n else seed = (std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() % 4294967295);\n\n quiet_output = quietSwitch.getValue();\n bool override_names = overrideSwitch.getValue();\n bool ignore_timeout = timeoutSwitch.getValue();\n\n std::vector unlabeledArgsVector = otherArgs.getValue();\n std::list unlabeledArgs;\n for(auto a = unlabeledArgsVector.begin(); a != unlabeledArgsVector.end(); a++) {\n unlabeledArgs.push_back(*a);\n }\n\n if(mapWidth == 0 && mapHeight == 0) {\n promptDimensions(mapWidth, mapHeight);\n }\n\n if(override_names) {\n if(unlabeledArgs.size() < 4 || unlabeledArgs.size() % 2 != 0) {\n std::cout << \"Invalid player parameters from argv. Prompting instead (override disabled):\" << std::endl;\n networking = promptNetworking();\n }\n else {\n try {\n names = new std::vector();\n while(!unlabeledArgs.empty()) {\n networking.startAndConnectBot(unlabeledArgs.front());\n unlabeledArgs.pop_front();\n names->push_back(unlabeledArgs.front());\n unlabeledArgs.pop_front();\n }\n }\n catch(...) {\n std::cout << \"Invalid player parameters from argv. Prompting instead (override disabled):\" << std::endl;\n networking = promptNetworking();\n delete names;\n names = NULL;\n }\n }\n }\n else {\n if(unlabeledArgs.size() < 2) {\n std::cout << \"Invalid player parameters from argv. Prompting instead:\" << std::endl;\n networking = promptNetworking();\n }\n try {\n while(!unlabeledArgs.empty()) {\n std::cout << unlabeledArgs.front() << std::endl;\n networking.startAndConnectBot(unlabeledArgs.front());\n unlabeledArgs.pop_front();\n }\n }\n catch(...) {\n std::cout << \"Invalid player parameters from argv. Prompting instead:\" << std::endl;\n networking = promptNetworking();\n }\n }\n\n \/\/Create game. Null parameters will be ignored.\n my_game = new Halite(mapWidth, mapHeight, seed, networking, ignore_timeout);\n\n GameStatistics stats = my_game->runGame(names, seed, id);\n if(names != NULL) delete names;\n\n std::string victoryOut;\n if(quiet_output) {\n std::cout << stats;\n }\n else {\n for(unsigned int a = 0; a < stats.player_statistics.size(); a++) std::cout << \"Player #\" << stats.player_statistics[a].tag << \", \" << my_game->getName(stats.player_statistics[a].tag) << \", came in rank #\" << stats.player_statistics[a].rank << \"!\\n\";\n }\n\n delete my_game;\n\n return 0;\n}\n\nNetworking promptNetworking() {\n Networking n;\n std::string in;\n bool done = false;\n for(int np = 0; !done; np++) {\n \/\/If less than 2, bypass this step: Ask if the user like to add another AI\n if (np >= 2) {\n std::cout << \"Would you like to add another player? Please enter Yes or No: \";\n while (true) {\n std::getline(std::cin, in);\n std::transform(in.begin(), in.end(), in.begin(), ::tolower);\n if (in == \"n\" || in == \"no\" || in == \"nope\" || in == \"y\" || in == \"yes\" || in == \"yep\") break;\n std::cout << \"That isn't a valid input. Please enter Yes or No: \";\n }\n if (in == \"n\" || in == \"no\" || in == \"nope\") break;\n }\n\n while (true) {\n std::string startCommand;\n std::cout << \"What is the start command for this bot: \";\n std::getline(std::cin, startCommand);\n\n try{\n n.startAndConnectBot(startCommand);\n break;\n }\n catch (int e) {\n std::cout << \"There was a problem with that start command. Please enter another one.\\n\";\n }\n }\n\n std::cout << \"Connected to player #\" << int(np + 1) << std::endl;\n }\n return n;\n}\n\nvoid promptDimensions(unsigned short & w, unsigned short & h) {\n std::string in;\n std::cout << \"Please enter the width of the map: \";\n std::getline(std::cin, in);\n while(true) {\n try{\n w = std::stoi(in);\n break;\n }\n catch(std::exception e) {\n std::cout << \"That isn't a valid input. Please enter a positive integer width of the map: \";\n std::getline(std::cin, in);\n }\n }\n std::cout << \"Please enter the height of the map: \";\n std::getline(std::cin, in);\n while(true) {\n try{\n h = std::stoi(in);\n break;\n }\n catch(std::exception e) {\n std::cout << \"That isn't a valid input. Please enter a positive integer height of the map: \";\n std::getline(std::cin, in);\n }\n }\n}\n<|endoftext|>"} {"text":"Disable tap to click by default<|endoftext|>"} {"text":"\/\/ @(#)root\/reflex:$Id$\n\/\/ Author: Stefan Roiser 2006\n\n\/\/ Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.\n\/\/\n\/\/ Permission to use, copy, modify, and distribute this software for any\n\/\/ purpose is hereby granted without fee, provided that this copyright and\n\/\/ permissions notice appear in all copies and derivatives.\n\/\/\n\/\/ This software is provided \"as is\" without express or implied warranty.\n\n#ifndef REFLEX_BUILD\n#define REFLEX_BUILD\n#endif\n\n#include \"NameLookup.h\"\n#include \"Reflex\/Base.h\"\n#include \"Reflex\/Scope.h\"\n#include \"Reflex\/Type.h\"\n#include \"Reflex\/Tools.h\"\n#include \"Reflex\/internal\/OwnedMember.h\"\n\n#include \n#include \n\n\/\/______________________________________________________________________________\nReflex::NameLookup::NameLookup(const std::string& name, const Scope& current):\n fLookupName(name), fPosNamePart(0), fPosNamePartLen(std::string::npos),\n fCurrentScope(current), fPartialSuccess(false)\n{\n \/\/ Initialize a NameLookup object used internally to keep track of lookup\n \/\/ states.\n}\n\n\/\/______________________________________________________________________________\nReflex::Type Reflex::NameLookup::LookupType(const std::string& nam, const Scope& current)\n{\n \/\/ Lookup up a (possibly scoped) type name appearing in the scope context\n \/\/ current. This is the public interface for type lookup.\n NameLookup lookup(nam, current);\n return lookup.Lookup();\n}\n\n\/\/______________________________________________________________________________\nReflex::Scope Reflex::NameLookup::LookupScope(const std::string& nam, const Scope& current)\n{\n \/\/ Lookup up a (possibly scoped) scope name appearing in the scope context\n \/\/ current. This is the public interface for scope lookup.\n NameLookup lookup(nam, current);\n return lookup.Lookup();\n}\n\n\/*\n\/\/______________________________________________________________________________\nReflex::Member LookupMember(const std::string& nam, const Scope& current )\n{\n \/\/ Lookup up a (possibly scoped) member name appearing in the scope context\n \/\/ current. This is the public interface for member lookup.\n NameLookup lookup(nam, current);\n \/\/ this will not work, member lookup is too different from type lookup...\n return lookup.Lookup();\n}\n*\/\n\n\/\/______________________________________________________________________________\ntemplate T Reflex::NameLookup::Lookup(bool isTemplateExpanded \/* = false *\/)\n{\n \/\/ Lookup a type using fLookupName, fCurrentScope.\n\n Scope startScope = fCurrentScope;\n T result;\n\n fPartialSuccess = false;\n fPosNamePart = 0;\n fPosNamePartLen = std::string::npos;\n FindNextScopePos();\n if (fPosNamePart == 2) {\n fLookedAtUsingDir.clear();\n \/\/ ::A...\n fCurrentScope = Scope::GlobalScope();\n result = LookupInScope();\n } else {\n \/\/ A...\n result = LookupInUnknownScope();\n }\n\n if (!isTemplateExpanded && !result && fLookupName.find('<') != std::string::npos) {\n\n \/\/ We need to replace the template argument both of this type\n \/\/ and any of it enclosing type:\n \/\/ myspace::mytop::mytype\n \n std::ostringstream tmp;\n for(size_t i = 0, level = 0, sofar = 0; i < fLookupName.size(); ++i) {\n if (level==0) {\n tmp << fLookupName.substr( sofar, i+1 - sofar );\n sofar = i+1;\n }\n switch( fLookupName[i] ) {\n case '<': ++level; break;\n case '>': --level; \/\/ intentional fall through to the ',' case\n case ',':\n if (level == (1 - (int)(fLookupName[i]=='>'))) {\n std::string arg( fLookupName.substr( sofar, i-sofar) );\n \n size_t p = arg.size();\n \n while (p > 0 && (arg[p-1] == '*' || arg[p-1] == '&'))\n --p;\n \n std::string end( arg.substr( p ) );\n arg.erase( p );\n\n const char *start = arg.c_str();\n while(strncmp(start,\"const \",6)==0) start+=6;\n\n tmp << arg.substr( 0, start - arg.c_str() );\n arg.erase(0, start - arg.c_str() ); \n\n Reflex::Type type( LookupType(arg , startScope ));\n\n if (type) {\n if (type.Name()!=\"Double32_t\" && type.Name()!=\"Float16_t\") {\n \/\/ Use the real type rather than the typedef unless\n \/\/ this is Double32_t or Float16_t\n type = type.FinalType();\n }\n tmp << type.Name(Reflex::SCOPED|Reflex::QUALIFIED);\n } else {\n tmp << arg;\n }\n tmp << end;\n \n tmp << fLookupName[i];\n\n sofar = i+1;\n } \n break;\n } \n }\n NameLookup next( tmp.str(), startScope );\n return next.Lookup(true);\n }\n\n\n return result;\n}\n\n\/\/______________________________________________________________________________\ntemplate T Reflex::NameLookup::LookupInScope()\n{\n \/\/ Lookup a type in fCurrentScope.\n \/\/ Checks sub-types, sub-scopes, using directives, and base classes for\n \/\/ the name given by fLookupName, fPosNamePart, and fPosNamePartLen.\n \/\/ If the name part is found, and another name part follows in fPosNamePart,\n \/\/ LookupTypeInScope requests the scope found to lookup the next name\n \/\/ part. fPartialMatch reflexts that the left part of the name was matched;\n \/\/ even if the trailing part of fLookupName cannot be found, the lookup\n \/\/ cannot continue on declaring scopes and has to fail.\n \/\/ A list of lookups performed in namespaces pulled in via using directives is\n \/\/ kept in fLookedAtUsingDir, to prevent infinite loops due to\n \/\/ namespace A{using namespace B;} namespace B{using namespace A;}\n \/\/ loops.\n \/\/ The lookup does not take the declaration order into account; the result of\n \/\/ parts of the lookup algorithm which depend on the order will be unpredictable.\n\n if (!fCurrentScope) {\n return Dummy::Get();\n }\n\n \/\/ prevent inf loop from\n \/\/ ns A { using ns B; } ns B {using ns A;}\n if (fLookedAtUsingDir.find(fCurrentScope) != fLookedAtUsingDir.end()) {\n return Dummy::Get();\n }\n\n int len = fCurrentScope.SubTypeSize();\n int i = 0;\n for (Type_Iterator it = fCurrentScope.SubType_Begin(); i < len; ++it, ++i) {\n const Type& type = *it;\n const TypeBase* base = type.ToTypeBase();\n if (base) {\n size_t pos;\n const std::string &name(base->SimpleName(pos));\n \/\/fprintf(stderr, \"Reflex::NameLookup::LookupInScope: looking up '%s', considering subscope '%s' ...\\n\", fLookupName.c_str(), name.c_str());\n if (\n (fLookupName[fPosNamePart] == name[pos]) &&\n !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length())\n ) {\n \/\/fprintf(stderr, \"Reflex::NameLookup::LookupInScope: lookup up '%s', partial success with subscope '%s' ...\\n\", fLookupName.c_str(), name.c_str());\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n if (fPosNamePart == std::string::npos) {\n return type;\n }\n if (it->IsTypedef()) {\n fCurrentScope = it->FinalType();\n }\n else {\n fCurrentScope = type;\n }\n return LookupInScope< T >();\n }\n }\n }\n\n Scope_Iterator subscope_end(fCurrentScope.SubScope_End());\n for (Scope_Iterator in = fCurrentScope.SubScope_Begin(); in != subscope_end; ++in) {\n \/\/ only take namespaces into account - classes were checked as part of SubType\n if (in->IsNamespace()) {\n const Scope& scope = *in;\n const ScopeBase* base = scope.ToScopeBase();\n if (base) {\n size_t pos;\n const std::string& name(base->SimpleName(pos));\n if (\n (fLookupName[fPosNamePart] == name[pos]) &&\n !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length())\n ) {\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n if (fPosNamePart == std::string::npos) {\n return (T) (*in);\n }\n fCurrentScope = (Scope) (*in);\n return LookupInScope();\n }\n }\n }\n }\n\n if (fCurrentScope.UsingDirectiveSize()) {\n fLookedAtUsingDir.insert(fCurrentScope);\n Scope storeCurrentScope = fCurrentScope;\n Scope_Iterator usingscope_end(storeCurrentScope.UsingDirective_End());\n for (Scope_Iterator si = storeCurrentScope.UsingDirective_Begin(); si != usingscope_end; ++si) {\n fCurrentScope = *si;\n T t = LookupInScope();\n if (fPartialSuccess) {\n return t;\n }\n }\n fCurrentScope = storeCurrentScope;\n }\n\n if (!fPosNamePart) { \/\/ only for \"BaseClass...\", not for \"A::BaseClass...\"\n Base_Iterator base_end(fCurrentScope.Base_End());\n for (Base_Iterator bi = fCurrentScope.Base_Begin(); bi != base_end; ++bi) {\n if (!fLookupName.compare(fPosNamePart, fPosNamePartLen, bi->Name())) {\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n if (fPosNamePart == std::string::npos) {\n return bi->ToType();\n }\n fCurrentScope = bi->ToType().FinalType();\n return LookupInScope< T >();\n }\n }\n }\n\n if (fCurrentScope.BaseSize()) {\n Scope storeCurrentScope = fCurrentScope;\n Base_Iterator base_end(storeCurrentScope.Base_End());\n for (Base_Iterator bi = storeCurrentScope.Base_Begin(); bi != base_end; ++bi) {\n fCurrentScope = bi->ToScope();\n T t = LookupInScope();\n if (fPartialSuccess) {\n return t;\n }\n }\n fCurrentScope = storeCurrentScope;\n }\n\n return Dummy::Get();\n}\n\n\/\/______________________________________________________________________________\ntemplate T Reflex::NameLookup::LookupInUnknownScope()\n{\n \/\/ Lookup a type in fCurrentScope and its declaring scopes.\n for (fPartialSuccess = false; !fPartialSuccess && fCurrentScope; fCurrentScope = fCurrentScope.DeclaringScope()) {\n fLookedAtUsingDir.clear();\n T t = LookupInScope();\n if (fPartialSuccess) {\n return t;\n }\n if (fCurrentScope.IsTopScope()) {\n break;\n }\n }\n return Dummy::Get();\n}\n\n\/\/______________________________________________________________________________\nReflex::Member Reflex::NameLookup::LookupMember(const std::string& nam, const Scope& current)\n{\n \/\/ Lookup a member.\n if (Tools::GetBasePosition(nam)) {\n return LookupMemberQualified(nam);\n }\n return LookupMemberUnqualified(nam, current);\n}\n\n\/\/______________________________________________________________________________\nReflex::Member Reflex::NameLookup::LookupMemberQualified(const std::string& nam)\n{\n \/\/ Lookup of a qualified member.\n Scope bscope = Scope::ByName(Tools::GetScopeName(nam));\n if (bscope) {\n return LookupMemberUnqualified(Tools::GetBaseName(nam), bscope);\n }\n return Dummy::Member();\n}\n\n\/\/______________________________________________________________________________\nReflex::Member Reflex::NameLookup::LookupMemberUnqualified(const std::string& nam, const Scope& current)\n{\n \/\/ Lookup of an unqualified member.\n {\n Member m = current.MemberByName(nam);\n if (m) {\n return m;\n }\n }\n for (Scope_Iterator si = current.UsingDirective_Begin(); si != current.UsingDirective_End(); ++si) {\n Member m = LookupMember(nam, *si);\n if (m) {\n return m;\n }\n }\n for (Base_Iterator bi = current.Base_Begin(); bi != current.Base_End(); ++bi) {\n Member m = LookupMember(nam, bi->ToScope());\n if (m) {\n return m;\n }\n }\n if (!current.IsTopScope()) {\n return LookupMember(nam, current.DeclaringScope());\n }\n return Dummy::Member();\n}\n\n\/\/______________________________________________________________________________\nReflex::Type Reflex::NameLookup::AccessControl(const Type& typ, const Scope& \/*current*\/)\n{\n \/\/ Check access.\n \/\/ if (typ.IsPublic()) {\n \/\/ return true;\n \/\/ }\n \/\/ else if (typ.IsProtected() && current.HasBase(typ.DeclaringScope())) {\n \/\/ return true;\n \/\/ }\n return typ;\n}\n\n\/\/______________________________________________________________________________\nvoid Reflex::NameLookup::FindNextScopePos()\n{\n \/\/ Move fPosNamePart to point to the next scope in fLookupName, updating\n \/\/ fPosNamePartLen. If fPosNamePartLen == std::string::npos, initialize\n \/\/ fPosNamePart and fPosNamePartLen. If there is no next scope left, fPosNamePart\n \/\/ will be set to std::string::npos and fPosNamePartLen will be set to 0.\n if (fPosNamePartLen != std::string::npos) {\n \/\/ we know the length, so jump\n fPosNamePart += fPosNamePartLen + 2;\n if (fPosNamePart > fLookupName.length()) {\n \/\/ past the string's end?\n fPosNamePart = std::string::npos;\n fPosNamePartLen = 0;\n return;\n }\n }\n else {\n \/\/ uninitialized\n \/\/ set fPosNamePartLen and check that fLookupName doesn't start with '::'\n fPosNamePart = 0;\n if (!fLookupName.compare(0, 2, \"::\")) {\n fPosNamePart = 2;\n }\n }\n fPosNamePartLen = Tools::GetFirstScopePosition(fLookupName.substr(fPosNamePart));\n if (!fPosNamePartLen) { \/\/ no next \"::\"\n fPosNamePartLen = fLookupName.length();\n }\n else { \/\/ no \"::\"\n fPosNamePartLen -= 2;\n }\n}\n\nFrom Paul and Philippe: In NameLookup when expanding template parameters, also _unconditionally_ strip the prefix std:: to match the fact that Cint(5) ignores it. With this updates, all ROOT dictionary should be properly generated and compiled. Now on to the bold frontier (roottest).\/\/ @(#)root\/reflex:$Id$\n\/\/ Author: Stefan Roiser 2006\n\n\/\/ Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.\n\/\/\n\/\/ Permission to use, copy, modify, and distribute this software for any\n\/\/ purpose is hereby granted without fee, provided that this copyright and\n\/\/ permissions notice appear in all copies and derivatives.\n\/\/\n\/\/ This software is provided \"as is\" without express or implied warranty.\n\n#ifndef REFLEX_BUILD\n#define REFLEX_BUILD\n#endif\n\n#include \"NameLookup.h\"\n#include \"Reflex\/Base.h\"\n#include \"Reflex\/Scope.h\"\n#include \"Reflex\/Type.h\"\n#include \"Reflex\/Tools.h\"\n#include \"Reflex\/internal\/OwnedMember.h\"\n\n#include \n#include \n\n\/\/______________________________________________________________________________\nReflex::NameLookup::NameLookup(const std::string& name, const Scope& current):\n fLookupName(name), fPosNamePart(0), fPosNamePartLen(std::string::npos),\n fCurrentScope(current), fPartialSuccess(false)\n{\n \/\/ Initialize a NameLookup object used internally to keep track of lookup\n \/\/ states.\n}\n\n\/\/______________________________________________________________________________\nReflex::Type Reflex::NameLookup::LookupType(const std::string& nam, const Scope& current)\n{\n \/\/ Lookup up a (possibly scoped) type name appearing in the scope context\n \/\/ current. This is the public interface for type lookup.\n NameLookup lookup(nam, current);\n return lookup.Lookup();\n}\n\n\/\/______________________________________________________________________________\nReflex::Scope Reflex::NameLookup::LookupScope(const std::string& nam, const Scope& current)\n{\n \/\/ Lookup up a (possibly scoped) scope name appearing in the scope context\n \/\/ current. This is the public interface for scope lookup.\n NameLookup lookup(nam, current);\n return lookup.Lookup();\n}\n\n\/*\n\/\/______________________________________________________________________________\nReflex::Member LookupMember(const std::string& nam, const Scope& current )\n{\n \/\/ Lookup up a (possibly scoped) member name appearing in the scope context\n \/\/ current. This is the public interface for member lookup.\n NameLookup lookup(nam, current);\n \/\/ this will not work, member lookup is too different from type lookup...\n return lookup.Lookup();\n}\n*\/\n\n\/\/______________________________________________________________________________\ntemplate T Reflex::NameLookup::Lookup(bool isTemplateExpanded \/* = false *\/)\n{\n \/\/ Lookup a type using fLookupName, fCurrentScope.\n\n Scope startScope = fCurrentScope;\n T result;\n\n fPartialSuccess = false;\n fPosNamePart = 0;\n fPosNamePartLen = std::string::npos;\n FindNextScopePos();\n if (fPosNamePart == 2) {\n fLookedAtUsingDir.clear();\n \/\/ ::A...\n fCurrentScope = Scope::GlobalScope();\n result = LookupInScope();\n } else {\n \/\/ A...\n result = LookupInUnknownScope();\n }\n\n if (!isTemplateExpanded && !result && fLookupName.find('<') != std::string::npos) {\n\n \/\/ We need to replace the template argument both of this type\n \/\/ and any of it enclosing type:\n \/\/ myspace::mytop::mytype\n \n std::ostringstream tmp;\n for(size_t i = 0, level = 0, sofar = 0; i < fLookupName.size(); ++i) {\n if (level==0) {\n tmp << fLookupName.substr( sofar, i+1 - sofar );\n sofar = i+1;\n }\n switch( fLookupName[i] ) {\n case '<': ++level; break;\n case '>': --level; \/\/ intentional fall through to the ',' case\n case ',':\n if (level == (1 - (int)(fLookupName[i]=='>'))) {\n std::string arg( fLookupName.substr( sofar, i-sofar) );\n \n size_t p = arg.size();\n \n while (p > 0 && (arg[p-1] == '*' || arg[p-1] == '&' || arg[p-1] == ' ') )\n --p;\n \n std::string end( arg.substr( p ) );\n arg.erase( p );\n\n const char *start = arg.c_str();\n while(strncmp(start,\"const \",6)==0) start+=6;\n\n tmp << arg.substr( 0, start - arg.c_str() );\n\n while(strncmp(start,\"std::\",5)==0) start+=5;\n\n arg.erase(0, start - arg.c_str() ); \n\n Reflex::Type type( LookupType(arg , startScope) );\n\n if (type) {\n if (type.Name()!=\"Double32_t\" && type.Name()!=\"Float16_t\") {\n \/\/ Use the real type rather than the typedef unless\n \/\/ this is Double32_t or Float16_t\n type = type.FinalType();\n }\n\t\t tmp << type.Name(Reflex::SCOPED|Reflex::QUALIFIED) );\n } else {\n tmp << arg;\n }\n tmp << end;\n \n tmp << fLookupName[i];\n\n sofar = i+1;\n } \n break;\n } \n }\n NameLookup next( tmp.str(), startScope );\n return next.Lookup(true);\n }\n\n\n return result;\n}\n\n\/\/______________________________________________________________________________\ntemplate T Reflex::NameLookup::LookupInScope()\n{\n \/\/ Lookup a type in fCurrentScope.\n \/\/ Checks sub-types, sub-scopes, using directives, and base classes for\n \/\/ the name given by fLookupName, fPosNamePart, and fPosNamePartLen.\n \/\/ If the name part is found, and another name part follows in fPosNamePart,\n \/\/ LookupTypeInScope requests the scope found to lookup the next name\n \/\/ part. fPartialMatch reflexts that the left part of the name was matched;\n \/\/ even if the trailing part of fLookupName cannot be found, the lookup\n \/\/ cannot continue on declaring scopes and has to fail.\n \/\/ A list of lookups performed in namespaces pulled in via using directives is\n \/\/ kept in fLookedAtUsingDir, to prevent infinite loops due to\n \/\/ namespace A{using namespace B;} namespace B{using namespace A;}\n \/\/ loops.\n \/\/ The lookup does not take the declaration order into account; the result of\n \/\/ parts of the lookup algorithm which depend on the order will be unpredictable.\n\n if (!fCurrentScope) {\n return Dummy::Get();\n }\n\n \/\/ prevent inf loop from\n \/\/ ns A { using ns B; } ns B {using ns A;}\n if (fLookedAtUsingDir.find(fCurrentScope) != fLookedAtUsingDir.end()) {\n return Dummy::Get();\n }\n\n int len = fCurrentScope.SubTypeSize();\n int i = 0;\n for (Type_Iterator it = fCurrentScope.SubType_Begin(); i < len; ++it, ++i) {\n const Type& type = *it;\n const TypeBase* base = type.ToTypeBase();\n if (base) {\n size_t pos;\n const std::string &name(base->SimpleName(pos));\n \/\/fprintf(stderr, \"Reflex::NameLookup::LookupInScope: looking up '%s', considering subscope '%s' ...\\n\", fLookupName.c_str(), name.c_str());\n if (\n (fLookupName[fPosNamePart] == name[pos]) &&\n !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length())\n ) {\n \/\/fprintf(stderr, \"Reflex::NameLookup::LookupInScope: lookup up '%s', partial success with subscope '%s' ...\\n\", fLookupName.c_str(), name.c_str());\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n if (fPosNamePart == std::string::npos) {\n return type;\n }\n if (it->IsTypedef()) {\n fCurrentScope = it->FinalType();\n }\n else {\n fCurrentScope = type;\n }\n return LookupInScope< T >();\n }\n }\n }\n\n Scope_Iterator subscope_end(fCurrentScope.SubScope_End());\n for (Scope_Iterator in = fCurrentScope.SubScope_Begin(); in != subscope_end; ++in) {\n \/\/ only take namespaces into account - classes were checked as part of SubType\n if (in->IsNamespace()) {\n const Scope& scope = *in;\n const ScopeBase* base = scope.ToScopeBase();\n if (base) {\n size_t pos;\n const std::string& name(base->SimpleName(pos));\n if (\n (fLookupName[fPosNamePart] == name[pos]) &&\n !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length())\n ) {\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n if (fPosNamePart == std::string::npos) {\n return (T) (*in);\n }\n fCurrentScope = (Scope) (*in);\n return LookupInScope();\n }\n }\n }\n }\n\n if (fCurrentScope.UsingDirectiveSize()) {\n fLookedAtUsingDir.insert(fCurrentScope);\n Scope storeCurrentScope = fCurrentScope;\n Scope_Iterator usingscope_end(storeCurrentScope.UsingDirective_End());\n for (Scope_Iterator si = storeCurrentScope.UsingDirective_Begin(); si != usingscope_end; ++si) {\n fCurrentScope = *si;\n T t = LookupInScope();\n if (fPartialSuccess) {\n return t;\n }\n }\n fCurrentScope = storeCurrentScope;\n }\n\n if (!fPosNamePart) { \/\/ only for \"BaseClass...\", not for \"A::BaseClass...\"\n Base_Iterator base_end(fCurrentScope.Base_End());\n for (Base_Iterator bi = fCurrentScope.Base_Begin(); bi != base_end; ++bi) {\n if (!fLookupName.compare(fPosNamePart, fPosNamePartLen, bi->Name())) {\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n if (fPosNamePart == std::string::npos) {\n return bi->ToType();\n }\n fCurrentScope = bi->ToType().FinalType();\n return LookupInScope< T >();\n }\n }\n }\n\n if (fCurrentScope.BaseSize()) {\n Scope storeCurrentScope = fCurrentScope;\n Base_Iterator base_end(storeCurrentScope.Base_End());\n for (Base_Iterator bi = storeCurrentScope.Base_Begin(); bi != base_end; ++bi) {\n fCurrentScope = bi->ToScope();\n T t = LookupInScope();\n if (fPartialSuccess) {\n return t;\n }\n }\n fCurrentScope = storeCurrentScope;\n }\n\n return Dummy::Get();\n}\n\n\/\/______________________________________________________________________________\ntemplate T Reflex::NameLookup::LookupInUnknownScope()\n{\n \/\/ Lookup a type in fCurrentScope and its declaring scopes.\n for (fPartialSuccess = false; !fPartialSuccess && fCurrentScope; fCurrentScope = fCurrentScope.DeclaringScope()) {\n fLookedAtUsingDir.clear();\n T t = LookupInScope();\n if (fPartialSuccess) {\n return t;\n }\n if (fCurrentScope.IsTopScope()) {\n break;\n }\n }\n return Dummy::Get();\n}\n\n\/\/______________________________________________________________________________\nReflex::Member Reflex::NameLookup::LookupMember(const std::string& nam, const Scope& current)\n{\n \/\/ Lookup a member.\n if (Tools::GetBasePosition(nam)) {\n return LookupMemberQualified(nam);\n }\n return LookupMemberUnqualified(nam, current);\n}\n\n\/\/______________________________________________________________________________\nReflex::Member Reflex::NameLookup::LookupMemberQualified(const std::string& nam)\n{\n \/\/ Lookup of a qualified member.\n Scope bscope = Scope::ByName(Tools::GetScopeName(nam));\n if (bscope) {\n return LookupMemberUnqualified(Tools::GetBaseName(nam), bscope);\n }\n return Dummy::Member();\n}\n\n\/\/______________________________________________________________________________\nReflex::Member Reflex::NameLookup::LookupMemberUnqualified(const std::string& nam, const Scope& current)\n{\n \/\/ Lookup of an unqualified member.\n {\n Member m = current.MemberByName(nam);\n if (m) {\n return m;\n }\n }\n for (Scope_Iterator si = current.UsingDirective_Begin(); si != current.UsingDirective_End(); ++si) {\n Member m = LookupMember(nam, *si);\n if (m) {\n return m;\n }\n }\n for (Base_Iterator bi = current.Base_Begin(); bi != current.Base_End(); ++bi) {\n Member m = LookupMember(nam, bi->ToScope());\n if (m) {\n return m;\n }\n }\n if (!current.IsTopScope()) {\n return LookupMember(nam, current.DeclaringScope());\n }\n return Dummy::Member();\n}\n\n\/\/______________________________________________________________________________\nReflex::Type Reflex::NameLookup::AccessControl(const Type& typ, const Scope& \/*current*\/)\n{\n \/\/ Check access.\n \/\/ if (typ.IsPublic()) {\n \/\/ return true;\n \/\/ }\n \/\/ else if (typ.IsProtected() && current.HasBase(typ.DeclaringScope())) {\n \/\/ return true;\n \/\/ }\n return typ;\n}\n\n\/\/______________________________________________________________________________\nvoid Reflex::NameLookup::FindNextScopePos()\n{\n \/\/ Move fPosNamePart to point to the next scope in fLookupName, updating\n \/\/ fPosNamePartLen. If fPosNamePartLen == std::string::npos, initialize\n \/\/ fPosNamePart and fPosNamePartLen. If there is no next scope left, fPosNamePart\n \/\/ will be set to std::string::npos and fPosNamePartLen will be set to 0.\n if (fPosNamePartLen != std::string::npos) {\n \/\/ we know the length, so jump\n fPosNamePart += fPosNamePartLen + 2;\n if (fPosNamePart > fLookupName.length()) {\n \/\/ past the string's end?\n fPosNamePart = std::string::npos;\n fPosNamePartLen = 0;\n return;\n }\n }\n else {\n \/\/ uninitialized\n \/\/ set fPosNamePartLen and check that fLookupName doesn't start with '::'\n fPosNamePart = 0;\n if (!fLookupName.compare(0, 2, \"::\")) {\n fPosNamePart = 2;\n }\n }\n fPosNamePartLen = Tools::GetFirstScopePosition(fLookupName.substr(fPosNamePart));\n if (!fPosNamePartLen) { \/\/ no next \"::\"\n fPosNamePartLen = fLookupName.length();\n }\n else { \/\/ no \"::\"\n fPosNamePartLen -= 2;\n }\n}\n\n<|endoftext|>"} {"text":"GTK: Add back more missing accelerators.<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/session_startup_pref.h\"\n\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"base\/string_util.h\"\n\n\/\/ static\nvoid SessionStartupPref::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterIntegerPref(prefs::kRestoreOnStartup, 0);\n prefs->RegisterListPref(prefs::kURLsToRestoreOnStartup);\n}\n\n\/\/ static\nvoid SessionStartupPref::SetStartupPref(\n Profile* profile,\n const SessionStartupPref& pref) {\n DCHECK(profile);\n SetStartupPref(profile->GetPrefs(), pref);\n}\n\n\/\/static\nvoid SessionStartupPref::SetStartupPref(PrefService* prefs,\n const SessionStartupPref& pref) {\n DCHECK(prefs);\n int type = 0;\n switch(pref.type) {\n case LAST:\n type = 1;\n break;\n\n case URLS:\n type = 4;\n break;\n\n default:\n break;\n }\n prefs->SetInteger(prefs::kRestoreOnStartup, type);\n\n \/\/ Always save the URLs, that way the UI can remain consistent even if the\n \/\/ user changes the startup type pref.\n \/\/ Ownership of the ListValue retains with the pref service.\n ListValue* url_pref_list =\n prefs->GetMutableList(prefs::kURLsToRestoreOnStartup);\n DCHECK(url_pref_list);\n url_pref_list->Clear();\n for (size_t i = 0; i < pref.urls.size(); ++i) {\n url_pref_list->Set(static_cast(i),\n new StringValue(UTF8ToWide(pref.urls[i].spec())));\n }\n}\n\n\/\/ static\nSessionStartupPref SessionStartupPref::GetStartupPref(Profile* profile) {\n DCHECK(profile);\n return GetStartupPref(profile->GetPrefs());\n}\n\n\/\/ static\nSessionStartupPref SessionStartupPref::GetStartupPref(PrefService* prefs) {\n DCHECK(prefs);\n SessionStartupPref pref;\n switch (prefs->GetInteger(prefs::kRestoreOnStartup)) {\n case 1: {\n pref.type = LAST;\n break;\n }\n\n case 4: {\n pref.type = URLS;\n break;\n }\n\n \/\/ default case or bogus type are treated as not doing anything special\n \/\/ on startup.\n }\n\n ListValue* url_pref_list = prefs->GetMutableList(\n prefs::kURLsToRestoreOnStartup);\n DCHECK(url_pref_list);\n for (size_t i = 0; i < url_pref_list->GetSize(); ++i) {\n Value* value = NULL;\n if (url_pref_list->Get(i, &value)) {\n std::wstring url_text;\n if (value->GetAsString(&url_text))\n pref.urls.push_back(GURL(WideToUTF8(url_text)));\n }\n }\n\n return pref;\n}\n\nChanged SessionStartupPref to use UTF-8 strings.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/session_startup_pref.h\"\n\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"base\/string_util.h\"\n\n\/\/ static\nvoid SessionStartupPref::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterIntegerPref(prefs::kRestoreOnStartup, 0);\n prefs->RegisterListPref(prefs::kURLsToRestoreOnStartup);\n}\n\n\/\/ static\nvoid SessionStartupPref::SetStartupPref(\n Profile* profile,\n const SessionStartupPref& pref) {\n DCHECK(profile);\n SetStartupPref(profile->GetPrefs(), pref);\n}\n\n\/\/static\nvoid SessionStartupPref::SetStartupPref(PrefService* prefs,\n const SessionStartupPref& pref) {\n DCHECK(prefs);\n int type = 0;\n switch(pref.type) {\n case LAST:\n type = 1;\n break;\n\n case URLS:\n type = 4;\n break;\n\n default:\n break;\n }\n prefs->SetInteger(prefs::kRestoreOnStartup, type);\n\n \/\/ Always save the URLs, that way the UI can remain consistent even if the\n \/\/ user changes the startup type pref.\n \/\/ Ownership of the ListValue retains with the pref service.\n ListValue* url_pref_list =\n prefs->GetMutableList(prefs::kURLsToRestoreOnStartup);\n DCHECK(url_pref_list);\n url_pref_list->Clear();\n for (size_t i = 0; i < pref.urls.size(); ++i) {\n url_pref_list->Set(static_cast(i),\n new StringValue(UTF8ToWide(pref.urls[i].spec())));\n }\n}\n\n\/\/ static\nSessionStartupPref SessionStartupPref::GetStartupPref(Profile* profile) {\n DCHECK(profile);\n return GetStartupPref(profile->GetPrefs());\n}\n\n\/\/ static\nSessionStartupPref SessionStartupPref::GetStartupPref(PrefService* prefs) {\n DCHECK(prefs);\n SessionStartupPref pref;\n switch (prefs->GetInteger(prefs::kRestoreOnStartup)) {\n case 1: {\n pref.type = LAST;\n break;\n }\n\n case 4: {\n pref.type = URLS;\n break;\n }\n\n \/\/ default case or bogus type are treated as not doing anything special\n \/\/ on startup.\n }\n\n ListValue* url_pref_list = prefs->GetMutableList(\n prefs::kURLsToRestoreOnStartup);\n DCHECK(url_pref_list);\n for (size_t i = 0; i < url_pref_list->GetSize(); ++i) {\n Value* value = NULL;\n if (url_pref_list->Get(i, &value)) {\n std::string url_text;\n if (value->GetAsString(&url_text))\n pref.urls.push_back(GURL(url_text));\n }\n }\n\n return pref;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Ubitrack - Library for Ubiquitous Tracking\n * Copyright 2006, Technische Universitaet Muenchen, and individual\n * contributors as indicated by the @authors tag. See the \n * copyright.txt in the distribution for a full listing of individual\n * contributors.\n *\n * This is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software 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 software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http:\/\/www.fsf.org.\n *\/\n\n\/**\n * @file\n * Implementation of a high resolution timer to measure execution time of code blocks\n *\n * @author Daniel Pustka \n *\/\n\n#include \n#include \n#include \n\n#include \"BlockTimer.h\"\n\nnamespace Ubitrack { namespace Util { \n\n\nBlockTimer::~BlockTimer()\n{\n\tif ( m_pLogger && m_nRuns ) \n\t{ \n\t\tstd::ostringstream s;\n\t\ts << *this;\n\t\tm_pLogger->log( log4cpp::Priority::debug, s.str(), m_sCodeFile.c_str(), m_nCodeLine );\n\t}\n}\n\n\nvoid BlockTimer::initializeStart( const char* sCodeFile, unsigned nCodeLine )\n{ \n\tm_sCodeFile = sCodeFile; \n\tm_nCodeLine = nCodeLine;\n}\n\n\nvoid BlockTimer::initializeEnd()\n{\n\tm_bInitialized = true;\n\t\/\/ TODO: add automatic hierarchy detection\n}\n\n\n\n\nstd::ostream& operator<<( std::ostream& s, const BlockTimer& t )\n{\t\t\n\tunsigned long long totalRunTime = getHighPerformanceCounter() - t.m_startTime;\n\treturn s << std::setw( 30 ) << t.getName()\n\t\t<< \" runs: \" << std::setw( 6 ) << t.getRuns()\n\t\t<< \", total: \" << std::setw( 7 ) << t.getTotalTime()\n\t\t<< \"ms, avg: \" << std::setw( 7 ) << t.getAvgTime() << \"ms\"\n\t\t<< \"ms, totalRuntime: \" << std::setw( 7 ) << totalRunTime << \"ms\"\n\t\t<< \"ms, call per second: \" << std::setw( 7 ) << totalRunTime\/1000.0 \/ t.getRuns() << \"ms\";\n\t\t\n}\n\n} } \/\/ namespace Ubitrack::Util\nsmall fix for nicer output\/*\n * Ubitrack - Library for Ubiquitous Tracking\n * Copyright 2006, Technische Universitaet Muenchen, and individual\n * contributors as indicated by the @authors tag. See the \n * copyright.txt in the distribution for a full listing of individual\n * contributors.\n *\n * This is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software 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 software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http:\/\/www.fsf.org.\n *\/\n\n\/**\n * @file\n * Implementation of a high resolution timer to measure execution time of code blocks\n *\n * @author Daniel Pustka \n *\/\n\n#include \n#include \n#include \n\n#include \"BlockTimer.h\"\n\nnamespace Ubitrack { namespace Util { \n\n\nBlockTimer::~BlockTimer()\n{\n\tif ( m_pLogger && m_nRuns ) \n\t{ \n\t\tstd::ostringstream s;\n\t\ts << *this;\n\t\tm_pLogger->log( log4cpp::Priority::debug, s.str(), m_sCodeFile.c_str(), m_nCodeLine );\n\t}\n}\n\n\nvoid BlockTimer::initializeStart( const char* sCodeFile, unsigned nCodeLine )\n{ \n\tm_sCodeFile = sCodeFile; \n\tm_nCodeLine = nCodeLine;\n}\n\n\nvoid BlockTimer::initializeEnd()\n{\n\tm_bInitialized = true;\n\t\/\/\/ @todo add automatic hierarchy detection\n}\n\n\n\n\nstd::ostream& operator<<( std::ostream& s, const BlockTimer& t )\n{\t\t\n\tunsigned long long totalRunTime = getHighPerformanceCounter() - t.m_startTime;\n\treturn s << std::setw( 30 ) << t.getName()\n\t\t<< \" runs: \" << std::setw( 6 ) << t.getRuns()\n\t\t<< \", total: \" << std::setw( 7 ) << t.getTotalTime() << \"ms\"\n\t\t<< \", avg: \" << std::setw( 7 ) << t.getAvgTime() << \"ms\"\n\t\t<< \", totalRuntime: \" << std::setw( 7 ) << totalRunTime << \"ms\"\n\t\t<< \", call per second: \" << std::setw( 7 ) << totalRunTime\/1000.0 \/ t.getRuns();\n\t\t\n}\n\n} } \/\/ namespace Ubitrack::Util\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 \"build\/build_config.h\"\n\n#if defined(OS_WIN)\n#include \n#endif\n\n#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/environment.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/test\/automation\/automation_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nclass ChromeLoggingTest : public testing::Test {\n public:\n \/\/ Stores the current value of the log file name environment\n \/\/ variable and sets the variable to new_value.\n void SaveEnvironmentVariable(std::string new_value) {\n scoped_ptr env(base::Environment::Create());\n if (!env->GetVar(env_vars::kLogFileName, &environment_filename_))\n environment_filename_ = \"\";\n\n env->SetVar(env_vars::kLogFileName, new_value);\n }\n\n \/\/ Restores the value of the log file nave environment variable\n \/\/ previously saved by SaveEnvironmentVariable().\n void RestoreEnvironmentVariable() {\n scoped_ptr env(base::Environment::Create());\n env->SetVar(env_vars::kLogFileName, environment_filename_);\n }\n\n private:\n std::string environment_filename_; \/\/ Saves real environment value.\n};\n\n\/\/ Tests the log file name getter without an environment variable.\nTEST_F(ChromeLoggingTest, LogFileName) {\n SaveEnvironmentVariable(\"\");\n\n FilePath filename = logging::GetLogFileName();\n ASSERT_NE(FilePath::StringType::npos,\n filename.value().find(FILE_PATH_LITERAL(\"chrome_debug.log\")));\n\n RestoreEnvironmentVariable();\n}\n\n\/\/ Tests the log file name getter with an environment variable.\nTEST_F(ChromeLoggingTest, EnvironmentLogFileName) {\n SaveEnvironmentVariable(\"test value\");\n\n FilePath filename = logging::GetLogFileName();\n ASSERT_EQ(FilePath(FILE_PATH_LITERAL(\"test value\")).value(),\n filename.value());\n\n RestoreEnvironmentVariable();\n}\n\n#if defined(OS_LINUX) && (!defined(NDEBUG) || !defined(USE_LINUX_BREAKPAD))\n\/\/ On Linux in Debug mode, Chrome generates a SIGTRAP.\n\/\/ we do not catch SIGTRAPs, thus no crash dump.\n\/\/ This also does not work if Breakpad is disabled.\n#define EXPECTED_ASSERT_CRASHES 0\n#else\n#define EXPECTED_ASSERT_CRASHES 1\n#endif\n\n\/\/ Touch build will start an extra renderer process (the extension process)\n\/\/ for the virtual keyboard.\n#if defined(TOUCH_UI)\n#define EXPECTED_ASSERT_ERRORS 2\n#else\n#define EXPECTED_ASSERT_ERRORS 1\n#endif\n\n#if !defined(NDEBUG) \/\/ We don't have assertions in release builds.\n\/\/ Tests whether we correctly fail on renderer assertions during tests.\nclass AssertionTest : public UITest {\n protected:\n AssertionTest() {\n#if defined(OS_WIN)\n \/\/ TODO(phajdan.jr): Make crash notifications on launch work on Win.\n wait_for_initial_loads_ = false;\n#endif\n launch_arguments_.AppendSwitch(switches::kRendererAssertTest);\n }\n};\n\n\/\/ Launch the app in assertion test mode, then close the app.\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/26715\n#define Assertion DISABLED_Assertion\n#elif defined(OS_MACOSX)\n\/\/ Crash service doesn't exist for the Mac yet: http:\/\/crbug.com\/45243\n#define Assertion DISABLED_Assertion\n#endif\nTEST_F(AssertionTest, Assertion) {\n expected_errors_ = EXPECTED_ASSERT_ERRORS;\n expected_crashes_ = EXPECTED_ASSERT_CRASHES;\n}\n#endif \/\/ !defined(NDEBUG)\n\n#if !defined(OFFICIAL_BUILD)\n\/\/ Only works on Linux in Release mode with CHROME_HEADLESS=1\nclass CheckFalseTest : public UITest {\n protected:\n CheckFalseTest() {\n#if defined(OS_WIN)\n \/\/ TODO(phajdan.jr): Make crash notifications on launch work on Win.\n wait_for_initial_loads_ = false;\n#endif\n launch_arguments_.AppendSwitch(switches::kRendererCheckFalseTest);\n }\n};\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/38497\n#define CheckFails FLAKY_CheckFails\n#elif defined(OS_MACOSX)\n\/\/ Crash service doesn't exist for the Mac yet: http:\/\/crbug.com\/45243\n#define CheckFails DISABLED_CheckFails\n#endif\n\/\/ Launch the app in assertion test mode, then close the app.\nTEST_F(CheckFalseTest, CheckFails) {\n expected_errors_ = EXPECTED_ASSERT_ERRORS;\n expected_crashes_ = EXPECTED_ASSERT_CRASHES;\n}\n#endif \/\/ !defined(OFFICIAL_BUILD)\n\n\/\/ Tests whether we correctly fail on browser crashes during UI Tests.\nclass RendererCrashTest : public UITest {\n protected:\n RendererCrashTest() {\n#if defined(OS_WIN)\n \/\/ TODO(phajdan.jr): Make crash notifications on launch work on Win.\n wait_for_initial_loads_ = false;\n#endif\n launch_arguments_.AppendSwitch(switches::kRendererCrashTest);\n }\n};\n\n#if defined(OS_LINUX) && !defined(USE_LINUX_BREAKPAD)\n\/\/ On Linux, do not expect a crash dump if Breakpad is disabled.\n#define EXPECTED_CRASH_CRASHES 0\n#else\n#define EXPECTED_CRASH_CRASHES 1\n#endif\n\n#if defined(OS_MACOSX)\n\/\/ Crash service doesn't exist for the Mac yet: http:\/\/crbug.com\/45243\n#define Crash DISABLED_Crash\n#endif\n\/\/ Launch the app in renderer crash test mode, then close the app.\nTEST_F(RendererCrashTest, Crash) {\n scoped_refptr browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n ASSERT_TRUE(browser->WaitForTabCountToBecome(1));\n expected_crashes_ = EXPECTED_CRASH_CRASHES;\n}\nMark RendererCrashTest.Crash test as flaky on ChromiumOS\/\/ 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 \"build\/build_config.h\"\n\n#if defined(OS_WIN)\n#include \n#endif\n\n#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/environment.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/test\/automation\/automation_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nclass ChromeLoggingTest : public testing::Test {\n public:\n \/\/ Stores the current value of the log file name environment\n \/\/ variable and sets the variable to new_value.\n void SaveEnvironmentVariable(std::string new_value) {\n scoped_ptr env(base::Environment::Create());\n if (!env->GetVar(env_vars::kLogFileName, &environment_filename_))\n environment_filename_ = \"\";\n\n env->SetVar(env_vars::kLogFileName, new_value);\n }\n\n \/\/ Restores the value of the log file nave environment variable\n \/\/ previously saved by SaveEnvironmentVariable().\n void RestoreEnvironmentVariable() {\n scoped_ptr env(base::Environment::Create());\n env->SetVar(env_vars::kLogFileName, environment_filename_);\n }\n\n private:\n std::string environment_filename_; \/\/ Saves real environment value.\n};\n\n\/\/ Tests the log file name getter without an environment variable.\nTEST_F(ChromeLoggingTest, LogFileName) {\n SaveEnvironmentVariable(\"\");\n\n FilePath filename = logging::GetLogFileName();\n ASSERT_NE(FilePath::StringType::npos,\n filename.value().find(FILE_PATH_LITERAL(\"chrome_debug.log\")));\n\n RestoreEnvironmentVariable();\n}\n\n\/\/ Tests the log file name getter with an environment variable.\nTEST_F(ChromeLoggingTest, EnvironmentLogFileName) {\n SaveEnvironmentVariable(\"test value\");\n\n FilePath filename = logging::GetLogFileName();\n ASSERT_EQ(FilePath(FILE_PATH_LITERAL(\"test value\")).value(),\n filename.value());\n\n RestoreEnvironmentVariable();\n}\n\n#if defined(OS_LINUX) && (!defined(NDEBUG) || !defined(USE_LINUX_BREAKPAD))\n\/\/ On Linux in Debug mode, Chrome generates a SIGTRAP.\n\/\/ we do not catch SIGTRAPs, thus no crash dump.\n\/\/ This also does not work if Breakpad is disabled.\n#define EXPECTED_ASSERT_CRASHES 0\n#else\n#define EXPECTED_ASSERT_CRASHES 1\n#endif\n\n\/\/ Touch build will start an extra renderer process (the extension process)\n\/\/ for the virtual keyboard.\n#if defined(TOUCH_UI)\n#define EXPECTED_ASSERT_ERRORS 2\n#else\n#define EXPECTED_ASSERT_ERRORS 1\n#endif\n\n#if !defined(NDEBUG) \/\/ We don't have assertions in release builds.\n\/\/ Tests whether we correctly fail on renderer assertions during tests.\nclass AssertionTest : public UITest {\n protected:\n AssertionTest() {\n#if defined(OS_WIN)\n \/\/ TODO(phajdan.jr): Make crash notifications on launch work on Win.\n wait_for_initial_loads_ = false;\n#endif\n launch_arguments_.AppendSwitch(switches::kRendererAssertTest);\n }\n};\n\n\/\/ Launch the app in assertion test mode, then close the app.\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/26715\n#define Assertion DISABLED_Assertion\n#elif defined(OS_MACOSX)\n\/\/ Crash service doesn't exist for the Mac yet: http:\/\/crbug.com\/45243\n#define Assertion DISABLED_Assertion\n#endif\nTEST_F(AssertionTest, Assertion) {\n expected_errors_ = EXPECTED_ASSERT_ERRORS;\n expected_crashes_ = EXPECTED_ASSERT_CRASHES;\n}\n#endif \/\/ !defined(NDEBUG)\n\n#if !defined(OFFICIAL_BUILD)\n\/\/ Only works on Linux in Release mode with CHROME_HEADLESS=1\nclass CheckFalseTest : public UITest {\n protected:\n CheckFalseTest() {\n#if defined(OS_WIN)\n \/\/ TODO(phajdan.jr): Make crash notifications on launch work on Win.\n wait_for_initial_loads_ = false;\n#endif\n launch_arguments_.AppendSwitch(switches::kRendererCheckFalseTest);\n }\n};\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/38497\n#define CheckFails FLAKY_CheckFails\n#elif defined(OS_MACOSX)\n\/\/ Crash service doesn't exist for the Mac yet: http:\/\/crbug.com\/45243\n#define CheckFails DISABLED_CheckFails\n#endif\n\/\/ Launch the app in assertion test mode, then close the app.\nTEST_F(CheckFalseTest, CheckFails) {\n expected_errors_ = EXPECTED_ASSERT_ERRORS;\n expected_crashes_ = EXPECTED_ASSERT_CRASHES;\n}\n#endif \/\/ !defined(OFFICIAL_BUILD)\n\n\/\/ Tests whether we correctly fail on browser crashes during UI Tests.\nclass RendererCrashTest : public UITest {\n protected:\n RendererCrashTest() {\n#if defined(OS_WIN)\n \/\/ TODO(phajdan.jr): Make crash notifications on launch work on Win.\n wait_for_initial_loads_ = false;\n#endif\n launch_arguments_.AppendSwitch(switches::kRendererCrashTest);\n }\n};\n\n#if defined(OS_LINUX) && !defined(USE_LINUX_BREAKPAD)\n\/\/ On Linux, do not expect a crash dump if Breakpad is disabled.\n#define EXPECTED_CRASH_CRASHES 0\n#else\n#define EXPECTED_CRASH_CRASHES 1\n#endif\n\n#if defined(OS_MACOSX)\n\/\/ Crash service doesn't exist for the Mac yet: http:\/\/crbug.com\/45243\n#define MAYBE_Crash DISABLED_Crash\n#elif defined(OS_CHROME)\n#define MAYBE_Crash FLAKY_Crash\n#else\n#define MAYBE_Crash Crash\n#endif\n\/\/ Launch the app in renderer crash test mode, then close the app.\nTEST_F(RendererCrashTest, MAYBE_Crash) {\n scoped_refptr browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n ASSERT_TRUE(browser->WaitForTabCountToBecome(1));\n expected_crashes_ = EXPECTED_CRASH_CRASHES;\n}\n<|endoftext|>"} {"text":"\/\/===--- ModuleManager.cpp - Module Manager ---------------------*- 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\/\/ This file defines the ModuleManager class, which manages a set of loaded\n\/\/ modules for the ASTReader.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"clang\/Serialization\/ModuleManager.h\"\n#include \"clang\/Frontend\/PCHContainerOperations.h\"\n#include \"clang\/Lex\/HeaderSearch.h\"\n#include \"clang\/Lex\/ModuleMap.h\"\n#include \"clang\/Serialization\/GlobalModuleIndex.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \n\n#ifndef NDEBUG\n#include \"llvm\/Support\/GraphWriter.h\"\n#endif\n\nusing namespace clang;\nusing namespace serialization;\n\nModuleFile *ModuleManager::lookup(StringRef Name) {\n const FileEntry *Entry = FileMgr.getFile(Name, \/*openFile=*\/false,\n \/*cacheFailure=*\/false);\n if (Entry)\n return lookup(Entry);\n\n return nullptr;\n}\n\nModuleFile *ModuleManager::lookup(const FileEntry *File) {\n llvm::DenseMap::iterator Known\n = Modules.find(File);\n if (Known == Modules.end())\n return nullptr;\n\n return Known->second;\n}\n\nstd::unique_ptr\nModuleManager::lookupBuffer(StringRef Name) {\n const FileEntry *Entry = FileMgr.getFile(Name, \/*openFile=*\/false,\n \/*cacheFailure=*\/false);\n return std::move(InMemoryBuffers[Entry]);\n}\n\nModuleManager::AddModuleResult\nModuleManager::addModule(StringRef FileName, ModuleKind Type,\n SourceLocation ImportLoc, ModuleFile *ImportedBy,\n unsigned Generation,\n off_t ExpectedSize, time_t ExpectedModTime,\n ASTFileSignature ExpectedSignature,\n ASTFileSignatureReader ReadSignature,\n ModuleFile *&Module,\n std::string &ErrorStr) {\n Module = nullptr;\n\n \/\/ Look for the file entry. This only fails if the expected size or\n \/\/ modification time differ.\n const FileEntry *Entry;\n if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {\n \/\/ If we're not expecting to pull this file out of the module cache, it\n \/\/ might have a different mtime due to being moved across filesystems in\n \/\/ a distributed build. The size must still match, though. (As must the\n \/\/ contents, but we can't check that.)\n ExpectedModTime = 0;\n }\n if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {\n ErrorStr = \"module file out of date\";\n return OutOfDate;\n }\n\n if (!Entry && FileName != \"-\") {\n ErrorStr = \"module file not found\";\n return Missing;\n }\n\n \/\/ Check whether we already loaded this module, before\n ModuleFile *ModuleEntry = Modules[Entry];\n bool NewModule = false;\n if (!ModuleEntry) {\n \/\/ Allocate a new module.\n NewModule = true;\n ModuleEntry = new ModuleFile(Type, Generation);\n ModuleEntry->Index = Chain.size();\n ModuleEntry->FileName = FileName.str();\n ModuleEntry->File = Entry;\n ModuleEntry->ImportLoc = ImportLoc;\n ModuleEntry->InputFilesValidationTimestamp = 0;\n\n if (ModuleEntry->Kind == MK_ImplicitModule) {\n std::string TimestampFilename = ModuleEntry->getTimestampFilename();\n vfs::Status Status;\n \/\/ A cached stat value would be fine as well.\n if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))\n ModuleEntry->InputFilesValidationTimestamp =\n Status.getLastModificationTime().toEpochTime();\n }\n\n \/\/ Load the contents of the module\n if (std::unique_ptr Buffer = lookupBuffer(FileName)) {\n \/\/ The buffer was already provided for us.\n ModuleEntry->Buffer = std::move(Buffer);\n } else {\n \/\/ Open the AST file.\n llvm::ErrorOr> Buf(\n (std::error_code()));\n if (FileName == \"-\") {\n Buf = llvm::MemoryBuffer::getSTDIN();\n } else {\n \/\/ Leave the FileEntry open so if it gets read again by another\n \/\/ ModuleManager it must be the same underlying file.\n \/\/ FIXME: Because FileManager::getFile() doesn't guarantee that it will\n \/\/ give us an open file, this may not be 100% reliable.\n Buf = FileMgr.getBufferForFile(ModuleEntry->File,\n \/*IsVolatile=*\/false,\n \/*ShouldClose=*\/false);\n }\n\n if (!Buf) {\n ErrorStr = Buf.getError().message();\n delete ModuleEntry;\n return Missing;\n }\n\n ModuleEntry->Buffer = std::move(*Buf);\n }\n\n \/\/ Initialize the stream.\n PCHContainerRdr.ExtractPCH(ModuleEntry->Buffer->getMemBufferRef(),\n ModuleEntry->StreamFile);\n }\n\n if (ExpectedSignature) {\n \/\/ If we've not read the control block yet, read the signature eagerly now\n \/\/ so that we can check it.\n if (!ModuleEntry->Signature)\n ModuleEntry->Signature = ReadSignature(ModuleEntry->StreamFile);\n\n if (ModuleEntry->Signature != ExpectedSignature) {\n ErrorStr = ModuleEntry->Signature ? \"signature mismatch\"\n : \"could not read module signature\";\n\n if (NewModule)\n delete ModuleEntry;\n return OutOfDate;\n }\n }\n\n if (ImportedBy) {\n ModuleEntry->ImportedBy.insert(ImportedBy);\n ImportedBy->Imports.insert(ModuleEntry);\n } else {\n if (!ModuleEntry->DirectlyImported)\n ModuleEntry->ImportLoc = ImportLoc;\n \n ModuleEntry->DirectlyImported = true;\n }\n\n Module = ModuleEntry;\n\n if (!NewModule)\n return AlreadyLoaded;\n\n assert(!Modules[Entry] && \"module loaded twice\");\n Modules[Entry] = ModuleEntry;\n\n Chain.push_back(ModuleEntry);\n if (!ModuleEntry->isModule())\n PCHChain.push_back(ModuleEntry);\n if (!ImportedBy)\n Roots.push_back(ModuleEntry);\n\n return NewlyLoaded;\n}\n\nvoid ModuleManager::removeModules(\n ModuleIterator first, ModuleIterator last,\n llvm::SmallPtrSetImpl &LoadedSuccessfully,\n ModuleMap *modMap) {\n if (first == last)\n return;\n\n \/\/ Explicitly clear VisitOrder since we might not notice it is stale.\n VisitOrder.clear();\n\n \/\/ Collect the set of module file pointers that we'll be removing.\n llvm::SmallPtrSet victimSet(first, last);\n\n auto IsVictim = [&](ModuleFile *MF) {\n return victimSet.count(MF);\n };\n \/\/ Remove any references to the now-destroyed modules.\n for (unsigned i = 0, n = Chain.size(); i != n; ++i) {\n Chain[i]->ImportedBy.remove_if(IsVictim);\n }\n Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),\n Roots.end());\n\n \/\/ Remove the modules from the PCH chain.\n for (auto I = first; I != last; ++I) {\n if (!(*I)->isModule()) {\n PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), *I),\n PCHChain.end());\n break;\n }\n }\n\n \/\/ Delete the modules and erase them from the various structures.\n for (ModuleIterator victim = first; victim != last; ++victim) {\n Modules.erase((*victim)->File);\n\n if (modMap) {\n StringRef ModuleName = (*victim)->ModuleName;\n if (Module *mod = modMap->findModule(ModuleName)) {\n mod->setASTFile(nullptr);\n }\n }\n\n \/\/ Files that didn't make it through ReadASTCore successfully will be\n \/\/ rebuilt (or there was an error). Invalidate them so that we can load the\n \/\/ new files that will be renamed over the old ones.\n if (LoadedSuccessfully.count(*victim) == 0)\n FileMgr.invalidateCache((*victim)->File);\n\n delete *victim;\n }\n\n \/\/ Remove the modules from the chain.\n Chain.erase(first, last);\n}\n\nvoid\nModuleManager::addInMemoryBuffer(StringRef FileName,\n std::unique_ptr Buffer) {\n\n const FileEntry *Entry =\n FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);\n InMemoryBuffers[Entry] = std::move(Buffer);\n}\n\nModuleManager::VisitState *ModuleManager::allocateVisitState() {\n \/\/ Fast path: if we have a cached state, use it.\n if (FirstVisitState) {\n VisitState *Result = FirstVisitState;\n FirstVisitState = FirstVisitState->NextState;\n Result->NextState = nullptr;\n return Result;\n }\n\n \/\/ Allocate and return a new state.\n return new VisitState(size());\n}\n\nvoid ModuleManager::returnVisitState(VisitState *State) {\n assert(State->NextState == nullptr && \"Visited state is in list?\");\n State->NextState = FirstVisitState;\n FirstVisitState = State;\n}\n\nvoid ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {\n GlobalIndex = Index;\n if (!GlobalIndex) {\n ModulesInCommonWithGlobalIndex.clear();\n return;\n }\n\n \/\/ Notify the global module index about all of the modules we've already\n \/\/ loaded.\n for (unsigned I = 0, N = Chain.size(); I != N; ++I) {\n if (!GlobalIndex->loadedModuleFile(Chain[I])) {\n ModulesInCommonWithGlobalIndex.push_back(Chain[I]);\n }\n }\n}\n\nvoid ModuleManager::moduleFileAccepted(ModuleFile *MF) {\n if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))\n return;\n\n ModulesInCommonWithGlobalIndex.push_back(MF);\n}\n\nModuleManager::ModuleManager(FileManager &FileMgr,\n const PCHContainerReader &PCHContainerRdr)\n : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr), GlobalIndex(),\n FirstVisitState(nullptr) {}\n\nModuleManager::~ModuleManager() {\n for (unsigned i = 0, e = Chain.size(); i != e; ++i)\n delete Chain[e - i - 1];\n delete FirstVisitState;\n}\n\nvoid ModuleManager::visit(llvm::function_ref Visitor,\n llvm::SmallPtrSetImpl *ModuleFilesHit) {\n \/\/ If the visitation order vector is the wrong size, recompute the order.\n if (VisitOrder.size() != Chain.size()) {\n unsigned N = size();\n VisitOrder.clear();\n VisitOrder.reserve(N);\n \n \/\/ Record the number of incoming edges for each module. When we\n \/\/ encounter a module with no incoming edges, push it into the queue\n \/\/ to seed the queue.\n SmallVector Queue;\n Queue.reserve(N);\n llvm::SmallVector UnusedIncomingEdges;\n UnusedIncomingEdges.resize(size());\n for (ModuleFile *M : llvm::reverse(*this)) {\n unsigned Size = M->ImportedBy.size();\n UnusedIncomingEdges[M->Index] = Size;\n if (!Size)\n Queue.push_back(M);\n }\n\n \/\/ Traverse the graph, making sure to visit a module before visiting any\n \/\/ of its dependencies.\n while (!Queue.empty()) {\n ModuleFile *CurrentModule = Queue.pop_back_val();\n VisitOrder.push_back(CurrentModule);\n\n \/\/ For any module that this module depends on, push it on the\n \/\/ stack (if it hasn't already been marked as visited).\n for (auto M = CurrentModule->Imports.rbegin(),\n MEnd = CurrentModule->Imports.rend();\n M != MEnd; ++M) {\n \/\/ Remove our current module as an impediment to visiting the\n \/\/ module we depend on. If we were the last unvisited module\n \/\/ that depends on this particular module, push it into the\n \/\/ queue to be visited.\n unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];\n if (NumUnusedEdges && (--NumUnusedEdges == 0))\n Queue.push_back(*M);\n }\n }\n\n assert(VisitOrder.size() == N && \"Visitation order is wrong?\");\n\n delete FirstVisitState;\n FirstVisitState = nullptr;\n }\n\n VisitState *State = allocateVisitState();\n unsigned VisitNumber = State->NextVisitNumber++;\n\n \/\/ If the caller has provided us with a hit-set that came from the global\n \/\/ module index, mark every module file in common with the global module\n \/\/ index that is *not* in that set as 'visited'.\n if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {\n for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)\n {\n ModuleFile *M = ModulesInCommonWithGlobalIndex[I];\n if (!ModuleFilesHit->count(M))\n State->VisitNumber[M->Index] = VisitNumber;\n }\n }\n\n for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {\n ModuleFile *CurrentModule = VisitOrder[I];\n \/\/ Should we skip this module file?\n if (State->VisitNumber[CurrentModule->Index] == VisitNumber)\n continue;\n\n \/\/ Visit the module.\n assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);\n State->VisitNumber[CurrentModule->Index] = VisitNumber;\n if (!Visitor(*CurrentModule))\n continue;\n\n \/\/ The visitor has requested that cut off visitation of any\n \/\/ module that the current module depends on. To indicate this\n \/\/ behavior, we mark all of the reachable modules as having been visited.\n ModuleFile *NextModule = CurrentModule;\n do {\n \/\/ For any module that this module depends on, push it on the\n \/\/ stack (if it hasn't already been marked as visited).\n for (llvm::SetVector::iterator\n M = NextModule->Imports.begin(),\n MEnd = NextModule->Imports.end();\n M != MEnd; ++M) {\n if (State->VisitNumber[(*M)->Index] != VisitNumber) {\n State->Stack.push_back(*M);\n State->VisitNumber[(*M)->Index] = VisitNumber;\n }\n }\n\n if (State->Stack.empty())\n break;\n\n \/\/ Pop the next module off the stack.\n NextModule = State->Stack.pop_back_val();\n } while (true);\n }\n\n returnVisitState(State);\n}\n\nbool ModuleManager::lookupModuleFile(StringRef FileName,\n off_t ExpectedSize,\n time_t ExpectedModTime,\n const FileEntry *&File) {\n \/\/ Open the file immediately to ensure there is no race between stat'ing and\n \/\/ opening the file.\n File = FileMgr.getFile(FileName, \/*openFile=*\/true, \/*cacheFailure=*\/false);\n\n if (!File && FileName != \"-\") {\n return false;\n }\n\n if ((ExpectedSize && ExpectedSize != File->getSize()) ||\n (ExpectedModTime && ExpectedModTime != File->getModificationTime()))\n \/\/ Do not destroy File, as it may be referenced. If we need to rebuild it,\n \/\/ it will be destroyed by removeModules.\n return true;\n\n return false;\n}\n\n#ifndef NDEBUG\nnamespace llvm {\n template<>\n struct GraphTraits {\n typedef ModuleFile *NodeRef;\n typedef llvm::SetVector::const_iterator ChildIteratorType;\n typedef ModuleManager::ModuleConstIterator nodes_iterator;\n\n static ChildIteratorType child_begin(NodeRef Node) {\n return Node->Imports.begin();\n }\n\n static ChildIteratorType child_end(NodeRef Node) {\n return Node->Imports.end();\n }\n \n static nodes_iterator nodes_begin(const ModuleManager &Manager) {\n return Manager.begin();\n }\n \n static nodes_iterator nodes_end(const ModuleManager &Manager) {\n return Manager.end();\n }\n };\n \n template<>\n struct DOTGraphTraits : public DefaultDOTGraphTraits {\n explicit DOTGraphTraits(bool IsSimple = false)\n : DefaultDOTGraphTraits(IsSimple) { }\n \n static bool renderGraphFromBottomUp() {\n return true;\n }\n\n std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {\n return M->ModuleName;\n }\n };\n}\n\nvoid ModuleManager::viewGraph() {\n llvm::ViewGraph(*this, \"Modules\");\n}\n#endif\nClean up handling of reading module files from stdin. Don't bother trying to look for a corresponding file, since we're not going to read it anyway.\/\/===--- ModuleManager.cpp - Module Manager ---------------------*- 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\/\/ This file defines the ModuleManager class, which manages a set of loaded\n\/\/ modules for the ASTReader.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"clang\/Serialization\/ModuleManager.h\"\n#include \"clang\/Frontend\/PCHContainerOperations.h\"\n#include \"clang\/Lex\/HeaderSearch.h\"\n#include \"clang\/Lex\/ModuleMap.h\"\n#include \"clang\/Serialization\/GlobalModuleIndex.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \n\n#ifndef NDEBUG\n#include \"llvm\/Support\/GraphWriter.h\"\n#endif\n\nusing namespace clang;\nusing namespace serialization;\n\nModuleFile *ModuleManager::lookup(StringRef Name) {\n const FileEntry *Entry = FileMgr.getFile(Name, \/*openFile=*\/false,\n \/*cacheFailure=*\/false);\n if (Entry)\n return lookup(Entry);\n\n return nullptr;\n}\n\nModuleFile *ModuleManager::lookup(const FileEntry *File) {\n llvm::DenseMap::iterator Known\n = Modules.find(File);\n if (Known == Modules.end())\n return nullptr;\n\n return Known->second;\n}\n\nstd::unique_ptr\nModuleManager::lookupBuffer(StringRef Name) {\n const FileEntry *Entry = FileMgr.getFile(Name, \/*openFile=*\/false,\n \/*cacheFailure=*\/false);\n return std::move(InMemoryBuffers[Entry]);\n}\n\nModuleManager::AddModuleResult\nModuleManager::addModule(StringRef FileName, ModuleKind Type,\n SourceLocation ImportLoc, ModuleFile *ImportedBy,\n unsigned Generation,\n off_t ExpectedSize, time_t ExpectedModTime,\n ASTFileSignature ExpectedSignature,\n ASTFileSignatureReader ReadSignature,\n ModuleFile *&Module,\n std::string &ErrorStr) {\n Module = nullptr;\n\n \/\/ Look for the file entry. This only fails if the expected size or\n \/\/ modification time differ.\n const FileEntry *Entry;\n if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {\n \/\/ If we're not expecting to pull this file out of the module cache, it\n \/\/ might have a different mtime due to being moved across filesystems in\n \/\/ a distributed build. The size must still match, though. (As must the\n \/\/ contents, but we can't check that.)\n ExpectedModTime = 0;\n }\n if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {\n ErrorStr = \"module file out of date\";\n return OutOfDate;\n }\n\n if (!Entry && FileName != \"-\") {\n ErrorStr = \"module file not found\";\n return Missing;\n }\n\n \/\/ Check whether we already loaded this module, before\n ModuleFile *ModuleEntry = Modules[Entry];\n bool NewModule = false;\n if (!ModuleEntry) {\n \/\/ Allocate a new module.\n NewModule = true;\n ModuleEntry = new ModuleFile(Type, Generation);\n ModuleEntry->Index = Chain.size();\n ModuleEntry->FileName = FileName.str();\n ModuleEntry->File = Entry;\n ModuleEntry->ImportLoc = ImportLoc;\n ModuleEntry->InputFilesValidationTimestamp = 0;\n\n if (ModuleEntry->Kind == MK_ImplicitModule) {\n std::string TimestampFilename = ModuleEntry->getTimestampFilename();\n vfs::Status Status;\n \/\/ A cached stat value would be fine as well.\n if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))\n ModuleEntry->InputFilesValidationTimestamp =\n Status.getLastModificationTime().toEpochTime();\n }\n\n \/\/ Load the contents of the module\n if (std::unique_ptr Buffer = lookupBuffer(FileName)) {\n \/\/ The buffer was already provided for us.\n ModuleEntry->Buffer = std::move(Buffer);\n } else {\n \/\/ Open the AST file.\n llvm::ErrorOr> Buf(\n (std::error_code()));\n if (FileName == \"-\") {\n Buf = llvm::MemoryBuffer::getSTDIN();\n } else {\n \/\/ Leave the FileEntry open so if it gets read again by another\n \/\/ ModuleManager it must be the same underlying file.\n \/\/ FIXME: Because FileManager::getFile() doesn't guarantee that it will\n \/\/ give us an open file, this may not be 100% reliable.\n Buf = FileMgr.getBufferForFile(ModuleEntry->File,\n \/*IsVolatile=*\/false,\n \/*ShouldClose=*\/false);\n }\n\n if (!Buf) {\n ErrorStr = Buf.getError().message();\n delete ModuleEntry;\n return Missing;\n }\n\n ModuleEntry->Buffer = std::move(*Buf);\n }\n\n \/\/ Initialize the stream.\n PCHContainerRdr.ExtractPCH(ModuleEntry->Buffer->getMemBufferRef(),\n ModuleEntry->StreamFile);\n }\n\n if (ExpectedSignature) {\n \/\/ If we've not read the control block yet, read the signature eagerly now\n \/\/ so that we can check it.\n if (!ModuleEntry->Signature)\n ModuleEntry->Signature = ReadSignature(ModuleEntry->StreamFile);\n\n if (ModuleEntry->Signature != ExpectedSignature) {\n ErrorStr = ModuleEntry->Signature ? \"signature mismatch\"\n : \"could not read module signature\";\n\n if (NewModule)\n delete ModuleEntry;\n return OutOfDate;\n }\n }\n\n if (ImportedBy) {\n ModuleEntry->ImportedBy.insert(ImportedBy);\n ImportedBy->Imports.insert(ModuleEntry);\n } else {\n if (!ModuleEntry->DirectlyImported)\n ModuleEntry->ImportLoc = ImportLoc;\n \n ModuleEntry->DirectlyImported = true;\n }\n\n Module = ModuleEntry;\n\n if (!NewModule)\n return AlreadyLoaded;\n\n assert(!Modules[Entry] && \"module loaded twice\");\n Modules[Entry] = ModuleEntry;\n\n Chain.push_back(ModuleEntry);\n if (!ModuleEntry->isModule())\n PCHChain.push_back(ModuleEntry);\n if (!ImportedBy)\n Roots.push_back(ModuleEntry);\n\n return NewlyLoaded;\n}\n\nvoid ModuleManager::removeModules(\n ModuleIterator first, ModuleIterator last,\n llvm::SmallPtrSetImpl &LoadedSuccessfully,\n ModuleMap *modMap) {\n if (first == last)\n return;\n\n \/\/ Explicitly clear VisitOrder since we might not notice it is stale.\n VisitOrder.clear();\n\n \/\/ Collect the set of module file pointers that we'll be removing.\n llvm::SmallPtrSet victimSet(first, last);\n\n auto IsVictim = [&](ModuleFile *MF) {\n return victimSet.count(MF);\n };\n \/\/ Remove any references to the now-destroyed modules.\n for (unsigned i = 0, n = Chain.size(); i != n; ++i) {\n Chain[i]->ImportedBy.remove_if(IsVictim);\n }\n Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),\n Roots.end());\n\n \/\/ Remove the modules from the PCH chain.\n for (auto I = first; I != last; ++I) {\n if (!(*I)->isModule()) {\n PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), *I),\n PCHChain.end());\n break;\n }\n }\n\n \/\/ Delete the modules and erase them from the various structures.\n for (ModuleIterator victim = first; victim != last; ++victim) {\n Modules.erase((*victim)->File);\n\n if (modMap) {\n StringRef ModuleName = (*victim)->ModuleName;\n if (Module *mod = modMap->findModule(ModuleName)) {\n mod->setASTFile(nullptr);\n }\n }\n\n \/\/ Files that didn't make it through ReadASTCore successfully will be\n \/\/ rebuilt (or there was an error). Invalidate them so that we can load the\n \/\/ new files that will be renamed over the old ones.\n if (LoadedSuccessfully.count(*victim) == 0)\n FileMgr.invalidateCache((*victim)->File);\n\n delete *victim;\n }\n\n \/\/ Remove the modules from the chain.\n Chain.erase(first, last);\n}\n\nvoid\nModuleManager::addInMemoryBuffer(StringRef FileName,\n std::unique_ptr Buffer) {\n\n const FileEntry *Entry =\n FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);\n InMemoryBuffers[Entry] = std::move(Buffer);\n}\n\nModuleManager::VisitState *ModuleManager::allocateVisitState() {\n \/\/ Fast path: if we have a cached state, use it.\n if (FirstVisitState) {\n VisitState *Result = FirstVisitState;\n FirstVisitState = FirstVisitState->NextState;\n Result->NextState = nullptr;\n return Result;\n }\n\n \/\/ Allocate and return a new state.\n return new VisitState(size());\n}\n\nvoid ModuleManager::returnVisitState(VisitState *State) {\n assert(State->NextState == nullptr && \"Visited state is in list?\");\n State->NextState = FirstVisitState;\n FirstVisitState = State;\n}\n\nvoid ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {\n GlobalIndex = Index;\n if (!GlobalIndex) {\n ModulesInCommonWithGlobalIndex.clear();\n return;\n }\n\n \/\/ Notify the global module index about all of the modules we've already\n \/\/ loaded.\n for (unsigned I = 0, N = Chain.size(); I != N; ++I) {\n if (!GlobalIndex->loadedModuleFile(Chain[I])) {\n ModulesInCommonWithGlobalIndex.push_back(Chain[I]);\n }\n }\n}\n\nvoid ModuleManager::moduleFileAccepted(ModuleFile *MF) {\n if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))\n return;\n\n ModulesInCommonWithGlobalIndex.push_back(MF);\n}\n\nModuleManager::ModuleManager(FileManager &FileMgr,\n const PCHContainerReader &PCHContainerRdr)\n : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr), GlobalIndex(),\n FirstVisitState(nullptr) {}\n\nModuleManager::~ModuleManager() {\n for (unsigned i = 0, e = Chain.size(); i != e; ++i)\n delete Chain[e - i - 1];\n delete FirstVisitState;\n}\n\nvoid ModuleManager::visit(llvm::function_ref Visitor,\n llvm::SmallPtrSetImpl *ModuleFilesHit) {\n \/\/ If the visitation order vector is the wrong size, recompute the order.\n if (VisitOrder.size() != Chain.size()) {\n unsigned N = size();\n VisitOrder.clear();\n VisitOrder.reserve(N);\n \n \/\/ Record the number of incoming edges for each module. When we\n \/\/ encounter a module with no incoming edges, push it into the queue\n \/\/ to seed the queue.\n SmallVector Queue;\n Queue.reserve(N);\n llvm::SmallVector UnusedIncomingEdges;\n UnusedIncomingEdges.resize(size());\n for (ModuleFile *M : llvm::reverse(*this)) {\n unsigned Size = M->ImportedBy.size();\n UnusedIncomingEdges[M->Index] = Size;\n if (!Size)\n Queue.push_back(M);\n }\n\n \/\/ Traverse the graph, making sure to visit a module before visiting any\n \/\/ of its dependencies.\n while (!Queue.empty()) {\n ModuleFile *CurrentModule = Queue.pop_back_val();\n VisitOrder.push_back(CurrentModule);\n\n \/\/ For any module that this module depends on, push it on the\n \/\/ stack (if it hasn't already been marked as visited).\n for (auto M = CurrentModule->Imports.rbegin(),\n MEnd = CurrentModule->Imports.rend();\n M != MEnd; ++M) {\n \/\/ Remove our current module as an impediment to visiting the\n \/\/ module we depend on. If we were the last unvisited module\n \/\/ that depends on this particular module, push it into the\n \/\/ queue to be visited.\n unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];\n if (NumUnusedEdges && (--NumUnusedEdges == 0))\n Queue.push_back(*M);\n }\n }\n\n assert(VisitOrder.size() == N && \"Visitation order is wrong?\");\n\n delete FirstVisitState;\n FirstVisitState = nullptr;\n }\n\n VisitState *State = allocateVisitState();\n unsigned VisitNumber = State->NextVisitNumber++;\n\n \/\/ If the caller has provided us with a hit-set that came from the global\n \/\/ module index, mark every module file in common with the global module\n \/\/ index that is *not* in that set as 'visited'.\n if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {\n for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)\n {\n ModuleFile *M = ModulesInCommonWithGlobalIndex[I];\n if (!ModuleFilesHit->count(M))\n State->VisitNumber[M->Index] = VisitNumber;\n }\n }\n\n for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {\n ModuleFile *CurrentModule = VisitOrder[I];\n \/\/ Should we skip this module file?\n if (State->VisitNumber[CurrentModule->Index] == VisitNumber)\n continue;\n\n \/\/ Visit the module.\n assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);\n State->VisitNumber[CurrentModule->Index] = VisitNumber;\n if (!Visitor(*CurrentModule))\n continue;\n\n \/\/ The visitor has requested that cut off visitation of any\n \/\/ module that the current module depends on. To indicate this\n \/\/ behavior, we mark all of the reachable modules as having been visited.\n ModuleFile *NextModule = CurrentModule;\n do {\n \/\/ For any module that this module depends on, push it on the\n \/\/ stack (if it hasn't already been marked as visited).\n for (llvm::SetVector::iterator\n M = NextModule->Imports.begin(),\n MEnd = NextModule->Imports.end();\n M != MEnd; ++M) {\n if (State->VisitNumber[(*M)->Index] != VisitNumber) {\n State->Stack.push_back(*M);\n State->VisitNumber[(*M)->Index] = VisitNumber;\n }\n }\n\n if (State->Stack.empty())\n break;\n\n \/\/ Pop the next module off the stack.\n NextModule = State->Stack.pop_back_val();\n } while (true);\n }\n\n returnVisitState(State);\n}\n\nbool ModuleManager::lookupModuleFile(StringRef FileName,\n off_t ExpectedSize,\n time_t ExpectedModTime,\n const FileEntry *&File) {\n if (FileName == \"-\") {\n File = nullptr;\n return false;\n }\n\n \/\/ Open the file immediately to ensure there is no race between stat'ing and\n \/\/ opening the file.\n File = FileMgr.getFile(FileName, \/*openFile=*\/true, \/*cacheFailure=*\/false);\n if (!File)\n return false;\n\n if ((ExpectedSize && ExpectedSize != File->getSize()) ||\n (ExpectedModTime && ExpectedModTime != File->getModificationTime()))\n \/\/ Do not destroy File, as it may be referenced. If we need to rebuild it,\n \/\/ it will be destroyed by removeModules.\n return true;\n\n return false;\n}\n\n#ifndef NDEBUG\nnamespace llvm {\n template<>\n struct GraphTraits {\n typedef ModuleFile *NodeRef;\n typedef llvm::SetVector::const_iterator ChildIteratorType;\n typedef ModuleManager::ModuleConstIterator nodes_iterator;\n\n static ChildIteratorType child_begin(NodeRef Node) {\n return Node->Imports.begin();\n }\n\n static ChildIteratorType child_end(NodeRef Node) {\n return Node->Imports.end();\n }\n \n static nodes_iterator nodes_begin(const ModuleManager &Manager) {\n return Manager.begin();\n }\n \n static nodes_iterator nodes_end(const ModuleManager &Manager) {\n return Manager.end();\n }\n };\n \n template<>\n struct DOTGraphTraits : public DefaultDOTGraphTraits {\n explicit DOTGraphTraits(bool IsSimple = false)\n : DefaultDOTGraphTraits(IsSimple) { }\n \n static bool renderGraphFromBottomUp() {\n return true;\n }\n\n std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {\n return M->ModuleName;\n }\n };\n}\n\nvoid ModuleManager::viewGraph() {\n llvm::ViewGraph(*this, \"Modules\");\n}\n#endif\n<|endoftext|>"} {"text":"\/\/===--- ModuleManager.cpp - Module Manager ---------------------*- 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\/\/ This file defines the ModuleManager class, which manages a set of loaded\n\/\/ modules for the ASTReader.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"clang\/Serialization\/ModuleManager.h\"\n#include \"clang\/Frontend\/PCHContainerOperations.h\"\n#include \"clang\/Lex\/HeaderSearch.h\"\n#include \"clang\/Lex\/ModuleMap.h\"\n#include \"clang\/Serialization\/GlobalModuleIndex.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \n\n#ifndef NDEBUG\n#include \"llvm\/Support\/GraphWriter.h\"\n#endif\n\nusing namespace clang;\nusing namespace serialization;\n\nModuleFile *ModuleManager::lookup(StringRef Name) {\n const FileEntry *Entry = FileMgr.getFile(Name, \/*openFile=*\/false,\n \/*cacheFailure=*\/false);\n if (Entry)\n return lookup(Entry);\n\n return nullptr;\n}\n\nModuleFile *ModuleManager::lookup(const FileEntry *File) {\n llvm::DenseMap::iterator Known\n = Modules.find(File);\n if (Known == Modules.end())\n return nullptr;\n\n return Known->second;\n}\n\nstd::unique_ptr\nModuleManager::lookupBuffer(StringRef Name) {\n const FileEntry *Entry = FileMgr.getFile(Name, \/*openFile=*\/false,\n \/*cacheFailure=*\/false);\n return std::move(InMemoryBuffers[Entry]);\n}\n\nstatic bool checkSignature(ASTFileSignature Signature,\n ASTFileSignature ExpectedSignature,\n std::string &ErrorStr) {\n if (!ExpectedSignature || Signature == ExpectedSignature)\n return false;\n\n ErrorStr =\n Signature ? \"signature mismatch\" : \"could not read module signature\";\n return true;\n}\n\nstatic void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,\n SourceLocation ImportLoc) {\n if (ImportedBy) {\n MF.ImportedBy.insert(ImportedBy);\n ImportedBy->Imports.insert(&MF);\n } else {\n if (!MF.DirectlyImported)\n MF.ImportLoc = ImportLoc;\n\n MF.DirectlyImported = true;\n }\n}\n\nModuleManager::AddModuleResult\nModuleManager::addModule(StringRef FileName, ModuleKind Type,\n SourceLocation ImportLoc, ModuleFile *ImportedBy,\n unsigned Generation,\n off_t ExpectedSize, time_t ExpectedModTime,\n ASTFileSignature ExpectedSignature,\n ASTFileSignatureReader ReadSignature,\n ModuleFile *&Module,\n std::string &ErrorStr) {\n Module = nullptr;\n\n \/\/ Look for the file entry. This only fails if the expected size or\n \/\/ modification time differ.\n const FileEntry *Entry;\n if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {\n \/\/ If we're not expecting to pull this file out of the module cache, it\n \/\/ might have a different mtime due to being moved across filesystems in\n \/\/ a distributed build. The size must still match, though. (As must the\n \/\/ contents, but we can't check that.)\n ExpectedModTime = 0;\n }\n if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {\n ErrorStr = \"module file out of date\";\n return OutOfDate;\n }\n\n if (!Entry && FileName != \"-\") {\n ErrorStr = \"module file not found\";\n return Missing;\n }\n\n \/\/ Check whether we already loaded this module, before\n if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {\n \/\/ Check the stored signature.\n if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))\n return OutOfDate;\n\n Module = ModuleEntry;\n updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);\n return AlreadyLoaded;\n }\n\n \/\/ Allocate a new module.\n auto NewModule = llvm::make_unique(Type, Generation);\n NewModule->Index = Chain.size();\n NewModule->FileName = FileName.str();\n NewModule->File = Entry;\n NewModule->ImportLoc = ImportLoc;\n NewModule->InputFilesValidationTimestamp = 0;\n\n if (NewModule->Kind == MK_ImplicitModule) {\n std::string TimestampFilename = NewModule->getTimestampFilename();\n vfs::Status Status;\n \/\/ A cached stat value would be fine as well.\n if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))\n NewModule->InputFilesValidationTimestamp =\n llvm::sys::toTimeT(Status.getLastModificationTime());\n }\n\n \/\/ Load the contents of the module\n if (std::unique_ptr Buffer = lookupBuffer(FileName)) {\n \/\/ The buffer was already provided for us.\n NewModule->Buffer = std::move(Buffer);\n } else {\n \/\/ Open the AST file.\n llvm::ErrorOr> Buf((std::error_code()));\n if (FileName == \"-\") {\n Buf = llvm::MemoryBuffer::getSTDIN();\n } else {\n \/\/ Leave the FileEntry open so if it gets read again by another\n \/\/ ModuleManager it must be the same underlying file.\n \/\/ FIXME: Because FileManager::getFile() doesn't guarantee that it will\n \/\/ give us an open file, this may not be 100% reliable.\n Buf = FileMgr.getBufferForFile(NewModule->File,\n \/*IsVolatile=*\/false,\n \/*ShouldClose=*\/false);\n }\n\n if (!Buf) {\n ErrorStr = Buf.getError().message();\n return Missing;\n }\n\n NewModule->Buffer = std::move(*Buf);\n }\n\n \/\/ Initialize the stream.\n NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);\n\n \/\/ Read the signature eagerly now so that we can check it.\n if (checkSignature(ReadSignature(NewModule->Data), ExpectedSignature,\n ErrorStr))\n return OutOfDate;\n\n \/\/ We're keeping this module. Store it everywhere.\n Module = Modules[Entry] = NewModule.get();\n\n updateModuleImports(*NewModule, ImportedBy, ImportLoc);\n\n if (!NewModule->isModule())\n PCHChain.push_back(NewModule.get());\n if (!ImportedBy)\n Roots.push_back(NewModule.get());\n\n Chain.push_back(std::move(NewModule));\n return NewlyLoaded;\n}\n\nvoid ModuleManager::removeModules(\n ModuleIterator First,\n llvm::SmallPtrSetImpl &LoadedSuccessfully,\n ModuleMap *modMap) {\n auto Last = end();\n if (First == Last)\n return;\n\n\n \/\/ Explicitly clear VisitOrder since we might not notice it is stale.\n VisitOrder.clear();\n\n \/\/ Collect the set of module file pointers that we'll be removing.\n llvm::SmallPtrSet victimSet(\n (llvm::pointer_iterator(First)),\n (llvm::pointer_iterator(Last)));\n\n auto IsVictim = [&](ModuleFile *MF) {\n return victimSet.count(MF);\n };\n \/\/ Remove any references to the now-destroyed modules.\n for (auto I = begin(); I != First; ++I) {\n I->Imports.remove_if(IsVictim);\n I->ImportedBy.remove_if(IsVictim);\n }\n Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),\n Roots.end());\n\n \/\/ Remove the modules from the PCH chain.\n for (auto I = First; I != Last; ++I) {\n if (!I->isModule()) {\n PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), &*I),\n PCHChain.end());\n break;\n }\n }\n\n \/\/ Delete the modules and erase them from the various structures.\n for (ModuleIterator victim = First; victim != Last; ++victim) {\n Modules.erase(victim->File);\n\n if (modMap) {\n StringRef ModuleName = victim->ModuleName;\n if (Module *mod = modMap->findModule(ModuleName)) {\n mod->setASTFile(nullptr);\n }\n }\n\n \/\/ Files that didn't make it through ReadASTCore successfully will be\n \/\/ rebuilt (or there was an error). Invalidate them so that we can load the\n \/\/ new files that will be renamed over the old ones.\n if (LoadedSuccessfully.count(&*victim) == 0)\n FileMgr.invalidateCache(victim->File);\n }\n\n \/\/ Delete the modules.\n Chain.erase(Chain.begin() + (First - begin()), Chain.end());\n}\n\nvoid\nModuleManager::addInMemoryBuffer(StringRef FileName,\n std::unique_ptr Buffer) {\n\n const FileEntry *Entry =\n FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);\n InMemoryBuffers[Entry] = std::move(Buffer);\n}\n\nModuleManager::VisitState *ModuleManager::allocateVisitState() {\n \/\/ Fast path: if we have a cached state, use it.\n if (FirstVisitState) {\n VisitState *Result = FirstVisitState;\n FirstVisitState = FirstVisitState->NextState;\n Result->NextState = nullptr;\n return Result;\n }\n\n \/\/ Allocate and return a new state.\n return new VisitState(size());\n}\n\nvoid ModuleManager::returnVisitState(VisitState *State) {\n assert(State->NextState == nullptr && \"Visited state is in list?\");\n State->NextState = FirstVisitState;\n FirstVisitState = State;\n}\n\nvoid ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {\n GlobalIndex = Index;\n if (!GlobalIndex) {\n ModulesInCommonWithGlobalIndex.clear();\n return;\n }\n\n \/\/ Notify the global module index about all of the modules we've already\n \/\/ loaded.\n for (ModuleFile &M : *this)\n if (!GlobalIndex->loadedModuleFile(&M))\n ModulesInCommonWithGlobalIndex.push_back(&M);\n}\n\nvoid ModuleManager::moduleFileAccepted(ModuleFile *MF) {\n if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))\n return;\n\n ModulesInCommonWithGlobalIndex.push_back(MF);\n}\n\nModuleManager::ModuleManager(FileManager &FileMgr,\n const PCHContainerReader &PCHContainerRdr)\n : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr), GlobalIndex(),\n FirstVisitState(nullptr) {}\n\nModuleManager::~ModuleManager() { delete FirstVisitState; }\n\nvoid ModuleManager::visit(llvm::function_ref Visitor,\n llvm::SmallPtrSetImpl *ModuleFilesHit) {\n \/\/ If the visitation order vector is the wrong size, recompute the order.\n if (VisitOrder.size() != Chain.size()) {\n unsigned N = size();\n VisitOrder.clear();\n VisitOrder.reserve(N);\n \n \/\/ Record the number of incoming edges for each module. When we\n \/\/ encounter a module with no incoming edges, push it into the queue\n \/\/ to seed the queue.\n SmallVector Queue;\n Queue.reserve(N);\n llvm::SmallVector UnusedIncomingEdges;\n UnusedIncomingEdges.resize(size());\n for (ModuleFile &M : llvm::reverse(*this)) {\n unsigned Size = M.ImportedBy.size();\n UnusedIncomingEdges[M.Index] = Size;\n if (!Size)\n Queue.push_back(&M);\n }\n\n \/\/ Traverse the graph, making sure to visit a module before visiting any\n \/\/ of its dependencies.\n while (!Queue.empty()) {\n ModuleFile *CurrentModule = Queue.pop_back_val();\n VisitOrder.push_back(CurrentModule);\n\n \/\/ For any module that this module depends on, push it on the\n \/\/ stack (if it hasn't already been marked as visited).\n for (auto M = CurrentModule->Imports.rbegin(),\n MEnd = CurrentModule->Imports.rend();\n M != MEnd; ++M) {\n \/\/ Remove our current module as an impediment to visiting the\n \/\/ module we depend on. If we were the last unvisited module\n \/\/ that depends on this particular module, push it into the\n \/\/ queue to be visited.\n unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];\n if (NumUnusedEdges && (--NumUnusedEdges == 0))\n Queue.push_back(*M);\n }\n }\n\n assert(VisitOrder.size() == N && \"Visitation order is wrong?\");\n\n delete FirstVisitState;\n FirstVisitState = nullptr;\n }\n\n VisitState *State = allocateVisitState();\n unsigned VisitNumber = State->NextVisitNumber++;\n\n \/\/ If the caller has provided us with a hit-set that came from the global\n \/\/ module index, mark every module file in common with the global module\n \/\/ index that is *not* in that set as 'visited'.\n if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {\n for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)\n {\n ModuleFile *M = ModulesInCommonWithGlobalIndex[I];\n if (!ModuleFilesHit->count(M))\n State->VisitNumber[M->Index] = VisitNumber;\n }\n }\n\n for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {\n ModuleFile *CurrentModule = VisitOrder[I];\n \/\/ Should we skip this module file?\n if (State->VisitNumber[CurrentModule->Index] == VisitNumber)\n continue;\n\n \/\/ Visit the module.\n assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);\n State->VisitNumber[CurrentModule->Index] = VisitNumber;\n if (!Visitor(*CurrentModule))\n continue;\n\n \/\/ The visitor has requested that cut off visitation of any\n \/\/ module that the current module depends on. To indicate this\n \/\/ behavior, we mark all of the reachable modules as having been visited.\n ModuleFile *NextModule = CurrentModule;\n do {\n \/\/ For any module that this module depends on, push it on the\n \/\/ stack (if it hasn't already been marked as visited).\n for (llvm::SetVector::iterator\n M = NextModule->Imports.begin(),\n MEnd = NextModule->Imports.end();\n M != MEnd; ++M) {\n if (State->VisitNumber[(*M)->Index] != VisitNumber) {\n State->Stack.push_back(*M);\n State->VisitNumber[(*M)->Index] = VisitNumber;\n }\n }\n\n if (State->Stack.empty())\n break;\n\n \/\/ Pop the next module off the stack.\n NextModule = State->Stack.pop_back_val();\n } while (true);\n }\n\n returnVisitState(State);\n}\n\nbool ModuleManager::lookupModuleFile(StringRef FileName,\n off_t ExpectedSize,\n time_t ExpectedModTime,\n const FileEntry *&File) {\n if (FileName == \"-\") {\n File = nullptr;\n return false;\n }\n\n \/\/ Open the file immediately to ensure there is no race between stat'ing and\n \/\/ opening the file.\n File = FileMgr.getFile(FileName, \/*openFile=*\/true, \/*cacheFailure=*\/false);\n if (!File)\n return false;\n\n if ((ExpectedSize && ExpectedSize != File->getSize()) ||\n (ExpectedModTime && ExpectedModTime != File->getModificationTime()))\n \/\/ Do not destroy File, as it may be referenced. If we need to rebuild it,\n \/\/ it will be destroyed by removeModules.\n return true;\n\n return false;\n}\n\n#ifndef NDEBUG\nnamespace llvm {\n template<>\n struct GraphTraits {\n typedef ModuleFile *NodeRef;\n typedef llvm::SetVector::const_iterator ChildIteratorType;\n typedef pointer_iterator nodes_iterator;\n\n static ChildIteratorType child_begin(NodeRef Node) {\n return Node->Imports.begin();\n }\n\n static ChildIteratorType child_end(NodeRef Node) {\n return Node->Imports.end();\n }\n \n static nodes_iterator nodes_begin(const ModuleManager &Manager) {\n return nodes_iterator(Manager.begin());\n }\n \n static nodes_iterator nodes_end(const ModuleManager &Manager) {\n return nodes_iterator(Manager.end());\n }\n };\n \n template<>\n struct DOTGraphTraits : public DefaultDOTGraphTraits {\n explicit DOTGraphTraits(bool IsSimple = false)\n : DefaultDOTGraphTraits(IsSimple) { }\n \n static bool renderGraphFromBottomUp() {\n return true;\n }\n\n std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {\n return M->ModuleName;\n }\n };\n}\n\nvoid ModuleManager::viewGraph() {\n llvm::ViewGraph(*this, \"Modules\");\n}\n#endif\nModules: Fix a minor performance bug from r293393\/\/===--- ModuleManager.cpp - Module Manager ---------------------*- 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\/\/ This file defines the ModuleManager class, which manages a set of loaded\n\/\/ modules for the ASTReader.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"clang\/Serialization\/ModuleManager.h\"\n#include \"clang\/Frontend\/PCHContainerOperations.h\"\n#include \"clang\/Lex\/HeaderSearch.h\"\n#include \"clang\/Lex\/ModuleMap.h\"\n#include \"clang\/Serialization\/GlobalModuleIndex.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \n\n#ifndef NDEBUG\n#include \"llvm\/Support\/GraphWriter.h\"\n#endif\n\nusing namespace clang;\nusing namespace serialization;\n\nModuleFile *ModuleManager::lookup(StringRef Name) {\n const FileEntry *Entry = FileMgr.getFile(Name, \/*openFile=*\/false,\n \/*cacheFailure=*\/false);\n if (Entry)\n return lookup(Entry);\n\n return nullptr;\n}\n\nModuleFile *ModuleManager::lookup(const FileEntry *File) {\n llvm::DenseMap::iterator Known\n = Modules.find(File);\n if (Known == Modules.end())\n return nullptr;\n\n return Known->second;\n}\n\nstd::unique_ptr\nModuleManager::lookupBuffer(StringRef Name) {\n const FileEntry *Entry = FileMgr.getFile(Name, \/*openFile=*\/false,\n \/*cacheFailure=*\/false);\n return std::move(InMemoryBuffers[Entry]);\n}\n\nstatic bool checkSignature(ASTFileSignature Signature,\n ASTFileSignature ExpectedSignature,\n std::string &ErrorStr) {\n if (!ExpectedSignature || Signature == ExpectedSignature)\n return false;\n\n ErrorStr =\n Signature ? \"signature mismatch\" : \"could not read module signature\";\n return true;\n}\n\nstatic void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,\n SourceLocation ImportLoc) {\n if (ImportedBy) {\n MF.ImportedBy.insert(ImportedBy);\n ImportedBy->Imports.insert(&MF);\n } else {\n if (!MF.DirectlyImported)\n MF.ImportLoc = ImportLoc;\n\n MF.DirectlyImported = true;\n }\n}\n\nModuleManager::AddModuleResult\nModuleManager::addModule(StringRef FileName, ModuleKind Type,\n SourceLocation ImportLoc, ModuleFile *ImportedBy,\n unsigned Generation,\n off_t ExpectedSize, time_t ExpectedModTime,\n ASTFileSignature ExpectedSignature,\n ASTFileSignatureReader ReadSignature,\n ModuleFile *&Module,\n std::string &ErrorStr) {\n Module = nullptr;\n\n \/\/ Look for the file entry. This only fails if the expected size or\n \/\/ modification time differ.\n const FileEntry *Entry;\n if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {\n \/\/ If we're not expecting to pull this file out of the module cache, it\n \/\/ might have a different mtime due to being moved across filesystems in\n \/\/ a distributed build. The size must still match, though. (As must the\n \/\/ contents, but we can't check that.)\n ExpectedModTime = 0;\n }\n if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {\n ErrorStr = \"module file out of date\";\n return OutOfDate;\n }\n\n if (!Entry && FileName != \"-\") {\n ErrorStr = \"module file not found\";\n return Missing;\n }\n\n \/\/ Check whether we already loaded this module, before\n if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {\n \/\/ Check the stored signature.\n if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))\n return OutOfDate;\n\n Module = ModuleEntry;\n updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);\n return AlreadyLoaded;\n }\n\n \/\/ Allocate a new module.\n auto NewModule = llvm::make_unique(Type, Generation);\n NewModule->Index = Chain.size();\n NewModule->FileName = FileName.str();\n NewModule->File = Entry;\n NewModule->ImportLoc = ImportLoc;\n NewModule->InputFilesValidationTimestamp = 0;\n\n if (NewModule->Kind == MK_ImplicitModule) {\n std::string TimestampFilename = NewModule->getTimestampFilename();\n vfs::Status Status;\n \/\/ A cached stat value would be fine as well.\n if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))\n NewModule->InputFilesValidationTimestamp =\n llvm::sys::toTimeT(Status.getLastModificationTime());\n }\n\n \/\/ Load the contents of the module\n if (std::unique_ptr Buffer = lookupBuffer(FileName)) {\n \/\/ The buffer was already provided for us.\n NewModule->Buffer = std::move(Buffer);\n } else {\n \/\/ Open the AST file.\n llvm::ErrorOr> Buf((std::error_code()));\n if (FileName == \"-\") {\n Buf = llvm::MemoryBuffer::getSTDIN();\n } else {\n \/\/ Leave the FileEntry open so if it gets read again by another\n \/\/ ModuleManager it must be the same underlying file.\n \/\/ FIXME: Because FileManager::getFile() doesn't guarantee that it will\n \/\/ give us an open file, this may not be 100% reliable.\n Buf = FileMgr.getBufferForFile(NewModule->File,\n \/*IsVolatile=*\/false,\n \/*ShouldClose=*\/false);\n }\n\n if (!Buf) {\n ErrorStr = Buf.getError().message();\n return Missing;\n }\n\n NewModule->Buffer = std::move(*Buf);\n }\n\n \/\/ Initialize the stream.\n NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);\n\n \/\/ Read the signature eagerly now so that we can check it. Avoid calling\n \/\/ ReadSignature unless there's something to check though.\n if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),\n ExpectedSignature, ErrorStr))\n return OutOfDate;\n\n \/\/ We're keeping this module. Store it everywhere.\n Module = Modules[Entry] = NewModule.get();\n\n updateModuleImports(*NewModule, ImportedBy, ImportLoc);\n\n if (!NewModule->isModule())\n PCHChain.push_back(NewModule.get());\n if (!ImportedBy)\n Roots.push_back(NewModule.get());\n\n Chain.push_back(std::move(NewModule));\n return NewlyLoaded;\n}\n\nvoid ModuleManager::removeModules(\n ModuleIterator First,\n llvm::SmallPtrSetImpl &LoadedSuccessfully,\n ModuleMap *modMap) {\n auto Last = end();\n if (First == Last)\n return;\n\n\n \/\/ Explicitly clear VisitOrder since we might not notice it is stale.\n VisitOrder.clear();\n\n \/\/ Collect the set of module file pointers that we'll be removing.\n llvm::SmallPtrSet victimSet(\n (llvm::pointer_iterator(First)),\n (llvm::pointer_iterator(Last)));\n\n auto IsVictim = [&](ModuleFile *MF) {\n return victimSet.count(MF);\n };\n \/\/ Remove any references to the now-destroyed modules.\n for (auto I = begin(); I != First; ++I) {\n I->Imports.remove_if(IsVictim);\n I->ImportedBy.remove_if(IsVictim);\n }\n Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),\n Roots.end());\n\n \/\/ Remove the modules from the PCH chain.\n for (auto I = First; I != Last; ++I) {\n if (!I->isModule()) {\n PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), &*I),\n PCHChain.end());\n break;\n }\n }\n\n \/\/ Delete the modules and erase them from the various structures.\n for (ModuleIterator victim = First; victim != Last; ++victim) {\n Modules.erase(victim->File);\n\n if (modMap) {\n StringRef ModuleName = victim->ModuleName;\n if (Module *mod = modMap->findModule(ModuleName)) {\n mod->setASTFile(nullptr);\n }\n }\n\n \/\/ Files that didn't make it through ReadASTCore successfully will be\n \/\/ rebuilt (or there was an error). Invalidate them so that we can load the\n \/\/ new files that will be renamed over the old ones.\n if (LoadedSuccessfully.count(&*victim) == 0)\n FileMgr.invalidateCache(victim->File);\n }\n\n \/\/ Delete the modules.\n Chain.erase(Chain.begin() + (First - begin()), Chain.end());\n}\n\nvoid\nModuleManager::addInMemoryBuffer(StringRef FileName,\n std::unique_ptr Buffer) {\n\n const FileEntry *Entry =\n FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);\n InMemoryBuffers[Entry] = std::move(Buffer);\n}\n\nModuleManager::VisitState *ModuleManager::allocateVisitState() {\n \/\/ Fast path: if we have a cached state, use it.\n if (FirstVisitState) {\n VisitState *Result = FirstVisitState;\n FirstVisitState = FirstVisitState->NextState;\n Result->NextState = nullptr;\n return Result;\n }\n\n \/\/ Allocate and return a new state.\n return new VisitState(size());\n}\n\nvoid ModuleManager::returnVisitState(VisitState *State) {\n assert(State->NextState == nullptr && \"Visited state is in list?\");\n State->NextState = FirstVisitState;\n FirstVisitState = State;\n}\n\nvoid ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {\n GlobalIndex = Index;\n if (!GlobalIndex) {\n ModulesInCommonWithGlobalIndex.clear();\n return;\n }\n\n \/\/ Notify the global module index about all of the modules we've already\n \/\/ loaded.\n for (ModuleFile &M : *this)\n if (!GlobalIndex->loadedModuleFile(&M))\n ModulesInCommonWithGlobalIndex.push_back(&M);\n}\n\nvoid ModuleManager::moduleFileAccepted(ModuleFile *MF) {\n if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))\n return;\n\n ModulesInCommonWithGlobalIndex.push_back(MF);\n}\n\nModuleManager::ModuleManager(FileManager &FileMgr,\n const PCHContainerReader &PCHContainerRdr)\n : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr), GlobalIndex(),\n FirstVisitState(nullptr) {}\n\nModuleManager::~ModuleManager() { delete FirstVisitState; }\n\nvoid ModuleManager::visit(llvm::function_ref Visitor,\n llvm::SmallPtrSetImpl *ModuleFilesHit) {\n \/\/ If the visitation order vector is the wrong size, recompute the order.\n if (VisitOrder.size() != Chain.size()) {\n unsigned N = size();\n VisitOrder.clear();\n VisitOrder.reserve(N);\n \n \/\/ Record the number of incoming edges for each module. When we\n \/\/ encounter a module with no incoming edges, push it into the queue\n \/\/ to seed the queue.\n SmallVector Queue;\n Queue.reserve(N);\n llvm::SmallVector UnusedIncomingEdges;\n UnusedIncomingEdges.resize(size());\n for (ModuleFile &M : llvm::reverse(*this)) {\n unsigned Size = M.ImportedBy.size();\n UnusedIncomingEdges[M.Index] = Size;\n if (!Size)\n Queue.push_back(&M);\n }\n\n \/\/ Traverse the graph, making sure to visit a module before visiting any\n \/\/ of its dependencies.\n while (!Queue.empty()) {\n ModuleFile *CurrentModule = Queue.pop_back_val();\n VisitOrder.push_back(CurrentModule);\n\n \/\/ For any module that this module depends on, push it on the\n \/\/ stack (if it hasn't already been marked as visited).\n for (auto M = CurrentModule->Imports.rbegin(),\n MEnd = CurrentModule->Imports.rend();\n M != MEnd; ++M) {\n \/\/ Remove our current module as an impediment to visiting the\n \/\/ module we depend on. If we were the last unvisited module\n \/\/ that depends on this particular module, push it into the\n \/\/ queue to be visited.\n unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];\n if (NumUnusedEdges && (--NumUnusedEdges == 0))\n Queue.push_back(*M);\n }\n }\n\n assert(VisitOrder.size() == N && \"Visitation order is wrong?\");\n\n delete FirstVisitState;\n FirstVisitState = nullptr;\n }\n\n VisitState *State = allocateVisitState();\n unsigned VisitNumber = State->NextVisitNumber++;\n\n \/\/ If the caller has provided us with a hit-set that came from the global\n \/\/ module index, mark every module file in common with the global module\n \/\/ index that is *not* in that set as 'visited'.\n if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {\n for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)\n {\n ModuleFile *M = ModulesInCommonWithGlobalIndex[I];\n if (!ModuleFilesHit->count(M))\n State->VisitNumber[M->Index] = VisitNumber;\n }\n }\n\n for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {\n ModuleFile *CurrentModule = VisitOrder[I];\n \/\/ Should we skip this module file?\n if (State->VisitNumber[CurrentModule->Index] == VisitNumber)\n continue;\n\n \/\/ Visit the module.\n assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);\n State->VisitNumber[CurrentModule->Index] = VisitNumber;\n if (!Visitor(*CurrentModule))\n continue;\n\n \/\/ The visitor has requested that cut off visitation of any\n \/\/ module that the current module depends on. To indicate this\n \/\/ behavior, we mark all of the reachable modules as having been visited.\n ModuleFile *NextModule = CurrentModule;\n do {\n \/\/ For any module that this module depends on, push it on the\n \/\/ stack (if it hasn't already been marked as visited).\n for (llvm::SetVector::iterator\n M = NextModule->Imports.begin(),\n MEnd = NextModule->Imports.end();\n M != MEnd; ++M) {\n if (State->VisitNumber[(*M)->Index] != VisitNumber) {\n State->Stack.push_back(*M);\n State->VisitNumber[(*M)->Index] = VisitNumber;\n }\n }\n\n if (State->Stack.empty())\n break;\n\n \/\/ Pop the next module off the stack.\n NextModule = State->Stack.pop_back_val();\n } while (true);\n }\n\n returnVisitState(State);\n}\n\nbool ModuleManager::lookupModuleFile(StringRef FileName,\n off_t ExpectedSize,\n time_t ExpectedModTime,\n const FileEntry *&File) {\n if (FileName == \"-\") {\n File = nullptr;\n return false;\n }\n\n \/\/ Open the file immediately to ensure there is no race between stat'ing and\n \/\/ opening the file.\n File = FileMgr.getFile(FileName, \/*openFile=*\/true, \/*cacheFailure=*\/false);\n if (!File)\n return false;\n\n if ((ExpectedSize && ExpectedSize != File->getSize()) ||\n (ExpectedModTime && ExpectedModTime != File->getModificationTime()))\n \/\/ Do not destroy File, as it may be referenced. If we need to rebuild it,\n \/\/ it will be destroyed by removeModules.\n return true;\n\n return false;\n}\n\n#ifndef NDEBUG\nnamespace llvm {\n template<>\n struct GraphTraits {\n typedef ModuleFile *NodeRef;\n typedef llvm::SetVector::const_iterator ChildIteratorType;\n typedef pointer_iterator nodes_iterator;\n\n static ChildIteratorType child_begin(NodeRef Node) {\n return Node->Imports.begin();\n }\n\n static ChildIteratorType child_end(NodeRef Node) {\n return Node->Imports.end();\n }\n \n static nodes_iterator nodes_begin(const ModuleManager &Manager) {\n return nodes_iterator(Manager.begin());\n }\n \n static nodes_iterator nodes_end(const ModuleManager &Manager) {\n return nodes_iterator(Manager.end());\n }\n };\n \n template<>\n struct DOTGraphTraits : public DefaultDOTGraphTraits {\n explicit DOTGraphTraits(bool IsSimple = false)\n : DefaultDOTGraphTraits(IsSimple) { }\n \n static bool renderGraphFromBottomUp() {\n return true;\n }\n\n std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {\n return M->ModuleName;\n }\n };\n}\n\nvoid ModuleManager::viewGraph() {\n llvm::ViewGraph(*this, \"Modules\");\n}\n#endif\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/ocmb\/odyssey\/procedures\/hwp\/memory\/lib\/mc\/ody_port.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2019,2022 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/ EKB-Mirror-To: hostboot\n\n\/\/\/\n\/\/\/ @file ody_port.C\n\/\/\/ @brief Odyssey specializations for memory ports\n\/\/\/\n\/\/ *HWP HWP Owner: Louis Stermole \n\/\/ *HWP HWP Backup: Stephen Glancy \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB:FSP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace mss\n{\nconst std::vector portTraits< mss::mc_type::ODYSSEY >::NON_SPARE_NIBBLES =\n{\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n \/\/ Byte 5 contains the spares (if they exist) for mc_type\n 12,\n 13,\n 14,\n 15,\n 16,\n 17,\n 18,\n 19,\n};\n\nconst std::vector portTraits< mss::mc_type::ODYSSEY >::SPARE_NIBBLES =\n{\n \/\/ Byte 5 contains the spares (if they exist) for mc_type\n 10,\n 11\n};\n\n\/\/\/\n\/\/\/ @brief Configures the write reorder queue bit - Odyssey specialization\n\/\/\/ @param[in] i_target the target to effect\n\/\/\/ @param[in] i_state to set the bit too\n\/\/\/ @return FAPI2_RC_SUCCSS iff ok\n\/\/\/ @NOTE: Due to RRQ and WRQ being combined into ROQ this function is now NOOP\n\/\/\/\ntemplate< >\nfapi2::ReturnCode configure_wrq(\n const fapi2::Target& i_target,\n const mss::states i_state)\n{\n return fapi2::FAPI2_RC_SUCCESS;\n}\n\n\/\/\/\n\/\/\/ @brief Configures the read reorder queue bit - Odyssey specialization\n\/\/\/ @param[in] i_target the target to effect\n\/\/\/ @param[in] i_state to set the bit too\n\/\/\/ @return FAPI2_RC_SUCCSS iff ok\n\/\/\/\ntemplate< >\nfapi2::ReturnCode configure_rrq(\n const fapi2::Target& i_target,\n const mss::states i_state)\n{\n using TT = portTraits;\n fapi2::buffer l_data;\n\n \/\/ Gets the reg\n FAPI_TRY(mss::getScom(i_target, TT::ROQ_REG, l_data), \"%s failed to getScom from ROQ0Q\",\n mss::c_str(i_target));\n\n \/\/ Sets the bit\n l_data.writeBit(i_state == mss::states::ON);\n\n \/\/ Sets the regs\n FAPI_TRY(mss::putScom(i_target, TT::ROQ_REG, l_data), \"%s failed to putScom to ROQ0Q\",\n mss::c_str(i_target));\n\n return fapi2::FAPI2_RC_SUCCESS;\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\nnamespace ody\n{\n\n\/\/\/\n\/\/\/ @brief Initializes the DFI interface\n\/\/\/ @param[in] i_target the target to check for DFI interface completion\n\/\/\/ @return FAPI2_RC_SUCCSS iff ok\n\/\/\/\nfapi2::ReturnCode poll_for_dfi_init_complete( const fapi2::Target& i_target )\n{\n\n \/\/ For each port...\n for(const auto& l_port : mss::find_targets(i_target))\n {\n \/\/ ... Polls for the DFI init complete\n FAPI_TRY(poll_for_dfi_init_complete(l_port));\n }\n\n return fapi2::FAPI2_RC_SUCCESS;\nfapi_try_exit:\n return fapi2::current_err;\n\n}\n\n\/\/\/\n\/\/\/ @brief Initializes the DFI interface\n\/\/\/ @param[in] i_target the target to check for DFI interface completion\n\/\/\/ @return FAPI2_RC_SUCCSS iff ok\n\/\/\/\nfapi2::ReturnCode poll_for_dfi_init_complete( const fapi2::Target& i_target )\n{\n using TT = mss::portTraits< mss::mc_type::ODYSSEY >;\n const auto& l_ocmb = mss::find_target(i_target);\n\n \/\/ Each PHY (aka port target) has its own DFI complete bit\n \/\/ As such, depending upon the port in question, the DFI complete bit is different\n const uint64_t DFI_COMPLETE_BIT = mss::relative_pos\n (i_target) == 0 ?\n TT::DFI_INIT_COMPLETE0 : TT::DFI_INIT_COMPLETE1;\n\n\n fapi2::buffer l_data;\n mss::poll_parameters l_poll_params(DELAY_10NS,\n 200,\n mss::DELAY_1MS,\n 200,\n 200);\n\n \/\/ Poll for getting 1 at the DFI complete bit\n bool l_poll_return = mss::poll(l_ocmb, l_poll_params, [&l_ocmb, &DFI_COMPLETE_BIT]()->bool\n {\n fapi2::buffer l_data;\n FAPI_TRY(fapi2::getScom(l_ocmb, TT::FARB6Q_REG, l_data));\n return l_data.getBit(DFI_COMPLETE_BIT);\n\n fapi_try_exit:\n FAPI_ERR(\"mss::poll() hit an error in mss::getScom\");\n return false;\n });\n\n \/\/ following FAPI_TRY to preserve the scom failure in lambda.\n FAPI_TRY(fapi2::current_err);\n FAPI_ASSERT(l_poll_return,\n fapi2::ODY_DRAMINIT_DFI_INIT_TIMEOUT().\n set_PORT_TARGET(i_target),\n TARGTIDFORMAT \" poll for DFI init complete timed out\", TARGTID);\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n} \/\/ ody\n\n} \/\/ mss\nAdds trace to Odyssey DFI polling functionality\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/ocmb\/odyssey\/procedures\/hwp\/memory\/lib\/mc\/ody_port.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2019,2022 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/ EKB-Mirror-To: hostboot\n\n\/\/\/\n\/\/\/ @file ody_port.C\n\/\/\/ @brief Odyssey specializations for memory ports\n\/\/\/\n\/\/ *HWP HWP Owner: Louis Stermole \n\/\/ *HWP HWP Backup: Stephen Glancy \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB:FSP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace mss\n{\nconst std::vector portTraits< mss::mc_type::ODYSSEY >::NON_SPARE_NIBBLES =\n{\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n \/\/ Byte 5 contains the spares (if they exist) for mc_type\n 12,\n 13,\n 14,\n 15,\n 16,\n 17,\n 18,\n 19,\n};\n\nconst std::vector portTraits< mss::mc_type::ODYSSEY >::SPARE_NIBBLES =\n{\n \/\/ Byte 5 contains the spares (if they exist) for mc_type\n 10,\n 11\n};\n\n\/\/\/\n\/\/\/ @brief Configures the write reorder queue bit - Odyssey specialization\n\/\/\/ @param[in] i_target the target to effect\n\/\/\/ @param[in] i_state to set the bit too\n\/\/\/ @return FAPI2_RC_SUCCSS iff ok\n\/\/\/ @NOTE: Due to RRQ and WRQ being combined into ROQ this function is now NOOP\n\/\/\/\ntemplate< >\nfapi2::ReturnCode configure_wrq(\n const fapi2::Target& i_target,\n const mss::states i_state)\n{\n return fapi2::FAPI2_RC_SUCCESS;\n}\n\n\/\/\/\n\/\/\/ @brief Configures the read reorder queue bit - Odyssey specialization\n\/\/\/ @param[in] i_target the target to effect\n\/\/\/ @param[in] i_state to set the bit too\n\/\/\/ @return FAPI2_RC_SUCCSS iff ok\n\/\/\/\ntemplate< >\nfapi2::ReturnCode configure_rrq(\n const fapi2::Target& i_target,\n const mss::states i_state)\n{\n using TT = portTraits;\n fapi2::buffer l_data;\n\n \/\/ Gets the reg\n FAPI_TRY(mss::getScom(i_target, TT::ROQ_REG, l_data), \"%s failed to getScom from ROQ0Q\",\n mss::c_str(i_target));\n\n \/\/ Sets the bit\n l_data.writeBit(i_state == mss::states::ON);\n\n \/\/ Sets the regs\n FAPI_TRY(mss::putScom(i_target, TT::ROQ_REG, l_data), \"%s failed to putScom to ROQ0Q\",\n mss::c_str(i_target));\n\n return fapi2::FAPI2_RC_SUCCESS;\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\nnamespace ody\n{\n\n\/\/\/\n\/\/\/ @brief Initializes the DFI interface\n\/\/\/ @param[in] i_target the target to check for DFI interface completion\n\/\/\/ @return FAPI2_RC_SUCCSS iff ok\n\/\/\/\nfapi2::ReturnCode poll_for_dfi_init_complete( const fapi2::Target& i_target )\n{\n\n \/\/ For each port...\n for(const auto& l_port : mss::find_targets(i_target))\n {\n \/\/ ... Polls for the DFI init complete\n FAPI_TRY(poll_for_dfi_init_complete(l_port));\n }\n\n FAPI_INF(TARGTIDFORMAT \" DFI polling completed successfully\", TARGTID);\n\n return fapi2::FAPI2_RC_SUCCESS;\nfapi_try_exit:\n return fapi2::current_err;\n\n}\n\n\/\/\/\n\/\/\/ @brief Initializes the DFI interface\n\/\/\/ @param[in] i_target the target to check for DFI interface completion\n\/\/\/ @return FAPI2_RC_SUCCSS iff ok\n\/\/\/\nfapi2::ReturnCode poll_for_dfi_init_complete( const fapi2::Target& i_target )\n{\n using TT = mss::portTraits< mss::mc_type::ODYSSEY >;\n const auto& l_ocmb = mss::find_target(i_target);\n\n \/\/ Each PHY (aka port target) has its own DFI complete bit\n \/\/ As such, depending upon the port in question, the DFI complete bit is different\n const uint64_t DFI_COMPLETE_BIT = mss::relative_pos\n (i_target) == 0 ?\n TT::DFI_INIT_COMPLETE0 : TT::DFI_INIT_COMPLETE1;\n\n\n fapi2::buffer l_data;\n mss::poll_parameters l_poll_params(DELAY_10NS,\n 200,\n mss::DELAY_1MS,\n 200,\n 200);\n\n \/\/ Poll for getting 1 at the DFI complete bit\n bool l_poll_return = mss::poll(l_ocmb, l_poll_params, [&l_ocmb, &DFI_COMPLETE_BIT]()->bool\n {\n fapi2::buffer l_data;\n FAPI_TRY(fapi2::getScom(l_ocmb, TT::FARB6Q_REG, l_data));\n return l_data.getBit(DFI_COMPLETE_BIT);\n\n fapi_try_exit:\n FAPI_ERR(\"mss::poll() hit an error in mss::getScom\");\n return false;\n });\n\n \/\/ following FAPI_TRY to preserve the scom failure in lambda.\n FAPI_TRY(fapi2::current_err);\n FAPI_ASSERT(l_poll_return,\n fapi2::ODY_DRAMINIT_DFI_INIT_TIMEOUT().\n set_PORT_TARGET(i_target),\n TARGTIDFORMAT \" poll for DFI init complete timed out\", TARGTID);\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n} \/\/ ody\n\n} \/\/ mss\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/perv\/p10_core_checkstop_handler.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2018,2020 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/\/ @file p10_core_checkstop_handler.C\n\/\/\/ @brief Depending on input flag, trun local xstops into system xstops.\n\/\/\/\n\/\/\/ *HWP HW Maintainer: Manish Chowdhary \n\/\/\/ *HWP FW Maintainer: Dan Crowell \n\/\/\/ *HWP Consumed by: HB\n\/\/\/\n\n#include \"p10_core_checkstop_handler.H\"\n#include \"p10_scom_c_b.H\"\n#include \"p10_scom_c_d.H\"\n#include \"p10_scom_c_d_unused.H\"\n#include \"p10_scom_c_b_unused.H\"\n\nusing namespace scomt;\nusing namespace scomt::c;\n\nfapi2::ReturnCode p10_core_checkstop_handler(\n const fapi2::Target& i_target_core,\n bool i_override_restore)\n{\n FAPI_INF(\"Entering ...\");\n\n fapi2::buffer l_action0;\n fapi2::buffer l_action1;\n\n \/\/if true, save off the original action, and turn local xstops into system xstops.\n if(i_override_restore == CORE_XSTOP_HNDLR__SAVE_AND_ESCALATE)\n {\n\n \/\/ Getting ACTION0\n FAPI_TRY(GET_EC_PC_FIR_CORE_ACTION0(i_target_core, l_action0));\n\n\n \/\/ Getting ACTION1\n FAPI_TRY(GET_EC_PC_FIR_CORE_ACTION1(i_target_core, l_action1));\n\n \/\/ We want to save the original actions into an attribute for a save-restore\n FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_ORIG_FIR_SETTINGS_ACTION0, i_target_core, l_action0),\n \"Error from FAPI_ATTR_SET (ATTR_ORIG_FIR_SETTINGS_ACTION0)\");\n\n FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_ORIG_FIR_SETTINGS_ACTION1, i_target_core, l_action1),\n \"Error from FAPI_ATTR_SET (ATTR_ORIG_FIR_SETTINGS_ACTION1)\");\n\n \/\/ For every bit, turn every local xstop (0b11) into system xstops (0b00)\n uint64_t l_local_xstop = l_action0 & l_action1; \/\/gets bits that are both set to 1\n l_action0 &= ~l_local_xstop;\n l_action1 &= ~l_local_xstop;\n }\n else\n {\n \/\/ We want to pull out the original actions, and restore them\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_ORIG_FIR_SETTINGS_ACTION0, i_target_core, l_action0),\n \"Error from FAPI_ATTR_GET (ATTR_ORIG_FIR_SETTINGS_ACTION0)\");\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_ORIG_FIR_SETTINGS_ACTION1, i_target_core, l_action1),\n \"Error from FAPI_ATTR_GET (ATTR_ORIG_FIR_SETTINGS_ACTION1)\");\n }\n\n \/\/ Save off the current values of actions into the register\n FAPI_TRY(PREP_EC_PC_FIR_CORE_ACTION0(i_target_core));\n FAPI_TRY(PUT_EC_PC_FIR_CORE_ACTION0(i_target_core, l_action0));\n FAPI_TRY(PREP_EC_PC_FIR_CORE_ACTION1(i_target_core));\n FAPI_TRY(PUT_EC_PC_FIR_CORE_ACTION1(i_target_core, l_action1));\n\n FAPI_INF(\"Exiting ...\");\n\nfapi_try_exit:\n return fapi2::current_err;\n}\nUpdate register header files for dd2\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/perv\/p10_core_checkstop_handler.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2018,2020 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/\/ @file p10_core_checkstop_handler.C\n\/\/\/ @brief Depending on input flag, trun local xstops into system xstops.\n\/\/\/\n\/\/\/ *HWP HW Maintainer: Manish Chowdhary \n\/\/\/ *HWP FW Maintainer: Dan Crowell \n\/\/\/ *HWP Consumed by: HB\n\/\/\/\n\n#include \"p10_core_checkstop_handler.H\"\n#include \"p10_scom_c_b.H\"\n#include \"p10_scom_c_d.H\"\n\nusing namespace scomt;\nusing namespace scomt::c;\n\nfapi2::ReturnCode p10_core_checkstop_handler(\n const fapi2::Target& i_target_core,\n bool i_override_restore)\n{\n FAPI_INF(\"Entering ...\");\n\n fapi2::buffer l_action0;\n fapi2::buffer l_action1;\n\n \/\/if true, save off the original action, and turn local xstops into system xstops.\n if(i_override_restore == CORE_XSTOP_HNDLR__SAVE_AND_ESCALATE)\n {\n\n \/\/ Getting ACTION0\n FAPI_TRY(GET_EC_PC_FIR_CORE_ACTION0(i_target_core, l_action0));\n\n\n \/\/ Getting ACTION1\n FAPI_TRY(GET_EC_PC_FIR_CORE_ACTION1(i_target_core, l_action1));\n\n \/\/ We want to save the original actions into an attribute for a save-restore\n FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_ORIG_FIR_SETTINGS_ACTION0, i_target_core, l_action0),\n \"Error from FAPI_ATTR_SET (ATTR_ORIG_FIR_SETTINGS_ACTION0)\");\n\n FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_ORIG_FIR_SETTINGS_ACTION1, i_target_core, l_action1),\n \"Error from FAPI_ATTR_SET (ATTR_ORIG_FIR_SETTINGS_ACTION1)\");\n\n \/\/ For every bit, turn every local xstop (0b11) into system xstops (0b00)\n uint64_t l_local_xstop = l_action0 & l_action1; \/\/gets bits that are both set to 1\n l_action0 &= ~l_local_xstop;\n l_action1 &= ~l_local_xstop;\n }\n else\n {\n \/\/ We want to pull out the original actions, and restore them\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_ORIG_FIR_SETTINGS_ACTION0, i_target_core, l_action0),\n \"Error from FAPI_ATTR_GET (ATTR_ORIG_FIR_SETTINGS_ACTION0)\");\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_ORIG_FIR_SETTINGS_ACTION1, i_target_core, l_action1),\n \"Error from FAPI_ATTR_GET (ATTR_ORIG_FIR_SETTINGS_ACTION1)\");\n }\n\n \/\/ Save off the current values of actions into the register\n FAPI_TRY(PREP_EC_PC_FIR_CORE_ACTION0(i_target_core));\n FAPI_TRY(PUT_EC_PC_FIR_CORE_ACTION0(i_target_core, l_action0));\n FAPI_TRY(PREP_EC_PC_FIR_CORE_ACTION1(i_target_core));\n FAPI_TRY(PUT_EC_PC_FIR_CORE_ACTION1(i_target_core, l_action1));\n\n FAPI_INF(\"Exiting ...\");\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"\/\/===--- QueryDriverDatabase.cpp ---------------------------------*- C++-*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Some compiler drivers have implicit search mechanism for system headers.\n\/\/ This compilation database implementation tries to extract that information by\n\/\/ executing the driver in verbose mode. gcc-compatible drivers print something\n\/\/ like:\n\/\/ ....\n\/\/ ....\n\/\/ #include <...> search starts here:\n\/\/ \/usr\/lib\/gcc\/x86_64-linux-gnu\/7\/include\n\/\/ \/usr\/local\/include\n\/\/ \/usr\/lib\/gcc\/x86_64-linux-gnu\/7\/include-fixed\n\/\/ \/usr\/include\/x86_64-linux-gnu\n\/\/ \/usr\/include\n\/\/ End of search list.\n\/\/ ....\n\/\/ ....\n\/\/ This component parses that output and adds each path to command line args\n\/\/ provided by Base, after prepending them with -isystem. Therefore current\n\/\/ implementation would not work with a driver that is not gcc-compatible.\n\/\/\n\/\/ First argument of the command line received from underlying compilation\n\/\/ database is used as compiler driver path. Due to this arbitrary binary\n\/\/ execution, this mechanism is not used by default and only executes binaries\n\/\/ in the paths that are explicitly whitelisted by the user.\n\n#include \"GlobalCompilationDatabase.h\"\n#include \"Logger.h\"\n#include \"Path.h\"\n#include \"Trace.h\"\n#include \"clang\/Driver\/Types.h\"\n#include \"clang\/Tooling\/CompilationDatabase.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/ADT\/ScopeExit.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/iterator_range.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Program.h\"\n#include \"llvm\/Support\/Regex.h\"\n#include \"llvm\/Support\/ScopedPrinter.h\"\n#include \n#include \n#include \n#include \n\nnamespace clang {\nnamespace clangd {\nnamespace {\n\nstd::vector parseDriverOutput(llvm::StringRef Output) {\n std::vector SystemIncludes;\n constexpr char const *SIS = \"#include <...> search starts here:\";\n constexpr char const *SIE = \"End of search list.\";\n llvm::SmallVector Lines;\n Output.split(Lines, '\\n', \/*MaxSplit=*\/-1, \/*KeepEmpty=*\/false);\n\n auto StartIt =\n std::find_if(Lines.begin(), Lines.end(),\n [SIS](llvm::StringRef Line) { return Line.trim() == SIS; });\n if (StartIt == Lines.end()) {\n elog(\"System include extraction: start marker not found: {0}\", Output);\n return {};\n }\n ++StartIt;\n const auto EndIt = std::find(StartIt, Lines.end(), SIE);\n if (EndIt == Lines.end()) {\n elog(\"System include extraction: end marker missing: {0}\", Output);\n return {};\n }\n\n for (llvm::StringRef Line : llvm::make_range(StartIt, EndIt)) {\n SystemIncludes.push_back(Line.trim().str());\n vlog(\"System include extraction: adding {0}\", Line);\n }\n return SystemIncludes;\n}\n\nstd::vector extractSystemIncludes(PathRef Driver,\n llvm::StringRef Lang,\n llvm::Regex &QueryDriverRegex) {\n trace::Span Tracer(\"Extract system includes\");\n SPAN_ATTACH(Tracer, \"driver\", Driver);\n SPAN_ATTACH(Tracer, \"lang\", Lang);\n\n if (!QueryDriverRegex.match(Driver)) {\n vlog(\"System include extraction: not whitelisted driver {0}\", Driver);\n return {};\n }\n\n if (!llvm::sys::fs::exists(Driver)) {\n elog(\"System include extraction: {0} does not exist.\", Driver);\n return {};\n }\n if (!llvm::sys::fs::can_execute(Driver)) {\n elog(\"System include extraction: {0} is not executable.\", Driver);\n return {};\n }\n\n llvm::SmallString<128> StdErrPath;\n if (auto EC = llvm::sys::fs::createTemporaryFile(\"system-includes\", \"clangd\",\n StdErrPath)) {\n elog(\"System include extraction: failed to create temporary file with \"\n \"error {0}\",\n EC.message());\n return {};\n }\n auto CleanUp = llvm::make_scope_exit(\n [&StdErrPath]() { llvm::sys::fs::remove(StdErrPath); });\n\n llvm::Optional Redirects[] = {\n {\"\"}, {\"\"}, llvm::StringRef(StdErrPath)};\n\n \/\/ Should we also preserve flags like \"-sysroot\", \"-nostdinc\" ?\n const llvm::StringRef Args[] = {Driver, \"-E\", \"-x\", Lang, \"-\", \"-v\"};\n\n if (int RC = llvm::sys::ExecuteAndWait(Driver, Args, \/*Env=*\/llvm::None,\n Redirects)) {\n elog(\"System include extraction: driver execution failed with return code: \"\n \"{0}\",\n llvm::to_string(RC));\n return {};\n }\n\n auto BufOrError = llvm::MemoryBuffer::getFile(StdErrPath);\n if (!BufOrError) {\n elog(\"System include extraction: failed to read {0} with error {1}\",\n StdErrPath, BufOrError.getError().message());\n return {};\n }\n\n auto Includes = parseDriverOutput(BufOrError->get()->getBuffer());\n log(\"System include extractor: succesfully executed {0}, got includes: \"\n \"\\\"{1}\\\"\",\n Driver, llvm::join(Includes, \", \"));\n return Includes;\n}\n\ntooling::CompileCommand &\naddSystemIncludes(tooling::CompileCommand &Cmd,\n llvm::ArrayRef SystemIncludes) {\n for (llvm::StringRef Include : SystemIncludes) {\n \/\/ FIXME(kadircet): This doesn't work when we have \"--driver-mode=cl\"\n Cmd.CommandLine.push_back(\"-isystem\");\n Cmd.CommandLine.push_back(Include.str());\n }\n return Cmd;\n}\n\n\/\/\/ Converts a glob containing only ** or * into a regex.\nstd::string convertGlobToRegex(llvm::StringRef Glob) {\n std::string RegText;\n llvm::raw_string_ostream RegStream(RegText);\n RegStream << '^';\n for (size_t I = 0, E = Glob.size(); I < E; ++I) {\n if (Glob[I] == '*') {\n if (I + 1 < E && Glob[I + 1] == '*') {\n \/\/ Double star, accept any sequence.\n RegStream << \".*\";\n \/\/ Also skip the second star.\n ++I;\n } else {\n \/\/ Single star, accept any sequence without a slash.\n RegStream << \"[^\/]*\";\n }\n } else {\n RegStream << llvm::Regex::escape(Glob.substr(I, 1));\n }\n }\n RegStream << '$';\n RegStream.flush();\n return RegText;\n}\n\n\/\/\/ Converts a glob containing only ** or * into a regex.\nllvm::Regex convertGlobsToRegex(llvm::ArrayRef Globs) {\n assert(!Globs.empty() && \"Globs cannot be empty!\");\n std::vector RegTexts;\n RegTexts.reserve(Globs.size());\n for (llvm::StringRef Glob : Globs)\n RegTexts.push_back(convertGlobToRegex(Glob));\n\n llvm::Regex Reg(llvm::join(RegTexts, \"|\"));\n assert(Reg.isValid(RegTexts.front()) &&\n \"Created an invalid regex from globs\");\n return Reg;\n}\n\n\/\/\/ Extracts system includes from a trusted driver by parsing the output of\n\/\/\/ include search path and appends them to the commands coming from underlying\n\/\/\/ compilation database.\nclass QueryDriverDatabase : public GlobalCompilationDatabase {\npublic:\n QueryDriverDatabase(llvm::ArrayRef QueryDriverGlobs,\n std::unique_ptr Base)\n : QueryDriverRegex(convertGlobsToRegex(QueryDriverGlobs)),\n Base(std::move(Base)) {\n assert(this->Base);\n BaseChanged =\n this->Base->watch([this](const std::vector &Changes) {\n OnCommandChanged.broadcast(Changes);\n });\n }\n\n llvm::Optional\n getCompileCommand(PathRef File) const override {\n auto Cmd = Base->getCompileCommand(File);\n if (!Cmd || Cmd->CommandLine.empty())\n return Cmd;\n\n llvm::StringRef Lang;\n for (size_t I = 0, E = Cmd->CommandLine.size(); I < E; ++I) {\n llvm::StringRef Arg = Cmd->CommandLine[I];\n if (Arg == \"-x\" && I + 1 < E)\n Lang = Cmd->CommandLine[I + 1];\n else if (Arg.startswith(\"-x\"))\n Lang = Arg.drop_front(2).trim();\n }\n if (Lang.empty()) {\n llvm::StringRef Ext = llvm::sys::path::extension(File).trim('.');\n auto Type = driver::types::lookupTypeForExtension(Ext);\n if (Type == driver::types::TY_INVALID) {\n elog(\"System include extraction: invalid file type for {0}\", Ext);\n return {};\n }\n Lang = driver::types::getTypeName(Type);\n }\n\n llvm::SmallString<128> Driver(Cmd->CommandLine.front());\n llvm::sys::fs::make_absolute(Cmd->Directory, Driver);\n auto Key = std::make_pair(Driver.str(), Lang);\n\n std::vector SystemIncludes;\n {\n std::lock_guard Lock(Mu);\n\n auto It = DriverToIncludesCache.find(Key);\n if (It != DriverToIncludesCache.end())\n SystemIncludes = It->second;\n else\n DriverToIncludesCache[Key] = SystemIncludes =\n extractSystemIncludes(Key.first, Key.second, QueryDriverRegex);\n }\n\n return addSystemIncludes(*Cmd, SystemIncludes);\n }\n\n llvm::Optional getProjectInfo(PathRef File) const override {\n return Base->getProjectInfo(File);\n }\n\nprivate:\n mutable std::mutex Mu;\n \/\/ Caches includes extracted from a driver.\n mutable std::map,\n std::vector>\n DriverToIncludesCache;\n mutable llvm::Regex QueryDriverRegex;\n\n std::unique_ptr Base;\n CommandChanged::Subscription BaseChanged;\n};\n} \/\/ namespace\n\nstd::unique_ptr\ngetQueryDriverDatabase(llvm::ArrayRef QueryDriverGlobs,\n std::unique_ptr Base) {\n assert(Base && \"Null base to SystemIncludeExtractor\");\n if (QueryDriverGlobs.empty())\n return Base;\n return llvm::make_unique(QueryDriverGlobs,\n std::move(Base));\n}\n\n} \/\/ namespace clangd\n} \/\/ namespace clang\n[clangd] Fix Fix -Wunused-lambda-capture after r366339\/\/===--- QueryDriverDatabase.cpp ---------------------------------*- C++-*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Some compiler drivers have implicit search mechanism for system headers.\n\/\/ This compilation database implementation tries to extract that information by\n\/\/ executing the driver in verbose mode. gcc-compatible drivers print something\n\/\/ like:\n\/\/ ....\n\/\/ ....\n\/\/ #include <...> search starts here:\n\/\/ \/usr\/lib\/gcc\/x86_64-linux-gnu\/7\/include\n\/\/ \/usr\/local\/include\n\/\/ \/usr\/lib\/gcc\/x86_64-linux-gnu\/7\/include-fixed\n\/\/ \/usr\/include\/x86_64-linux-gnu\n\/\/ \/usr\/include\n\/\/ End of search list.\n\/\/ ....\n\/\/ ....\n\/\/ This component parses that output and adds each path to command line args\n\/\/ provided by Base, after prepending them with -isystem. Therefore current\n\/\/ implementation would not work with a driver that is not gcc-compatible.\n\/\/\n\/\/ First argument of the command line received from underlying compilation\n\/\/ database is used as compiler driver path. Due to this arbitrary binary\n\/\/ execution, this mechanism is not used by default and only executes binaries\n\/\/ in the paths that are explicitly whitelisted by the user.\n\n#include \"GlobalCompilationDatabase.h\"\n#include \"Logger.h\"\n#include \"Path.h\"\n#include \"Trace.h\"\n#include \"clang\/Driver\/Types.h\"\n#include \"clang\/Tooling\/CompilationDatabase.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/ADT\/ScopeExit.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/iterator_range.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Program.h\"\n#include \"llvm\/Support\/Regex.h\"\n#include \"llvm\/Support\/ScopedPrinter.h\"\n#include \n#include \n#include \n#include \n\nnamespace clang {\nnamespace clangd {\nnamespace {\n\nstd::vector parseDriverOutput(llvm::StringRef Output) {\n std::vector SystemIncludes;\n const char SIS[] = \"#include <...> search starts here:\";\n constexpr char const *SIE = \"End of search list.\";\n llvm::SmallVector Lines;\n Output.split(Lines, '\\n', \/*MaxSplit=*\/-1, \/*KeepEmpty=*\/false);\n\n auto StartIt = llvm::find_if(\n Lines, [SIS](llvm::StringRef Line) { return Line.trim() == SIS; });\n if (StartIt == Lines.end()) {\n elog(\"System include extraction: start marker not found: {0}\", Output);\n return {};\n }\n ++StartIt;\n const auto EndIt = std::find(StartIt, Lines.end(), SIE);\n if (EndIt == Lines.end()) {\n elog(\"System include extraction: end marker missing: {0}\", Output);\n return {};\n }\n\n for (llvm::StringRef Line : llvm::make_range(StartIt, EndIt)) {\n SystemIncludes.push_back(Line.trim().str());\n vlog(\"System include extraction: adding {0}\", Line);\n }\n return SystemIncludes;\n}\n\nstd::vector extractSystemIncludes(PathRef Driver,\n llvm::StringRef Lang,\n llvm::Regex &QueryDriverRegex) {\n trace::Span Tracer(\"Extract system includes\");\n SPAN_ATTACH(Tracer, \"driver\", Driver);\n SPAN_ATTACH(Tracer, \"lang\", Lang);\n\n if (!QueryDriverRegex.match(Driver)) {\n vlog(\"System include extraction: not whitelisted driver {0}\", Driver);\n return {};\n }\n\n if (!llvm::sys::fs::exists(Driver)) {\n elog(\"System include extraction: {0} does not exist.\", Driver);\n return {};\n }\n if (!llvm::sys::fs::can_execute(Driver)) {\n elog(\"System include extraction: {0} is not executable.\", Driver);\n return {};\n }\n\n llvm::SmallString<128> StdErrPath;\n if (auto EC = llvm::sys::fs::createTemporaryFile(\"system-includes\", \"clangd\",\n StdErrPath)) {\n elog(\"System include extraction: failed to create temporary file with \"\n \"error {0}\",\n EC.message());\n return {};\n }\n auto CleanUp = llvm::make_scope_exit(\n [&StdErrPath]() { llvm::sys::fs::remove(StdErrPath); });\n\n llvm::Optional Redirects[] = {\n {\"\"}, {\"\"}, llvm::StringRef(StdErrPath)};\n\n \/\/ Should we also preserve flags like \"-sysroot\", \"-nostdinc\" ?\n const llvm::StringRef Args[] = {Driver, \"-E\", \"-x\", Lang, \"-\", \"-v\"};\n\n if (int RC = llvm::sys::ExecuteAndWait(Driver, Args, \/*Env=*\/llvm::None,\n Redirects)) {\n elog(\"System include extraction: driver execution failed with return code: \"\n \"{0}\",\n llvm::to_string(RC));\n return {};\n }\n\n auto BufOrError = llvm::MemoryBuffer::getFile(StdErrPath);\n if (!BufOrError) {\n elog(\"System include extraction: failed to read {0} with error {1}\",\n StdErrPath, BufOrError.getError().message());\n return {};\n }\n\n auto Includes = parseDriverOutput(BufOrError->get()->getBuffer());\n log(\"System include extractor: succesfully executed {0}, got includes: \"\n \"\\\"{1}\\\"\",\n Driver, llvm::join(Includes, \", \"));\n return Includes;\n}\n\ntooling::CompileCommand &\naddSystemIncludes(tooling::CompileCommand &Cmd,\n llvm::ArrayRef SystemIncludes) {\n for (llvm::StringRef Include : SystemIncludes) {\n \/\/ FIXME(kadircet): This doesn't work when we have \"--driver-mode=cl\"\n Cmd.CommandLine.push_back(\"-isystem\");\n Cmd.CommandLine.push_back(Include.str());\n }\n return Cmd;\n}\n\n\/\/\/ Converts a glob containing only ** or * into a regex.\nstd::string convertGlobToRegex(llvm::StringRef Glob) {\n std::string RegText;\n llvm::raw_string_ostream RegStream(RegText);\n RegStream << '^';\n for (size_t I = 0, E = Glob.size(); I < E; ++I) {\n if (Glob[I] == '*') {\n if (I + 1 < E && Glob[I + 1] == '*') {\n \/\/ Double star, accept any sequence.\n RegStream << \".*\";\n \/\/ Also skip the second star.\n ++I;\n } else {\n \/\/ Single star, accept any sequence without a slash.\n RegStream << \"[^\/]*\";\n }\n } else {\n RegStream << llvm::Regex::escape(Glob.substr(I, 1));\n }\n }\n RegStream << '$';\n RegStream.flush();\n return RegText;\n}\n\n\/\/\/ Converts a glob containing only ** or * into a regex.\nllvm::Regex convertGlobsToRegex(llvm::ArrayRef Globs) {\n assert(!Globs.empty() && \"Globs cannot be empty!\");\n std::vector RegTexts;\n RegTexts.reserve(Globs.size());\n for (llvm::StringRef Glob : Globs)\n RegTexts.push_back(convertGlobToRegex(Glob));\n\n llvm::Regex Reg(llvm::join(RegTexts, \"|\"));\n assert(Reg.isValid(RegTexts.front()) &&\n \"Created an invalid regex from globs\");\n return Reg;\n}\n\n\/\/\/ Extracts system includes from a trusted driver by parsing the output of\n\/\/\/ include search path and appends them to the commands coming from underlying\n\/\/\/ compilation database.\nclass QueryDriverDatabase : public GlobalCompilationDatabase {\npublic:\n QueryDriverDatabase(llvm::ArrayRef QueryDriverGlobs,\n std::unique_ptr Base)\n : QueryDriverRegex(convertGlobsToRegex(QueryDriverGlobs)),\n Base(std::move(Base)) {\n assert(this->Base);\n BaseChanged =\n this->Base->watch([this](const std::vector &Changes) {\n OnCommandChanged.broadcast(Changes);\n });\n }\n\n llvm::Optional\n getCompileCommand(PathRef File) const override {\n auto Cmd = Base->getCompileCommand(File);\n if (!Cmd || Cmd->CommandLine.empty())\n return Cmd;\n\n llvm::StringRef Lang;\n for (size_t I = 0, E = Cmd->CommandLine.size(); I < E; ++I) {\n llvm::StringRef Arg = Cmd->CommandLine[I];\n if (Arg == \"-x\" && I + 1 < E)\n Lang = Cmd->CommandLine[I + 1];\n else if (Arg.startswith(\"-x\"))\n Lang = Arg.drop_front(2).trim();\n }\n if (Lang.empty()) {\n llvm::StringRef Ext = llvm::sys::path::extension(File).trim('.');\n auto Type = driver::types::lookupTypeForExtension(Ext);\n if (Type == driver::types::TY_INVALID) {\n elog(\"System include extraction: invalid file type for {0}\", Ext);\n return {};\n }\n Lang = driver::types::getTypeName(Type);\n }\n\n llvm::SmallString<128> Driver(Cmd->CommandLine.front());\n llvm::sys::fs::make_absolute(Cmd->Directory, Driver);\n auto Key = std::make_pair(Driver.str(), Lang);\n\n std::vector SystemIncludes;\n {\n std::lock_guard Lock(Mu);\n\n auto It = DriverToIncludesCache.find(Key);\n if (It != DriverToIncludesCache.end())\n SystemIncludes = It->second;\n else\n DriverToIncludesCache[Key] = SystemIncludes =\n extractSystemIncludes(Key.first, Key.second, QueryDriverRegex);\n }\n\n return addSystemIncludes(*Cmd, SystemIncludes);\n }\n\n llvm::Optional getProjectInfo(PathRef File) const override {\n return Base->getProjectInfo(File);\n }\n\nprivate:\n mutable std::mutex Mu;\n \/\/ Caches includes extracted from a driver.\n mutable std::map,\n std::vector>\n DriverToIncludesCache;\n mutable llvm::Regex QueryDriverRegex;\n\n std::unique_ptr Base;\n CommandChanged::Subscription BaseChanged;\n};\n} \/\/ namespace\n\nstd::unique_ptr\ngetQueryDriverDatabase(llvm::ArrayRef QueryDriverGlobs,\n std::unique_ptr Base) {\n assert(Base && \"Null base to SystemIncludeExtractor\");\n if (QueryDriverGlobs.empty())\n return Base;\n return llvm::make_unique(QueryDriverGlobs,\n std::move(Base));\n}\n\n} \/\/ namespace clangd\n} \/\/ namespace clang\n<|endoftext|>"} {"text":"\/\/Copyright (c) 2018 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"linearAlg2D.h\"\n\n#include \/\/ atan2\n#include \n#include \/\/ swap\n\n#include \"IntPoint.h\" \/\/ dot\n\nnamespace cura \n{\n\nfloat LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c)\n{\n const Point ba = a - b;\n const Point bc = c - b;\n const coord_t dott = dot(ba, bc); \/\/ dot product\n const coord_t det = ba.X * bc.Y - ba.Y * bc.X; \/\/ determinant\n const float angle = -atan2(det, dott); \/\/ from -pi to pi\n if (angle >= 0)\n {\n return angle;\n }\n else \n {\n return M_PI * 2 + angle;\n }\n}\n\n\nbool LinearAlg2D::getPointOnLineWithDist(const Point& p, const Point& a, const Point& b, const coord_t dist, Point& result)\n{\n \/\/ result\n \/\/ v\n \/\/ b<----r---a.......x\n \/\/ '-. :\n \/\/ '-. :\n \/\/ '-.p\n const Point ab = b - a;\n const coord_t ab_size = vSize(ab);\n const Point ap = p - a;\n const coord_t ax_size = (ab_size < 50)? dot(normal(ab, 1000), ap) \/ 1000 : dot(ab, ap) \/ ab_size;\n const coord_t ap_size2 = vSize2(ap);\n const coord_t px_size = sqrt(std::max(coord_t(0), ap_size2 - ax_size * ax_size));\n if (px_size > dist)\n {\n return false;\n }\n const coord_t xr_size = sqrt(dist * dist - px_size * px_size);\n if (ax_size <= 0)\n { \/\/ x lies before ab\n const coord_t ar_size = xr_size + ax_size;\n if (ar_size < 0 || ar_size > ab_size)\n { \/\/ r lies outisde of ab\n return false;\n }\n else\n {\n result = a + normal(ab, ar_size);\n return true;\n }\n }\n else if (ax_size >= ab_size)\n { \/\/ x lies after ab\n \/\/ result\n \/\/ v\n \/\/ a-----r-->b.......x\n \/\/ '-. :\n \/\/ '-. :\n \/\/ '-.p\n const coord_t ar_size = ax_size - xr_size;\n if (ar_size < 0 || ar_size > ab_size)\n { \/\/ r lies outisde of ab\n return false;\n }\n else\n {\n result = a + normal(ab, ar_size);\n return true;\n }\n }\n else \/\/ ax_size > 0 && ax_size < ab_size\n { \/\/ x lies on ab\n \/\/ result is either or\n \/\/ v v\n \/\/ a-----r-----------x-----------r----->b\n \/\/ '-. : .-'\n \/\/ '-. : .-'\n \/\/ '-.p.-'\n \/\/ or there is not result:\n \/\/ v v\n \/\/ r a-------x---->b r\n \/\/ '-. : .-'\n \/\/ '-. : .-'\n \/\/ '-.p.-'\n \/\/ try r in both directions\n const coord_t ar1_size = ax_size - xr_size;\n if (ar1_size >= 0)\n {\n result = a + normal(ab, ar1_size);\n return true;\n }\n const coord_t ar2_size = ax_size + xr_size;\n if (ar2_size < ab_size)\n {\n result = a + normal(ab, ar2_size);\n return true;\n }\n return false;\n }\n}\n\n\nstd::pair LinearAlg2D::getClosestConnection(Point a1, Point a2, Point b1, Point b2)\n{\n Point b1_on_a = getClosestOnLineSegment(b1, a1, a2);\n coord_t b1_on_a_dist2 = vSize2(b1_on_a - b1);\n Point b2_on_a = getClosestOnLineSegment(b2, a1, a2);\n coord_t b2_on_a_dist2 = vSize2(b2_on_a - b2);\n Point a1_on_b = getClosestOnLineSegment(a1, b1, b2);\n coord_t a1_on_b_dist2 = vSize2(a1_on_b - a1);\n Point a2_on_b = getClosestOnLineSegment(a1, b1, b2);\n coord_t a2_on_b_dist2 = vSize2(a2_on_b - a2);\n if (b1_on_a_dist2 < b2_on_a_dist2 && b1_on_a_dist2 < a1_on_b_dist2 && b1_on_a_dist2 < a2_on_b_dist2)\n {\n return std::make_pair(b1_on_a, b1);\n }\n else if (b2_on_a_dist2 < a1_on_b_dist2 && b2_on_a_dist2 < a2_on_b_dist2)\n {\n return std::make_pair(b2_on_a, b2);\n }\n else if (a1_on_b_dist2 < a2_on_b_dist2)\n {\n return std::make_pair(a1, a1_on_b);\n }\n else\n {\n return std::make_pair(a2, a2_on_b);\n }\n}\n\nbool LinearAlg2D::lineSegmentsCollide(const Point& a_from_transformed, const Point& a_to_transformed, Point b_from_transformed, Point b_to_transformed)\n{\n assert(std::abs(a_from_transformed.Y - a_to_transformed.Y) < 2 && \"line a is supposed to be transformed to be aligned with the X axis!\");\n assert(a_from_transformed.X - 2 <= a_to_transformed.X && \"line a is supposed to be aligned with X axis in positive direction!\");\n if ((b_from_transformed.Y >= a_from_transformed.Y && b_to_transformed.Y <= a_from_transformed.Y) || (b_to_transformed.Y >= a_from_transformed.Y && b_from_transformed.Y <= a_from_transformed.Y))\n {\n if(b_to_transformed.Y == b_from_transformed.Y)\n {\n if (b_to_transformed.X < b_from_transformed.X)\n {\n std::swap(b_to_transformed.X, b_from_transformed.X);\n }\n if (b_from_transformed.X > a_to_transformed.X)\n {\n return false;\n }\n if (b_to_transformed.X < a_from_transformed.X)\n {\n return false;\n }\n return true;\n }\n else\n {\n const coord_t x = b_from_transformed.X + (b_to_transformed.X - b_from_transformed.X) * (a_from_transformed.Y - b_from_transformed.Y) \/ (b_to_transformed.Y - b_from_transformed.Y);\n if (x >= a_from_transformed.X && x <= a_to_transformed.X)\n {\n return true;\n }\n }\n }\n return false;\n}\n\ncoord_t LinearAlg2D::getDist2FromLine(const Point& p, const Point& a, const Point& b)\n{\n \/\/ x.......a------------b\n \/\/ :\n \/\/ :\n \/\/ p\n \/\/ return px_size\n assert(a != b); \/\/ the line can't be a point\n const Point vab = b - a;\n const Point vap = p - a;\n const coord_t dott = dot(vab, vap);\n const coord_t ax_size2 = dott * dott \/ vSize2(vab);\n const coord_t ap_size2 = vSize2(vap);\n const coord_t px_size2 = std::max(coord_t(0), ap_size2 - ax_size2);\n return px_size2;\n}\n\n} \/\/ namespace cura\nAllow lines of length 0\/\/Copyright (c) 2019 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"linearAlg2D.h\"\n\n#include \/\/ atan2\n#include \n#include \/\/ swap\n\n#include \"IntPoint.h\" \/\/ dot\n\nnamespace cura \n{\n\nfloat LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c)\n{\n const Point ba = a - b;\n const Point bc = c - b;\n const coord_t dott = dot(ba, bc); \/\/ dot product\n const coord_t det = ba.X * bc.Y - ba.Y * bc.X; \/\/ determinant\n const float angle = -atan2(det, dott); \/\/ from -pi to pi\n if (angle >= 0)\n {\n return angle;\n }\n else \n {\n return M_PI * 2 + angle;\n }\n}\n\n\nbool LinearAlg2D::getPointOnLineWithDist(const Point& p, const Point& a, const Point& b, const coord_t dist, Point& result)\n{\n \/\/ result\n \/\/ v\n \/\/ b<----r---a.......x\n \/\/ '-. :\n \/\/ '-. :\n \/\/ '-.p\n const Point ab = b - a;\n const coord_t ab_size = vSize(ab);\n const Point ap = p - a;\n const coord_t ax_size = (ab_size < 50)? dot(normal(ab, 1000), ap) \/ 1000 : dot(ab, ap) \/ ab_size;\n const coord_t ap_size2 = vSize2(ap);\n const coord_t px_size = sqrt(std::max(coord_t(0), ap_size2 - ax_size * ax_size));\n if (px_size > dist)\n {\n return false;\n }\n const coord_t xr_size = sqrt(dist * dist - px_size * px_size);\n if (ax_size <= 0)\n { \/\/ x lies before ab\n const coord_t ar_size = xr_size + ax_size;\n if (ar_size < 0 || ar_size > ab_size)\n { \/\/ r lies outisde of ab\n return false;\n }\n else\n {\n result = a + normal(ab, ar_size);\n return true;\n }\n }\n else if (ax_size >= ab_size)\n { \/\/ x lies after ab\n \/\/ result\n \/\/ v\n \/\/ a-----r-->b.......x\n \/\/ '-. :\n \/\/ '-. :\n \/\/ '-.p\n const coord_t ar_size = ax_size - xr_size;\n if (ar_size < 0 || ar_size > ab_size)\n { \/\/ r lies outisde of ab\n return false;\n }\n else\n {\n result = a + normal(ab, ar_size);\n return true;\n }\n }\n else \/\/ ax_size > 0 && ax_size < ab_size\n { \/\/ x lies on ab\n \/\/ result is either or\n \/\/ v v\n \/\/ a-----r-----------x-----------r----->b\n \/\/ '-. : .-'\n \/\/ '-. : .-'\n \/\/ '-.p.-'\n \/\/ or there is not result:\n \/\/ v v\n \/\/ r a-------x---->b r\n \/\/ '-. : .-'\n \/\/ '-. : .-'\n \/\/ '-.p.-'\n \/\/ try r in both directions\n const coord_t ar1_size = ax_size - xr_size;\n if (ar1_size >= 0)\n {\n result = a + normal(ab, ar1_size);\n return true;\n }\n const coord_t ar2_size = ax_size + xr_size;\n if (ar2_size < ab_size)\n {\n result = a + normal(ab, ar2_size);\n return true;\n }\n return false;\n }\n}\n\n\nstd::pair LinearAlg2D::getClosestConnection(Point a1, Point a2, Point b1, Point b2)\n{\n Point b1_on_a = getClosestOnLineSegment(b1, a1, a2);\n coord_t b1_on_a_dist2 = vSize2(b1_on_a - b1);\n Point b2_on_a = getClosestOnLineSegment(b2, a1, a2);\n coord_t b2_on_a_dist2 = vSize2(b2_on_a - b2);\n Point a1_on_b = getClosestOnLineSegment(a1, b1, b2);\n coord_t a1_on_b_dist2 = vSize2(a1_on_b - a1);\n Point a2_on_b = getClosestOnLineSegment(a1, b1, b2);\n coord_t a2_on_b_dist2 = vSize2(a2_on_b - a2);\n if (b1_on_a_dist2 < b2_on_a_dist2 && b1_on_a_dist2 < a1_on_b_dist2 && b1_on_a_dist2 < a2_on_b_dist2)\n {\n return std::make_pair(b1_on_a, b1);\n }\n else if (b2_on_a_dist2 < a1_on_b_dist2 && b2_on_a_dist2 < a2_on_b_dist2)\n {\n return std::make_pair(b2_on_a, b2);\n }\n else if (a1_on_b_dist2 < a2_on_b_dist2)\n {\n return std::make_pair(a1, a1_on_b);\n }\n else\n {\n return std::make_pair(a2, a2_on_b);\n }\n}\n\nbool LinearAlg2D::lineSegmentsCollide(const Point& a_from_transformed, const Point& a_to_transformed, Point b_from_transformed, Point b_to_transformed)\n{\n assert(std::abs(a_from_transformed.Y - a_to_transformed.Y) < 2 && \"line a is supposed to be transformed to be aligned with the X axis!\");\n assert(a_from_transformed.X - 2 <= a_to_transformed.X && \"line a is supposed to be aligned with X axis in positive direction!\");\n if ((b_from_transformed.Y >= a_from_transformed.Y && b_to_transformed.Y <= a_from_transformed.Y) || (b_to_transformed.Y >= a_from_transformed.Y && b_from_transformed.Y <= a_from_transformed.Y))\n {\n if(b_to_transformed.Y == b_from_transformed.Y)\n {\n if (b_to_transformed.X < b_from_transformed.X)\n {\n std::swap(b_to_transformed.X, b_from_transformed.X);\n }\n if (b_from_transformed.X > a_to_transformed.X)\n {\n return false;\n }\n if (b_to_transformed.X < a_from_transformed.X)\n {\n return false;\n }\n return true;\n }\n else\n {\n const coord_t x = b_from_transformed.X + (b_to_transformed.X - b_from_transformed.X) * (a_from_transformed.Y - b_from_transformed.Y) \/ (b_to_transformed.Y - b_from_transformed.Y);\n if (x >= a_from_transformed.X && x <= a_to_transformed.X)\n {\n return true;\n }\n }\n }\n return false;\n}\n\ncoord_t LinearAlg2D::getDist2FromLine(const Point& p, const Point& a, const Point& b)\n{\n \/\/ x.......a------------b\n \/\/ :\n \/\/ :\n \/\/ p\n \/\/ return px_size\n const Point vab = b - a;\n const Point vap = p - a;\n const coord_t ab_size2 = vSize2(vab);\n const coord_t ap_size2 = vSize2(vap);\n if(ab_size2 == 0) \/\/Line of 0 length. Assume it's a line perpendicular to the direction to p.\n {\n return ap_size2;\n }\n const coord_t dott = dot(vab, vap);\n const coord_t ax_size2 = dott * dott \/ vSize2(vab);\n const coord_t px_size2 = std::max(coord_t(0), ap_size2 - ax_size2);\n return px_size2;\n}\n\n} \/\/ namespace cura\n<|endoftext|>"} {"text":"\/*\r\n * (c) Copyright Ascensio System SIA 2010-2017\r\n *\r\n * This program is a free software product. You can redistribute it and\/or\r\n * modify it under the terms of the GNU Affero General Public License (AGPL)\r\n * version 3 as published by the Free Software Foundation. In accordance with\r\n * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect\r\n * that Ascensio System SIA expressly excludes the warranty of non-infringement\r\n * of any third-party rights.\r\n *\r\n * This program is distributed WITHOUT ANY WARRANTY; without even the implied\r\n * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For\r\n * details, see the GNU AGPL at: http:\/\/www.gnu.org\/licenses\/agpl-3.0.html\r\n *\r\n * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,\r\n * EU, LV-1021.\r\n *\r\n * The interactive user interfaces in modified source and object code versions\r\n * of the Program must display Appropriate Legal Notices, as required under\r\n * Section 5 of the GNU AGPL version 3.\r\n *\r\n * Pursuant to Section 7(b) of the License you must retain the original Product\r\n * logo when distributing the program. Pursuant to Section 7(e) we decline to\r\n * grant you any rights under trademark law for use of our trademarks.\r\n *\r\n * All the Product's GUI elements, including illustrations and icon sets, as\r\n * well as technical writing content are licensed under the terms of the\r\n * Creative Commons Attribution-ShareAlike 4.0 International. See the License\r\n * terms at http:\/\/creativecommons.org\/licenses\/by-sa\/4.0\/legalcode\r\n *\r\n *\/\r\n\r\n#include \"SERIESDATA.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nnamespace XLS\r\n{\r\n\r\n\r\nSERIESDATA::SERIESDATA()\r\n{\r\n}\r\n\r\n\r\nSERIESDATA::~SERIESDATA()\r\n{\r\n}\r\n\r\n\r\n\/\/ (Number \/ BoolErr \/ Blank \/ Label)\r\nclass Parenthesis_SERIESDATA_2: public ABNFParenthesis\r\n{\r\n\tBASE_OBJECT_DEFINE_CLASS_NAME(Parenthesis_SERIESDATA_2)\r\npublic:\r\n\tBaseObjectPtr clone()\r\n\t{\r\n\t\treturn BaseObjectPtr(new Parenthesis_SERIESDATA_2(*this));\r\n\t}\r\n\r\n\tconst bool loadContent(BinProcessor& proc)\r\n\t{\r\n\t\treturn\tproc.optional() ||\r\n\t\t\t\tproc.optional() ||\r\n\t\t\t\tproc.optional() ||\r\n\t\t\t\tproc.optional